
    BVhjS                       U d Z ddlZddlmZ ddlmZmZmZmZmZ ddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZmZmZmZmZ ddlZddlmZ ddlZddl m!Z! ddl m"Z" dd	l m#Z# dd
l$m%Z% ddl&m'Z' ddl&m(Z( ddl&m)Z) ddl*m+Z+ ddl*m,Z, ddl*m-Z- ddl.m/Z/ ddl.m0Z0 ddl1m2Z2 ddl1m3Z3 ddl1m4Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl:m<Z< ddl:m=Z= ddl>m?Z? ddl>m@Z@ ddl>mAZB ddl>mCZC ddl>mDZD dd l>mEZE dd!l>mFZF dd"l>mGZG dd#l>mHZH dd$l>mIZI dd%l>mJZJ dd&l>mKZK dd'l>mLZM dd(l>mNZN dd)l>mOZO dd*l>mPZP dd+l>mQZQ dd,lRmSZS dd-lRmTZT dd.lRmUZU dd/lRmVZV dd0lRmWZW dd1lRmXZX dd2lRmYZY dd3lRmZZZ dd4lRm[Z[ dd5l\m]Z] dd6l\m^Z^ dd7l\m_Z_ dd8l`maZa dd9l`mbZb dd:l`mcZd dd;lemfZf dd<lgmhZh dd=lgmiZi dd>lgmjZj dd?lgmkZk dd@lgmlZl ddAlgmmZm ddBlgmnZn ddClompZp ddDlqmrZr ddElsmtZt ddFlumvZv  edGedHef   I      Zw edJ      Zx edKeydL   I      ZzdMe{fdNZ|	 ddOl}m|Z| dMee{   fdPZ	 ddQlmZ dMe{fdRZdMe{fdSZdMe{fdTZdMe{fdUZ	 ddVee   dMej                  e   fdWZ evdX      dMefdY       ZdZeeef   d[eIj                  dMeee(j                  f   fd\Z evd]g ^      d_e'j                  d`e'j                  dMdfda       Z evd]g^      	 	 dd`e'j                  d_e'j                  dce{dde{dMdf
de       Z	 	 dd`e'j                  d_e'j                  dce{dde{dMdf
dfZdgdLdhe,j&                  die,j&                  dMdfdjZdkZdle'j                  dMdfdmZdnZdle'j                  dMdfdoZdMe{fdpZdMe{fdqZdMe{fdrZdMe{fdsZdt ZdMe{fduZdMe{fdvZd dwZdxeeMjB                  ee   f   dMeeMjB                  ee   f   fdyZdzeeMjB                  ee   f   dMeeMjB                  ee   f   fd{ZdzeeMjB                  ee   f   dMeeMjB                  ee   f   fd|ZdxeeMjB                  ee   f   dMeeMjB                  ee   f   fd}Zd~eeg e{f   e{f   dMeewgewf   fdZe	jR                  	 ddejT                  deye~   deeee   df   dMed   fd       ZdewdMewfdZdeyex   dMeyex   fdZdewdMewfdZdezdMezfdZdedMeewgewf   fdZdewdMewfdZ	 ddedMeedHef   ged   f   fdZdewdMewfdZdee   dedMe{fdZdewdMewfdZdMeeeef      fdZdMeeeef      fdZdezdMezfdZdezdMezfdZdewdMewfdZdewdMewfdZdewdMewfdZe	 ddeyex   de{dMeyex   fd       Ze	 	 dddde{dMeeyex   geyex   f   fd       Z evd      	 	 ddeeyex      de{dMeeeyex   geyex   f   eyex   f   fd       ZdewdMewfdZdezdMezfdZdedMeewgewf   fdZddedMeewgewf   fdZdedHef   dMed   fdZdewdMewfdZe	 	 	 ddedHef   dee+j                     de{de{dMed   f
d       Ze	 	 	 	 ddddee+j                     de{de{dMeedHef   ged   f   f
d       Z	 	 	 	 ddeedHef      dee+j                     de{de{dMeeedHef   ged   f   ed   f   f
dZ	 	 ddee   de{dMeedHef   ged   f   fdZdewdMewfdZdedHef   dMed   fdZedewdMewfd       ZedezdMeez   fd       Zdeezewf   dMeezewf   fdZeZdezdMezfdZːddZ̐d	dZ͐d	dZdewdMewfdZdewdMewfdZdewdMewfdZdeeeeef      dMeedHef   ged   f   fdZ ejj                  dd       evd      	 	 d
de{deeeef      dMe{fdĄ              Ze	jR                  de{dMed   fdń       ZAe	jR                  dMed   fdƄ       Ze	jR                  dMed   fdǄ       Ze	jR                  dMed   fdȄ       Ze	jR                  dMed   fdɄ       Z G dʄ d˫      Z G d̄ dͫ      Z G d΄ de5j                        ZdewdMewfdЄZdedMeewgewf   fd҄Zde{dMeewgewf   fdԄZdedMeewgewf   fdՄZdedMeewgewf   fdքZdedMeewgewf   fdׄZdedMeewgewf   fd؄ZdedMeewgewf   fdلZdedMeewgewf   fdڄZdedMeeezewf   geezewdf   f   fd܄ZdedHef   dMeezgezf   fdބZdedMeewgewf   fd߄ZdedMeewgewf   fdZdedMeedHef   ged   f   fdZdedMeezgezf   fdZd Z G d d      ZdbZ evd       G d dLebjT                               Z e       aee   ed<    ej                         Zd Z evd      	 	 	 ddedededee+j                     dee+j                     dMeeefj                     eefj                     f   fd       Zdedle'j                  dMee(j                     fdZd[eIj                  dedMdfdZe	jR                  d        Z G d d      Ze	jR                  de{dMed   fd       Z G d d      Z evd      d d       Zy# e~$ r Y Ow xY w# e$ r 	 ddQlmZ n# e$ r Y nw xY wY ^w xY w(  zTest utils for tensorflow.    N)OrderedDict)IterableIteratorCallable
CollectionSequence)AnycastUnionOptionaloverloadTypeVar)parameterizeddescriptor_pool)message)text_format)flags)	graph_pb2)node_def_pb2)
tensor_pb2)
config_pb2)meta_graph_pb2)rewriter_config_pb2)pywrap_sanitizers)tf2)
device_lib)pywrap_tf_session)session)	v2_compatforward_compatibility_horizon)backprop)context)def_function)_test_metrics_util)configdevice)dtypes)errors)errors_impl)gpu_util)importer)indexed_slices)ops)random_seed)sparse_tensor)tensor)tensor_shape)tensor_util)
tfrt_utils)versions)	array_ops)control_flow_util)control_flow_util_v2)gen_sync_ops)gradients_impl)math_ops)
script_ops)summary_ops_v2)	variables)
ragged_ops)ragged_tensor)ragged_tensor_value)_pywrap_stacktrace_handler)
googletest)
tf_logging)
server_lib)_pywrap_util_port)compat)deprecation)nest)tf_decorator)
tf_inspect)traceback_utils)collections_abc)np_where)compare)	tf_export_F.)bound_T_TCTensorFlowTestCasereturnc                       yNF r[       U/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/framework/test_util.pyis_xla_enabledr^   s   s    	r\   )r^   c                       y Nr[   r[   r\   r]   is_mlir_bridge_enabledra      s    	r\   )ra   c                  *    t        j                         S )zCheck if ASAN is enabled.)r   is_asan_enabledr[   r\   r]   rc   rc          		*	*	,,r\   c                  *    t        j                         S )zCheck if MSAN is enabled.)r   is_msan_enabledr[   r\   r]   rf   rf      rd   r\   c                  *    t        j                         S )zCheck if TSAN is enabled.)r   is_tsan_enabledr[   r\   r]   rh   rh      rd   r\   c                  *    t        j                         S )zCheck if UBSAN is enabled.)r   is_ubsan_enabledr[   r\   r]   rj   rj      s    		+	+	--r\   excludec           	         t        j                  t        j                         D cg c]  }t	        |      j
                   c}      t        j                  | D cg c]  }t	        |      j
                   c}      z
  S c c}w c c}w r`   )collectionsCountergcget_objectstype__name__)rk   objs     r]   _get_object_count_by_typert      sc     9IJ#49--JKA#49--ABCDJAs   B B
ztest.gpu_device_namec                      t        j                         D ]2  } | j                  dk(  st        j                  | j
                        c S  y)a  Returns the name of a GPU device if available or a empty string.

  This method should only be used in tests written with `tf.test.TestCase`.

  >>> class MyTest(tf.test.TestCase):
  ...
  ...   def test_add_on_gpu(self):
  ...     if not tf.test.is_built_with_gpu_support():
  ...       self.skipTest("test is only applicable on GPU")
  ...
  ...     with tf.device(tf.test.gpu_device_name()):
  ...       self.assertEqual(tf.math.add(1.0, 2.0), 3.0)

  GPU )r   list_local_devicesdevice_typerI   as_strname)xs    r]   gpu_device_namer}      s@      ((* #a}}]]166""# 
r\   expected_opsgraphc           	         i }t        t        j                  |j                               }|j                  D ]q  }|j
                  | v s| |j
                     |j                  k7  r5t        d|j
                  d| |j
                     d|j                        |||j
                  <   s t        | j                               t        |j                               k7  r-t        d| j                         d|j                               |S )a  Assert all expected operations are found.

  Args:
    expected_ops: `dict<string, string>` of op name to op type.
    graph: Graph to check.

  Returns:
    `dict<string, node>` of node name to node.

  Raises:
    ValueError: If the expected ops are not present in the graph.
  zExpected op for node z is different. z vs z+Not all expected ops are present. Expected z, found )
r
   r   GraphDefas_graph_defnoder{   op
ValueErrorsetkeys)r~   r   
actual_opsgdr   s        r]   assert_ops_in_graphr      s     13*I 2 2 45"gg #dyyL 	dii	 DGG	+))\$))%<dggG H 	H"j# 				Z__%6!77
"''):??+<> ? ?	r\   ztest.assert_equal_graph_def)v1expectedactualc                 "    t        || dd       y)a9  Asserts that two `GraphDef`s are (mostly) the same.

  Compares two `GraphDef` protos for equality, ignoring versions and ordering of
  nodes, attrs, and control inputs.  Node names are used to match up nodes
  between the graphs, so the naming of nodes must be consistent. This function
  ignores randomized attribute values that may appear in V2 checkpoints.

  Args:
    expected: The `GraphDef` we expected.
    actual: The `GraphDef` we have.

  Raises:
    AssertionError: If the `GraphDef`s do not match.
    TypeError: If either argument is not a `GraphDef`.
  T)checkpoint_v2hash_table_shared_nameNassert_equal_graph_def)r   r   s     r]   assert_equal_graph_def_v2r      s    & 046r\   Fr   r   c                      t        | |||       y)a  Asserts that two `GraphDef`s are (mostly) the same.

  Compares two `GraphDef` protos for equality, ignoring versions and ordering of
  nodes, attrs, and control inputs.  Node names are used to match up nodes
  between the graphs, so the naming of nodes must be consistent.

  Args:
    actual: The `GraphDef` we have.
    expected: The `GraphDef` we expected.
    checkpoint_v2: boolean determining whether to ignore randomized attribute
      values that appear in V2 checkpoints.
    hash_table_shared_name: boolean determining whether to ignore randomized
      shared_names that appear in HashTableV2 op defs.

  Raises:
    AssertionError: If the `GraphDef`s do not match.
    TypeError: If either argument is not a `GraphDef`.
  Nr   )r   r   r   r   s       r]   assert_equal_graph_def_v1r      s    2 =/1r\   c                    t        | t        j                        s!t        dt	        |       j
                  z        t        |t        j                        s!t        dt	        |      j
                  z        |rt        |        t        |       |rt        |        t        |       t        j                  | j                         |j                               }|rt        t        j                  |            y )Nz'Expected tf.GraphDef for actual, got %sz)Expected tf.GraphDef for expected, got %s)
isinstancer   r   	TypeErrorrq   rr   _strip_checkpoint_v2_randomized_strip_hash_table_shared_namer   EqualGraphDefWrapperSerializeToStringAssertionErrorrI   rz   )r   r   r   r   diffs        r]   r   r     s     
FI..	/
=L))* + +	Hi00	1
?N++, - - #F+#H-!&)!(+		/	/0H0H0J080J0J0L
N$	
t,
-- 
r\   testerabc                    | j                  t        |j                        t        |j                               |j                  j                         }|D ]5  }|j                  |   }|j                  |   }t	        t
        t        j                     t        j                  |            }|r |       } |       }	| j                  t        |j                  j                        t        |j                  j                               t        |j                  j                  |j                  j                        D ]9  \  }
}|j                  |
       |	j                  |       | j                  ||	       ; $| j                  ||       8 |j!                  d       |j!                  d       t#        |j$                  |j$                  d       | j                  |j$                  j&                  |j$                  j&                         |j!                  d       |j!                  d       | j                  ||       y)z?Compares MetaGraphDefs `a` and `b` in unit test class `tester`.collection_defT)r   	graph_defN)assertEqualr   r   r   r
   rq   r   Messager0   get_collection_proto_typelen
bytes_listvaluezipParseFromStringassertProtoEquals
ClearFieldr   r   r7   )r   r   r   collection_keyska_valueb_value
proto_typea_protob_protoa_value_itemb_value_items               r]   assert_meta_graph_protos_equalr   ,  s    	S))*C0@0@,AB$$))+/ +aq!Gq!Gd7??+S-J-J1-MNJgg
g  &&
'W-?-?-E-E)FH*-g.@.@.F.F.5.@.@.F.F+H 3
&<--  '2	3 '*!+& ,, ,,  akkF1;;//1E1EF ,,{,,{1a r\   z_temp_[0-9a-z]{32}/partr   c                    | j                   D ]  }g }|j                  D ]  }t        t        j                  |j                  |   j
                        }|s7t        |j                        dk(  sP|j                  d   }|sbt        j                  t        j                  t              |      s|j                  |        |D ]  }|j                  |=   y N   r   )r   attrr
   r   TensorProtor3   r   
string_valrematchrI   as_bytes_SHARDED_SAVE_OP_PATTERNappend)r   r   delete_keysattr_keyattr_tensor_valueattr_tensor_string_values         r]   r   r   \  s    nn dKII '

 
 $))H"5"<"<>	s#4#?#?@AE#4#?#?#B $HHV__%=>-/


X
&'   
))H
r\   zhash_table_[0-9a-z\-]+c                 6   | j                   D ]  }g }|j                  dk(  rcd|j                  v rUt        j                  t        j                  t              |j                  d   j                        r|j                  d       |D ]  }|j                  |=   y )NHashTableV2shared_name)
r   r   r   r   r   rI   r   _TABLE_SHARED_NAME_PATTERNsr   )r   r   r   r   s       r]   r   r   o  s    nn dKww-MTYY$>	&//"<=))M*,,
.=) 
))H
r\   c                  *    t        j                         S r`   )rH   IsGoogleCudaEnabledr[   r\   r]   r   r   z  s    		.	.	00r\   c                  *    t        j                         S r`   )rH   IsBuiltWithROCmr[   r\   r]   r   r   ~      		*	*	,,r\   c                  *    t        j                         S r`   )rH   IsBuiltWithXLAr[   r\   r]   r   r     s    		)	)	++r\   c                  *    t        j                         S r`   )rH   IsBuiltWithNvccr[   r\   r]   r   r     r   r\   c                    | j                  d      rt        j                         S | j                  d      rt        j                         S | j                  d      s| j                  d      rt        j                         S | j                  d      rt        j
                         S | j                  d      rt        j                         S J d| z          )Narmaarch64ppcpowerpcx86s390xzUnknown CPU target: )
startswithrH   IsAArch32AvailableIsAArch64AvailableIsPowerPCAvailableIsX86AvailableIsSystemZAvailabletargets    r]   IsCPUTargetAvailabler     s    u//11#//116#4#4Y#?//11++--!//11/&//r\   c                  *    t        j                         S r`   )rH   GpuSupportsHalfMatMulAndConvr[   r\   r]   r   r     s    		7	7	99r\   c                  *    t        j                         S r`   )rH   IsMklEnabledr[   r\   r]   r   r     s    		'	'	))r\   c                  ,    t        j                          y r`   )rD   InstallStacktraceHandlerr[   r\   r]   InstallStackTraceHandlerr     s    557r\   input_tensorc                     g dg dg dd}t        | t        j                        r/| j                  j                  }t        j                  | ||         S t        |       }||   D cg c]  }| |   	 c}S c c}w )zConverts the input from the NHWC format to NCHW.

  Args:
    input_tensor: a 3-, 4-, or 5-D tensor, or an array representing shape

  Returns:
    converted tensor or shape array
  )r      r   )r      r   r   )r      r   r   r   )r   r      r   
tensor_libTensorshapendimsr8   	transposer   r   new_axesr   r   s       r]   
NHWCToNCHWr     sn     |@(j//0$$E|Xe_==E%-e_5LO555s   (A7input_shape_or_tensorc                    g dg dd}t        | t        j                        }|r| j                  j	                         n| }|d   dz  dk7  rt        d      |dxx   dz  cc<   |j                  d       |t        |         }|r,t        j                  | |      }t        j                  ||      S |D cg c]  }||   	 c}S c c}w )a  Transforms the input from the NHWC layout to NCHW_VECT_C layout.

  Note: Does not include quantization or type conversion steps, which should
  be applied afterwards.

  Args:
    input_shape_or_tensor: a 4- or 5-D tensor, or an array representing shape

  Returns:
    tensor or shape array transformed into NCHW_VECT_C

  Raises:
    ValueError: if last dimension of `input_shape_or_tensor` is not evenly
        divisible by 4.
  )r   r   r   r   r   )r   r   r   r   r   r   r      r   r   zPLast dimension of input must be evenly divisible by 4 to convert to NCHW_VECT_C.)r   r   r   r   as_listr   r   r   r8   reshaper   )r   permutations	is_tensor
temp_shapepermutationtr   s          r]   NHWCToNCHW_VECT_Cr    s    $ %);<,.
0A0AB) 
 !!))+-  ^a1
	  R.Q.AS_-+/<Aq+..#./aJqM///s   6Cc                 z   g dg dd}t        | t        j                        }|r| j                  j	                         n| }|d   dk7  rt        d      |t        |         }|dd D cg c]  }||   	 }}|dxx   |d   z  cc<   |r,t        j                  | |      }t        j                  ||      S |S c c}w )a  Transforms the input from the NCHW_VECT_C layout to NHWC layout.

  Note: Does not include de-quantization or type conversion steps, which should
  be applied beforehand.

  Args:
    input_shape_or_tensor: a 5- or 6-D tensor, or an array representing shape

  Returns:
    tensor or shape array transformed into NHWC

  Raises:
    ValueError: if last dimension of `input_shape_or_tensor` is not 4.
  )r   r   r   r   r   )r   r   r   r   r   r   r   r   r   z(Last dimension of NCHW_VECT_C must be 4.N)
r   r   r   r   r  r   r   r8   r   r  )r   r  r  input_shaper  r   
nhwc_shaper  s           r]   NCHW_VECT_CToNHWCr    s    " %);<,.
0A0AB) 
 !!))+-  _
?
@@S-.+(3CR(891A9*9R.KO#.1;?AQ
++ :s   *B8c                     g dg dd}t        | t        j                        r/| j                  j                  }t        j                  | ||         S t        |       }||   D cg c]  }| |   	 c}S c c}w )zConverts the input from the NCHW format to NHWC.

  Args:
    input_tensor: a 4- or 5-D tensor, or an array representing shape

  Returns:
    converted tensor or shape array
  )r   r   r   r   )r   r   r   r   r   )r   r   r   r   s       r]   
NCHWToNHWCr     sl     /2(j//0$$E|Xe_==E%-e_5LO555s   %A4	conditionc                 ,     dt         dt         f fd}|S )zSkips the decorated function if condition is or evaluates to True.

  Args:
    condition: Either an expression that can be used in "if not condition"
      statement, or a callable whose result should be a boolean.

  Returns:
    The wrapped function
  fnrX   c                       fd}|S )Nc                  D    t              r        }n}|s | i |S y r`   )callable)argskwargsskipr  r  s      r]   wrapperz.skip_if.<locals>.real_skip_if.<locals>.wrapper"  s/    	)	{4"6"" r\   r[   )r  r  r  s   ` r]   real_skip_ifzskip_if.<locals>.real_skip_if   s    # Nr\   rS   )r  r  s   ` r]   skip_ifr    s    
r 
b 
 
r\   test_obj
error_typemessagesc           	   #      K   |rt        j                  |      }	 d y# |$ rU|rt        fd|D              r4| j                  dj	                  t              t                           n Y dydww xY ww)al  Context manager to skip cases not considered failures by the tests.

  Note that this does not work if used in setUpClass/tearDownClass.
  Usage in setUp/tearDown works fine just like regular test methods.

  Args:
    test_obj: A test object provided as `self` in the test methods; this object
      is usually an instance of `unittest.TestCase`'s subclass and should have
      `skipTest` method.
    error_type: The error type to skip. Note that if `messages` are given, both
      `error_type` and `messages` need to match for the test to be skipped.
    messages: Optional, a string or list of strings. If `None`, the test will be
      skipped if `error_type` matches what is raised; otherwise, the test is
      skipped if any of the `messages` is contained in the message of the error
      raised, and `error_type` matches the error raised.

  Yields:
    Nothing.
  Nc              3   8   K   | ]  }|t              v   y wr`   str).0r   es     r]   	<genexpr>z skip_if_error.<locals>.<genexpr>M  s     E7c!f,E   zSkipping error: {}: {})rK   flattenanyskipTestformatrq   r"  )r  r  r  r$  s      @r]   skip_if_errorr+  /  sn     2 ||H%H		 sEHEE077QQHI Js+   A>! A>A;AA61A>6A;;A>r  c                     | S z%No-op. TODO(b/74620627): Remove this.r[   )r  s    r]   enable_c_shapesr.  S  s    	)r\   clsc                     | S r-  r[   r/  s    r]   with_c_shapesr2  X  s    	*r\   c                       fd}|S )ak  Decorator for enabling CondV2 and WhileV2 on a test.

  Note this enables using CondV2 and WhileV2 after running the test class's
  setup/teardown methods.

  In addition to this, callers must import the while_v2 module in order to set
  the _while_v2 module in control_flow_ops.

  Args:
    fn: the function to be wrapped

  Returns:
    The wrapped function
  c                      t         j                  }dt         _        	  | i ||t         _        S # |t         _        w xY wNT)r9   ENABLE_CONTROL_FLOW_V2)r  r  enable_control_flow_v2_oldr  s      r]   r  z'enable_control_flow_v2.<locals>.wrapperm  s?    !2!I!I/3,L  1K.1K.   1 >r[   r  r  s   ` r]   enable_control_flow_v2r:  ]  s     L 
.r\   c                 D   t         j                  r| S | j                  j                         j	                         D ]b  \  }}t        |      s|j                  t        j                  j                        s<t        |dd      rJt        | |dz   t        |             d | S )a  Adds methods that call original methods with WhileV2 and CondV2 enabled.

  Note this enables CondV2 and WhileV2 in new methods after running the test
  class's setup method.

  In addition to this, callers must import the while_v2 module in order to set
  the _while_v2 module in control_flow_ops.

  If a test function has _disable_control_flow_v2 attr set to True (using the
  @disable_control_flow_v2 decorator), the v2 function is not generated for it.

  Example:

  @test_util.with_control_flow_v2
  class ControlFlowTest(test.TestCase):

    def testEnabledForV2(self):
      ...

    @test_util.disable_control_flow_v2("b/xyzabc")
    def testDisabledForV2(self):
      ...

  Generated class:
  class ControlFlowTest(test.TestCase):

    def testEnabledForV2(self):
      ...

    def testEnabledForV2WithControlFlowV2(self):
      // Enable V2 flags.
      testEnabledForV2(self)
      // Restore V2 flags.

    def testDisabledForV2(self):
      ...

  Args:
    cls: class to decorate

  Returns:
    cls with new test methods added
  _disable_control_flow_v2FWithControlFlowV2)r9   r6  __dict__copyitemsr  r   unittest
TestLoadertestMethodPrefixgetattrsetattrr:  r/  r{   r   s      r]   with_control_flow_v2rG  x  s    X --J\\&&(..0 NkdE++<<=E5u=c4--/Ee/LM	N
 
*r\   
unused_msgc                 &    dt         dt         fd}|S )a  Decorator for a function in a with_control_flow_v2 enabled test class.

  Blocks the function from being run with v2 control flow ops.

  Args:
    unused_msg: Reason for disabling.

  Returns:
    The wrapped function with _disable_control_flow_v2 attr set to True.
  funcrX   c                     d| _         | S r5  )r<  rJ  s    r]   r  z(disable_control_flow_v2.<locals>.wrapper  s    $(D!Kr\   r  )rH  r  s     r]   disable_control_flow_v2rM    s    B 2  
.r\   c                       fd}|S )zForce-enable outputing all intermediates from functional control flow ops.

  Args:
    fn: the function to be wrapped

  Returns:
    The wrapped function
  c                      t         j                  }dt         _        	  | i ||t         _        S # |t         _        w xY wr5  )r:   /_EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)r  r  output_all_intermediates_oldr  s      r]   r  z0enable_output_all_intermediates.<locals>.wrapper  sF    LL !KOH'   ' J
& Jr8  r[   r9  s   ` r]   enable_output_all_intermediatesrR    s    ' 
.r\   warmup_iters.Nc                 D     dt         dt        f   dt         d   f fd}|S )a*  Decorator for asserting that no new Python objects persist after a test.

  Returns a decorator that runs the test multiple times executing eagerly,
  first as a warmup and then to let objects accumulate. The warmup helps ignore
  caches which do not grow as the test is run repeatedly.

  Useful for checking that there are no missing Py_DECREFs in the C exercised by
  a bit of Python.

  Args:
    warmup_iters: The numer of warmup iterations, excluded from measuring.

  Returns:
    A decorator function which can be applied to the test function.
  f.rX   rT  c                 @     d fd}t        j                   |      S )Nc           
         t        j                         5  t        j                          d}d}t	        | j
                  d      r-| j
                  j                  }| j
                  j                  }n@| j
                  j                  j                  }| j
                  j                  j                  }t              D ]  } | g|i |  | j                          t               }t        j                          t        j                          j                         }t        t        j                  ||            }t        j                          rHt        j"                         j$                  D ci c]!  }|t'        t        j(                  |            # }	}t        d      D ]  } | g|i |  | j                          t        j                          rwt        j"                         j$                  D ]U  }
t        j(                  |
      }	j+                  |
d      }t'        |      |kD  rt-        d|
|t'        |      |fz        ~~
~W ~	t        j                          t        t        j                  ||            |z
  }t        j                          j                         |z
  }|r
J d|z         |rJ dt/        |      z         t        j0                          ddd       yc c}w # 1 sw Y   yxY w)	zDWarms up, gets object counts, runs the test, checks for new objects.Nr+   )rk   r   r   zACollection %s increased in size from %d to %d (current items %s).z.The following functions were newly created: %sz,The following objects were newly created: %s)r$   
eager_modero   disablehasattr_outcomer+   skippedresultrange
doCleanupsrt   collectlist_function_namesget_referentsr0   has_default_graphget_default_graphrm   r   get_collectiongetr   r"  enable)selfr  r  test_errorstest_skipped_obj_count_by_typeregistered_function_names
collectioncollection_sizes_beforecollection_keysize_beforeleftover_functionsrV  rS  s                r]   	decoratorzLassert_no_new_pyobjects_executing_eagerly.<locals>.wrap_f.<locals>.decorator  s    Y


 4==(+,,+..,,,33+--55, |$ 	#A
D
"4
"6
"	# 	 67


 %,OO$5$I$I$K!
 6$$[,?A   " !$ 5 5 7 C C% #c00<==%
! % q 	#A
D
"4
"6
"	# 	   " # 5 5 7 C C n++N;J155naHK:,"2!;JLMN N  &


 &((lCE 	 OO1136OO 	% 	 <	 % % 	$:!"#	$$ 			sY YP%QY Ys   EK02&K+E
K0+K00K9ri  rW   rX   NrL   make_decorator)rV  rt  rS  s   ` r]   wrap_fz9assert_no_new_pyobjects_executing_eagerly.<locals>.wrap_f  s    [x &&q)44r\   r   r	   )rS  rx  s   ` r]   )assert_no_new_pyobjects_executing_eagerlyrz    s/    &]5c" ]5x	': ]5~ 
-r\   rV  c                 <     d fd}t        j                   |      S )a\  Decorator for asserting that no new Tensors persist after a test.

  Mainly useful for checking that code using the Python C API has correctly
  manipulated reference counts.

  Clears the caches that it knows about, runs the garbage collector, then checks
  that there are no Tensor or Tensor-like objects still around. This includes
  Tensors to which something still has a reference (e.g. from missing
  Py_DECREFs) and uncollectable cycles (i.e. Python reference cycles where one
  of the objects has __del__ defined).

  Args:
    f: The test case to run.

  Returns:
    The decorated test case.
  c                 0   dt         fdt        fdt        j                         D              }t	        t         t        j                               }t        j                         j                  }t        j                         j                         5  |t        j                         _	        |r't        j                         5   	| fi |}ddd       n	 	| fi |}ddd       t        j
                         j                          t        j                          t        j                         D cg c]  } |      rt        |      |vr| }}|r"t!        dt#        |      t%        |      fz        S # 1 sw Y   xY w# 1 sw Y   xY wc c}w )z>Finds existing Tensors, runs the test, checks for new Tensors.rX   c                     	 t        | t        j                  t        j                  t
        j                  t
        j                  f      S # t        t        f$ r Y yw xY wrZ   )
r   r   r   r@   Variabler4   	DimensionTensorShapeReferenceErrorAttributeErrorrs   s    r]   _is_tensorflow_objectzGassert_no_new_tensors.<locals>.decorator.<locals>._is_tensorflow_objectd  sY    #%,,i.@.@'11<3K3KMN 	N n- s   AA
 
AAc              3   F   K   | ]  } |      st        |        y wr`   )id)r#  rs   r  s     r]   r%  z;assert_no_new_tensors.<locals>.decorator.<locals>.<genexpr>m  s$      K/DS/I3Ks   !!Nz)%d Tensors not deallocated after test: %s)boolr   ro   rp   r
   r$   executing_eagerlyr0   re  
_graph_keyGraph
as_defaultrY  _clear_cachesra  r  r   r   r"  )
ri  r  tensors_beforeoutside_executed_eagerlyoutside_graph_keyr^  rs   tensors_afterr  rV  s
           @r]   rt  z(assert_no_new_tensors.<locals>.decoratora  sp   d   K>>+K KN#D'*C*C*EF --/::				! #+<c(	!! 	%T$V$&	% 	% 4"6"# OO##%JJL~~' %"S'*G 	M  G
m

m
K  
 
 M#	% 	%# #s*   0F
E;F5F;F	 FFri  rW   rv  rV  rt  s   ` r]   assert_no_new_tensorsr  N  s    &&P 
	$	$Q		22r\   objectsidxc                 D  	 dt         dt        t            dt        t           fd		 ddt         dt        t            dt        dt        f	fddt         dt
        t        t        t           f   d	t
        t        t        f   dt        t         d
f   dd f
	fddt        dt
        t        t        t           f   d	t
        t        t        f   dt        t        d
f   dt        t           f
fd| |   }i }i } |||| ||	f       |D ]  } |||d      s y y)Nrs   denylistrX   c                     t        |      dkD  ryt        j                  |       rdt        j                  |       d   v ry|D ]  }|| u s y | |u ryy)zDTests whether an object should be omitted from the dependency graph.d   z<depth limit>ztest_util.pyr   z<test code>N)r   rM   isframegetframeinfo)rs   r  r   s      r]   get_ignore_reasonz0_find_reference_cycle.<locals>.get_ignore_reason  sb    
8}s#	:2237:	: 	
c hr\   Fleaves_onlyc                     | |      r"dj                   | |      t        |             S t        j                  |       r$dj                  t        j                  |             S t        j
                  |       rdj                  | j                        S |r$dj                  t        |       t        |             S t        | t              r2dj                  t        |       | D cg c]  } ||d       c}      S t        | t              r2dj                  t        |       | D cg c]  } ||d       c}      S t        | t              r2d	j                  t        |       t        | j                                     S t        j                  |       r9d
j                  t        |       | j                  t        | j                              S dj                  t        |       t        |             S c c}w c c}w )a  Returns a custom human-readable summary of obj.

    Args:
      obj: the value to describe.
      denylist: same as denylist in get_ignore_reason.
      leaves_only: boolean flag used when calling describe recursively. Useful
        for summarizing collections.
    z{}{}z	frame: {}z
module: {}z{}, {}zlist({}): {}T)r  ztuple({}): {}zdict({}): {} keyszfunction({}) {}; globals ID: {})r*  rq   rM   r  r  ismodulerr   r  r   listtupledictr   r   
isfunction__globals__)rs   r  r  r$  describer  s       r]   r  z'_find_reference_cycle.<locals>.describe  s    h']],S(;T#YGG#
 7 7 <==			S	!  ..	tCy"S'22c4 $$sGsK!hq(=KM 	Mc5!%%sGsK!hq(=KM 	Mc4 "))"S'3sxxz?CC  %077sGS\\2coo#68 	8 tCy"S'22 L Ls   %G4
'G9
r   reprs.c                    t        j                  |       }||fz   }t        |       }|D ]S  } 
||      t        |      }||vrg ||<   |||   vs)||   j                  |        ||||        	||      ||<   U y)a  Builds a reference graph as <referrer> -> <list of referents>.

    Args:
      obj: The object to start from. The graph will be built by recursively
        adding its referrers.
      graph: Dict holding the graph to be built. To avoid creating extra
        references, the graph holds object IDs rather than actual objects.
      reprs: Auxiliary structure that maps object IDs to their human-readable
        description.
      denylist: List of objects to ignore.
    N)ro   get_referrersr  r   )rs   r   r  r  	referrersobj_idrr_idbuild_ref_graphr  r  s           r]   r  z._find_reference_cycle.<locals>.build_ref_graph  s    "   %I9,&HWF .	1h	'	/!uu%+t$
+

V
$
!UE8
4 H-%+.r\   elpathc                     | |vry||    D ]j  }||v rSt        j                  d       ||fz   D ]3  }t        j                  |j                  |dt        |      z                5  y |||||fz         sj y y)z8Finds and prints a single cycle in the dependency graph.NzReference cycle sample:zunknown object TF)loggingerrorrg  r"  )r  r   r  r  r  p
find_cycles         r]   r  z)_find_reference_cycle.<locals>.find_cycle  s     
2Y 	
d/0 	BA
--		!%6Q%?@
A	Batqd{3 r\   r[   TF)	r	   r   r   r"  r  r  intr  r  )
r  r  rs   r   r  r   r  r  r  r  s
         @@@@r]   _find_reference_cycler    sY   S JsO  $ @E 3 3$S/ 38< 3
 3D..#tCy.!. #s(^. c3h	.
 .>
#tCy.! #s(^ #s(O	
 ~( 	# "%%#uegue=N&.&M N a!UE2& 
r\   c                      d fd}|S )aU  Test method decorator to assert that no garbage has been created.

  Note that this decorator sets DEBUG_SAVEALL, which in some Python interpreters
  cannot be un-set (i.e. will disable garbage collection for any other unit
  tests in the same file/shard).

  Args:
    f: The function to decorate.

  Returns:
    The decorated function.
  c                 t   t        j                          t        j                         }t        j                  t         j                         t        j
                          t        t         j                        } 
| fi |}t        j
                          t        t         j                        }||kD  r:t        t         j                  |d       D ]  \  }}t        |dd      dk(  s|dz  } ||kD  rt        j                  d       t        t         j                  |d       D ]r  \  }}	 t        j                  d|t        t         j                        |z
         dt        fd	}t        j                  d
 ||             t        j                  ddj                  t        j                  |      D 	cg c]
  }	 ||	       c}	             t        j                  ddj                  t        j                  |      D 	cg c]
  }	 ||	       c}	             t        j                  dt!        |             t        j                  d       t        j                  |       t        j                  d       t        j                  t#        |             u ||kD  r-t'        ||      D ]  }t)        t         j                  |      s n | j+                  ||       t        j                  |       t        j,                          |S c c}	w c c}	w # t$        $ r t        j                  d       Y w xY w)z>Sets DEBUG_SAVEALL, runs the test, and checks for new garbage.N
__module__rw   astr   zyThe decorated test created work for Python's garbage collector, likely due to a reference cycle. New objects in cycle(s):zObject %d of %drX   c                 J    d| j                   j                  t        |       fz  S )Nz<%s %d>)	__class__rr   r  r  s    r]   _safe_object_strzFassert_no_garbage_created.<locals>.decorator.<locals>._safe_object_str)  s      6 63@@@r\   z  Object type: %sz  Referrer types: %s, z  Referent types: %sz  Object attribute names: %sz  Object __str__:z  Object __repr__:z!(Exception while printing object))ro   rZ  	get_debug	set_debugDEBUG_UNCOLLECTABLEra  r   garbage	enumeraterD  r  r  r"  joinr  rc  dirrepr	Exceptionr_  r  r   rh  )ri  r  previous_debug_flagsprevious_garbager^  new_garbageirs   r  refrV  s             r]   rt  z,assert_no_garbage_created.<locals>.decorator  s   JJL<<>LL''(JJL2::tvFJJLbjj/K%%bjj)9):;< &!S3b)U2

+
 %%mmFG bjj)9):;< =&!S	=
--)1BJJ*::<As A --+-=c-B
C
--$dii464D4DS4IJS#C(J'LM --$dii464D4DS4IJS#C(J'LM --6C
A
--+
,
--

--,
-
--S	
"'=2 %%%{3 ! Q/
 	%{3 LL%&IIKM7 K K  	=
--;
<	=s2   .B	L7L=LLBL
LL76L7r  r[   r  s   ` r]   assert_no_garbage_createdr    s     ;z 
r\   c                      d }g }t        | j                         |      D ]9  \  }}t        |t              s|g}|j	                  |D cg c]  }||f c}       ; t        j                  | D cg c]  }t        |       c}S c c}w c c}w )a  Generate combinations based on its keyword arguments.

  Two sets of returned combinations can be concatenated using +.  Their product
  can be computed using `times()`.

  Args:
    **kwargs: keyword arguments of form `option=[possibilities, ...]` or
      `option=the_only_possibility`.

  Returns:
    a list of dictionaries for each combination. Keys in the dictionaries are
    the keyword argument names.  Each key has one value - one of the
    corresponding keyword argument values.
  c                     | d   S Nr   r[   )r   s    r]   <lambda>z+_combine_named_parameters.<locals>.<lambda>^  s
    !A$ r\   )key)sortedr@  r   r  r   	itertoolsproductr   )r  sort_by_keycombinationsr  valuesr   r^  s          r]   _combine_named_parametersr  O  s     +.0,FLLN< <kc6fd#xf6:%#u:;<
 -6,=,=|,L	M&+f
	MM ;	Ms   	B
1Bc                     t        di | }g }|D ]  }t        |t              sJ dj                  |j	                         D cg c]n  \  }}dj                  dj                  t        t        j                  |            dj                  t        t        j                  t        |                        p c}}      }|j                  t        t        |j	                               ddj                  |      fgz                 |S c c}}w )a5  Generate combinations based on its keyword arguments using combine().

  This function calls combine() and appends a testcase name to the list of
  dictionaries returned. The 'testcase_name' key is a required for named
  parameterized tests.

  Args:
    **kwargs: keyword arguments of form `option=[possibilities, ...]` or
      `option=the_only_possibility`.

  Returns:
    a list of dictionaries for each combination. Keys in the dictionaries are
    the keyword argument names.  Each key has one value - one of the
    corresponding keyword argument values.
  rw   z_{}_{}testcase_namez_test{}r[   )r  r   r   r  r@  r*  filterr"  isalnumr   r  )r  r  named_combinationscombinationr  r   r{   s          r]   (generate_combinations_with_testcase_namer  h  s    $ +4V4,46! 
:kk;///77 &++- C 	s{{C 89s{{CJ ?@	B D
 ""$%y//5678	9:
: 
s   A3Dc                 6   t         }t        |       D ]  }|j                  t        j                  j
                        r,|j                  d      s|j                  d      s
|dk(  s|dk(  rYt        | |d      }t        |      srt        | | ||              | S )zCExecute all test methods in the given class with and without eager.testSkipEagertest_skip_eagertest_session
test_scopeN)	run_in_graph_and_eager_modesr  r   rA  rB  rC  rD  r  rE  r/  base_decoratorr{   r   s       r]    run_all_in_graph_and_eager_modesr    s    /.#h 	0dOOH//@@A()*Ct$Ec4./	0 
*r\   c                 6   t         }t        |       D ]  }|j                  t        j                  j
                        r,|j                  d      s|j                  d      s
|dk(  s|dk(  rYt        | |d      }t        |      srt        | | ||              | S )z=Execute all test methods in a given class in v1 and v2 modes.r  r  r  r  N)	run_in_v1_v2r  r   rA  rB  rC  rD  r  rE  )r/  r  r{   r   s       r]   run_class_in_v1_v2r    s    .#h -dOOH//@@A()*3d#DD>C~d+,- 
*r\   c                       fd}|S )a  Decorator for enabling nested_function_shape_inference on a test.

  This function returns a decorator intended to be applied to test methods in
  a `tf.test.TestCase` class. Doing so will set nested_function_shape_inference,
  reset the context, execute the test, then reset the context to the state
  it was in prior to this test.

  Example:

  class MyTest(test.TestCase):

    @enable_nested_function_shape_inference
    def testFoo(self):
      ...

  Args:
    fn: the function to be wrapped.

  Returns:
    The wrapped function.
  c                     t        j                         j                  j                         r | i |S t        j                         j                  j	                  d       	  | i |t        j                         j                  j	                  d       S # t        j                         j                  j	                  d       w xY wNTF)r   r'   &enable_nested_function_shape_inferencer   resetr  r  r  s     r]   r  z7enable_nested_function_shape_inference.<locals>.wrapper  s    ||~<<BBD   	LLN99??EI  lln;;AA%Helln;;AA%H   $B /Cr[   r9  s   ` r]   r  r    s    .	I 
.r\   c                       fd}|S )a
  Decorator for enabling quantized_dtypes_training on a test.

  This function returns a decorator intended to be applied to test methods in
  a `tf.test.TestCase` class. Doing so will set quantized_dtypes_training,
  reset the context, execute the test, then reset the context to the state
  it was in prior to this test.

  Example:

  class MyTest(test.TestCase):

    @enable_quantized_dtypes_training
    def testFoo(self):
      ...

  Args:
    fn: the function to be wrapped.

  Returns:
    The wrapped function.
  c                     t        j                         j                  j                         r | i |S t        j                         j                  j	                  d       	  | i |t        j                         j                  j	                  d       S # t        j                         j                  j	                  d       w xY wr  )r   r'    enable_quantized_dtypes_trainingr   r  r  s     r]   r  z1enable_quantized_dtypes_training.<locals>.wrapper  s    ||~66<<>   	LLN3399$?C  lln55;;EBelln55;;EBr  r[   r9  s   ` r]   r  r    s    .	C 
.r\   c                       fd}|S )zReturns the same fn. This will be removed once all usages are removed.

  Args:
    fn: the function to be wrapped.

  Returns:
    The wrapped function.
  c                       | i |S r`   r[   r  s     r]   r  z,enable_eager_op_as_function.<locals>.wrapper  s    tvr\   r[   r9  s   ` r]   enable_eager_op_as_functionr    s     
.r\   only_as_functionc                      y r`   r[   r/  r  s     r]   with_eager_op_as_functionr        
 r\   c                      y r`   r[   r  s     r]   r  r    r  r\   ztest.with_eager_op_as_functionc                 V    dt         t           dt         t           fd}|  ||       S |S )zReturns the same class. This will be removed once all usages are removed.

  Args:
    cls: class to decorate.
    only_as_function: unused argument.

  Returns:
    cls
  r/  rX   c                     | S r`   r[   r1  s    r]   rt  z,with_eager_op_as_function.<locals>.decorator'  s    Jr\   )rq   rU   )r/  r  rt  s      r]   r  r    s4    T"X $r(  	_S>	r\   c                       fd}|S )a  Decorator for enabling graph_building_optimization on a test.

  This function returns a decorator intended to be applied to test methods in
  a `tf.test.TestCase` class. Doing so will enable graph_building_optimization,
  execute the test, then reset the feature flag to its default value.

  Example:

  class MyTest(test.TestCase):

    @enable_graph_building_optimization
    def testFoo(self):
      ...

  Args:
    fn: the function to be wrapped.

  Returns:
    The wrapped function.
  c                     t        j                         j                  j                         r | i |S t        j                         j                  j	                  d       	  | i |t        j                         j                  j	                  d       S # t        j                         j                  j	                  d       w xY wr  )r   r'   graph_building_optimizationr   r  r  s     r]   r  z3enable_graph_building_optimization.<locals>.wrapperF  s    ||~11779   	LLN..44T:>  lln0066u=elln0066u=r  r[   r9  s   ` r]   "enable_graph_building_optimizationr  0  s    ,	> 
.r\   c                    t        j                         j                  j                         r| S | j                  j                         j                         D ]e  \  }}t        |      s|j                  t        j                  j                        s|j                  d      sMt        | |dz   t        |             g | S )a  Adds methods with graph_building_optimization enabled to the test suite.

  Example:

  @test_util.add_graph_building_optimization_tests
  class FooTest(test.TestCase):

    def testBar(self):
      ...

  Generated class:
  class FooTest(test.TestCase):

    def testBar(self):
      ...

    def testBarWithGraphBuildingOptimization(self):
      // Enable graph_building_optimization
      testBar(self)
      // Disable graph_building_optimization

  Args:
    cls: class to decorate.

  Returns:
    cls with new test methods added.
  	benchmarkWithGraphBuildingOptimization)r   r'   r  r   r>  r?  r@  r  r   rA  rB  rC  rE  r  rF  s      r]   %add_graph_building_optimization_testsr
  T  s    : \\^//557J\\&&(..0 9kdE	,,==	>		%c499079	9 
*r\   c                     t        d      S )a   Decorator for a function in a with_eager_op_as_function enabled test class.

  Blocks the function from being run with eager_op_as_function enabled.

  Args:
    unused_msg: Reason for disabling.

  Returns:
    The wrapped function with _disable_eager_op_as_function attr set to True.
  F)execute_func)_disable_test)rH  s    r]   disable_eager_op_as_functionr  }  s     
E	**r\   flagc                 ,     dt         dt         f fd}|S )a  Decorator for setting XLA_FLAGS prior to running a test.

  This function returns a decorator intended to be applied to test methods in
  a `tf.test.TestCase` class. Doing so will allow users to set any xla flags
  exposed via the XLA_FLAGS environment variable, execute the test, then reset
  the XLA_FLAGS to the state it was in prior to this test.

  Example:

  class MyTest(test.TestCase):

    @set_xla_env_flag(flag='--xla_gpu_enable_fast_min_max=false')
    def testFoo(self):
      ...

  Args:
    flag: The xla flag to be set in the XLA_FLAGS env variable.

  Returns:
    A decorator which sets the configured flag in XLA_FLAGS for the decorated
    function.
  rV  rX   c                 F     t        j                          fd       }|S )Nc                  8   t         j                  j                  d      }}|r|dz   |z   }|t         j                  d<   	  | i ||t         j                  d= S |t         j                  d<   S # |t         j                  d= w |t         j                  d<   w xY w)N	XLA_FLAGS osenvironrg  )r  r  original_xla_flagsnew_xla_flagsrV  r  s       r]   	decoratedz6set_xla_env_flag.<locals>.decorator.<locals>.decorated  s    ::>>+6m	%+.@@ -bjj7$!&!%jj%$6"**[
! %jj%$6"**[
!s   A0 0)B)	functoolswraps)rV  r  r  s   ` r]   rt  z#set_xla_env_flag.<locals>.decorator  s&    __Q7 7 r\   r  )r  rt  s   ` r]   set_xla_env_flagr    s    02 " & 
r\   rJ  c                      t        j                         rt        d      t        j                  dd      t        j                         dddt        ddf fd	              }|S )
a  Run a test case in v1 graph mode and inside tf.function in eager mode.

  WARNING: This decorator can only be used in test cases that statically checks
  generated graph. Attempting to evaluate graph or function results via.
  session.run() or self.evaluate() will fail.

  WARNING: This decorator can only be used for test cases that inherit from
  absl.testing.parameterized.TestCase.

  Args:
    func: Test case function to be decorated.

  Returns:
    Decorated test case function.
  z<`run_in_graph_mode_and_function` only supports test methods.)	_v1_graphv1_graph)	_functionfunctionri  rW   run_moderX   Nc                     |dk(  r8t        j                         j                         5    gi  d d d        y |dk(  rt        j                   fd       }t        j                         }|j                         5  t        j                         5   |        d d d        d d d        t        j                  |       y t        d|z        # 1 sw Y   y xY w# 1 sw Y   AxY w# 1 sw Y   ExY w)Nr   r"  c                       g i  y r`   r[   )r  rJ  r  ri  s   r]   function_in_eagerzLbuild_as_function_and_v1_graph.<locals>.decorated.<locals>.function_in_eager  s    T#D#F#r\   zUnknown run mode %s)	r0   r  r  r%   r"  r$   rY  dismantle_graphr   )ri  r#  r  r  r&  graph_for_eager_testrJ  s   ` ``  r]   r  z1build_as_function_and_v1_graph.<locals>.decorated  s     :99;!!# $T#D#F#$ $	Z	$ $
 !YY[**, g.@.@.B  	./,x788$ $   s/   CC/C##C/C #C,	(C//C8)rM   isclassr   r   named_parametersr  r  r"  rJ  r  s   ` r]   build_as_function_and_v1_graphr,    s}    & 
FH H !!";";=??49 99
 9 =90 
r\   c                      t        j                  ddg      t        j                         dddt        f fd              }|S )z-Execute the test in async mode and sync mode.)AsyncT)rw   Fri  rW   
async_modec                    |r9t        j                  t         j                        5   | g|i | d d d        y t        j                  t         j                        5   | g|i | d d d        y # 1 sw Y   y xY w# 1 sw Y   y xY wr`   )r$   execution_modeASYNCSYNC)ri  r/  r  r  rV  s       r]   rt  z-run_in_async_and_sync_mode.<locals>.decorator  s     !!'--0 !	$   ! ! !!',,/ !	$   ! !! !! !s   A6 B6A?B)r   r*  r  r  r  r  s   ` r]   run_in_async_and_sync_moder4    sP     !!?K"@A??1!* ! !  B! 
r\   r'   use_gpuassert_no_eager_garbagec                      y r`   r[   rJ  r'   r5  r6  s       r]   r  r         r\   c                      y r`   r[   r8  s       r]   r  r    r9  r\   c                 `    dt         dt        f   dt         d   ffd}|  ||       S |S )a	  Execute the decorated test with and without enabling eager execution.

  This function returns a decorator intended to be applied to test methods in
  a `tf.test.TestCase` class. Doing so will cause the contents of the test
  method to be executed twice - once normally, and once with eager execution
  enabled. This allows unittests to confirm the equivalence between eager
  and graph execution (see `tf.compat.v1.enable_eager_execution`).

  For example, consider the following unittest:

  ```python
  class MyTests(tf.test.TestCase):

    @run_in_graph_and_eager_modes
    def test_foo(self):
      x = tf.constant([1, 2])
      y = tf.constant([3, 4])
      z = tf.add(x, y)
      self.assertAllEqual([4, 6], self.evaluate(z))

  if __name__ == "__main__":
    tf.test.main()
  ```

  This test validates that `tf.add()` has the same behavior when computed with
  eager execution enabled as it does when constructing a TensorFlow graph and
  executing the `z` tensor in a session.

  `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and
  `run_in_graph_and_eager_modes` are available decorators for different
  v1/v2/eager/graph combinations.


  Args:
    func: function to be annotated. If `func` is None, this method returns a
      decorator the can be applied to a function. If `func` is not None this
      returns the decorator applied to `func`.
    config: An optional config_pb2.ConfigProto to use to configure the session
      when executing graphs.
    use_gpu: If True, attempt to run as many operations as possible on GPU.
    assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage
      collector and asserts that no extra garbage has been created when running
      the test with eager execution enabled. This will fail if there are
      reference cycles (e.g. a = []; a.append(a)). Off by default because some
      tests may create garbage for legitimate reasons (e.g. they define a class
      which inherits from `object`), and because DEBUG_SAVEALL is sticky in some
      Python interpreters (meaning that tests which rely on objects being
      collected elsewhere in the unit test file will not work). Additionally,
      checks that nothing still has a reference to Tensors that the test
      allocated.

  Returns:
    Returns a decorator that will run the decorated test method twice:
    once by constructing and executing a graph in a session and once with
    eager execution enabled.
  rV  .rX   rT  c                      t        j                         rt        d      d fd}t        j                   |      S )Nzr`run_in_graph_and_eager_modes` only supports test methods. Did you mean to use `run_all_in_graph_and_eager_modes`?c                 .   t        j                  d
j                         	 t        j                         5  | j                  d      5  | j                  j                         D ]!  }|j                  dk(  s| j                  }i } n | j                  }t        	      } |di |5   
| gi | d d d        d d d        d d d        d
fd}r(t        j                          t!        t#        |            }| j%                          d | _        t        j(                         }|j+                         5  t        j,                         5  | j                  d      5  | j/                           || fi | d d d        d d d        d d d        t        j0                  |       y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# t        j                  j                  $ r Y  w xY w# 1 sw Y   wxY w# 1 sw Y   {xY w# 1 sw Y   xY w)	NzRunning %s in GRAPH mode.
graph_modeXLATestCase)r5  r'   c                     t        j                  dj                         s+t        j                  d      5   | gi | d d d        y  | gi | y # 1 sw Y   y xY w)NzRunning %s in EAGER mode./device:CPU:0r  inforr   r0   r)   )ri  r  r  rV  r5  s     r]   run_eagerlyzWrun_in_graph_and_eager_modes.<locals>.decorator.<locals>.decorated.<locals>.run_eagerlyl  se    0!**=zz/* %d$T$V$% % D
"4
"6
"% %   AA%rY  r[   ru  )r  rC  rr   r$   r>  subTestr  mror   r  r  rA  caseSkipTestr0   reset_default_graphr  r  tearDown_tempdirr  r  rY  setUpr'  )ri  r  r  class_session_funcsession_kwargsrD  r(  r6  r'   rV  r5  s    `      r]   r  zBrun_in_graph_and_eager_modes.<locals>.decorator.<locals>.decoratedY  s   ll.

;! 	%4<<#= 	% **, Bf-/!\\l!n	B  ,,L!'&AN-n- %d$T$V$%	% 	% # 
!!+%k24
 mmodm !YY[

)
)
+$



$ ,,|
$$
 	

D#F#$ $ $ 
./A% %	% 	% 	% 	% ]]## .$ $ $ $ $ $s   G G
-F782F7*F+7F7?GG <HG?#G3=G?H+F40F77G 	<GGG G0/G03G<8G??H	HHru  rM   r)  r   rL   rw  )rV  r  r6  r'   r5  s   ` r]   rt  z/run_in_graph_and_eager_modes.<locals>.decoratorS  sF    !DE E.0 .0` &&q)44r\   ry  )rJ  r'   r5  r6  rt  s    ``` r]   r  r    s>    D658CH% 65(9*= 65p 
T?	r\   device_to_usec                 H     dt         dt        f   dt         d   f fd}|S )a  Execute the decorated test in v1 and v2 modes.

  The overall execution is similar to that of `run_in_graph_and_eager_mode`.

  Args:
    device_to_use: A string in the following format: "/device:CPU:0".
    assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage
      collector and asserts that no extra garbage has been created when running
      the test with eager execution enabled. This will fail if there are
      reference cycles (e.g. a = []; a.append(a)). Off by default because some
      tests may create garbage for legitimate reasons (e.g. they define a class
      which inherits from `object`), and because DEBUG_SAVEALL is sticky in some
      Python interpreters (meaning that tests which rely on objects being
      collected elsewhere in the unit test file will not work). Additionally,
      checks that nothing still has a reference to Tensors that the test
      allocated.

  Returns:
    A decorator that runs a given test in v1 and v2 modes.
  rV  .rX   rT  c                      d}t         |      r S d fd}t        j                   |      }d|j                  |<   |S )Nwrapped_with_v1_v2_decoratorc                 |   t        j                  dj                         	 | j                  d      5  t	        j
                           | gi | d d d        dfd}r(t        j                          t        t        |            }| j                          d | _        t        j                          t	        j                          | j                  d      5  | j!                           || fi | d d d        y # 1 sw Y   xY w# t        j                  j                  $ r Y w xY w# 1 sw Y   y xY w)NzRunning %s in V1 mode.V1_modec                     t        j                  dj                         r+t        j                        5   | gi | d d d        y  | gi | y # 1 sw Y   y xY w)NzRunning %s in V2 mode.rB  )ri  r  r  rR  rV  s     r]   run_v2zBrun_in_v1_v2.<locals>.decorator.<locals>.decorated.<locals>.run_v2  se    -qzz:zz-( %d$T$V$% % D
"4
"6
"% %rE  V2_moderu  )r  rC  rr   rF  r    disable_v2_behaviorrA  rH  rI  r0   rJ  r  r  rK  rL  enable_v2_behaviorrM  )ri  r  r  rY  r6  rR  rV  s    `  r]   r  z2run_in_v1_v2.<locals>.decorator.<locals>.decorated  s   ll+QZZ8\\)$ 	#

'
'
)
D
"4
"6
"	## 
!!&%f-/
 mmodm	""$<<	" 

tv 5	# 	# ]]## . s4   D !DD  D2DD D/.D/2D;Tru  )r[  rL   rw  r>  )rV  decorator_tagr  tf_decoratedr6  rR  s   `   r]   rt  zrun_in_v1_v2.<locals>.decorator  sG    2Mq- hB  ..q)<L+/L-(r\   ry  )rR  r6  rt  s   `` r]   r  r    s-    2)8CH% )(9*= )V 
r\   c                 :      fd}t        j                   |      S )Nc                  H    t        j                         s  i S g }g t               D ]R  \  }}t        |t        j
                  t        j                  f      s1|j                  |       j                  |       T  fd}t        j                  ||g       S )Nc                  \    t              }t        |       D ]
  \  }}|||<     |i S r`   )r  r   )inner_tensor_argsmy_argsr  nr  rV  kwdstensor_indicess       r]   inner_fz:py_func_if_in_function.<locals>.decorated.<locals>.inner_f  s@    T
gn&78 $!Q
 4  r\   )r0   inside_functionr  r   r   r   r@   r~  r   r>   py_func)r  re  tensor_argsr  argrg  rf  rV  s   ``    @r]   r  z)py_func_if_in_function.<locals>.decorated  s     FHK "ND/ !3	C*++Y-?-?@	A3a !
! g{B77r\   rv  rV  r  s   ` r]   py_func_if_in_functionrm    s    8& 
	$	$Q		22r\   c                      d fd}|S )a  Runs the decorated test twice--once as is, once inside a tf.function.

  This allows you to run a test both in eager execution and inside a
  tf.function, exercising the two execution modes supported in tf 2.0. The test
  assertions are automatically done inside tf.py_funcs, and tf.function ensures
  that they run in the proper order and with the proper side effects.

  Currently variable creation is not supported in tests annotated with this
  decorator since it's tricky to ensure the variable doesn't get repeatedly
  created when retracing the tf.function.

  Args:
    f: the test method to be decorated

  Returns:
    The decorated test method, which will run both in eager and inside a
    tf.function.
  c                       d fd}t        j                         5   |         t        j                  |d              d d d        y # 1 sw Y   y xY w)Nc                        i  y r`   r[   )r  rV  re  s   r]   bound_fz;also_run_as_tf_function.<locals>.decorated.<locals>.bound_f  s    r\   F)	autographrX   N)r$   rY  r%   r"  )r  re  rq  rV  s   `` r]   r  z*also_run_as_tf_function.<locals>.decorated  sG     
			 8i 6lGu578 8 8s   $AArs  r[   rl  s   ` r]   also_run_as_tf_functionrt    s    (
8 
r\   c                      y r`   r[   rL  s    r]   deprecated_graph_mode_onlyrv        r\   c                      y r`   r[   rL  s    r]   rv  rv    rw  r\   c                     t        j                         r j                  j                  d      }|t	         dt        |              j                  j                         j                         D ]Q  \  }}t        |      s|j                  t        j                  j                        s<t	         |t        |             S  S  fd}t        j                   |      S )a4  Execute the decorated test in graph mode.

  This is a decorator intended to be applied to tests that are not compatible
  with eager mode. When this decorator is applied, the test body will be run in
  an environment where API calls construct graphs instead of executing eagerly.

  `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and
  `run_in_graph_and_eager_modes` are available decorators for different
  v1/v2/eager/graph combinations.

  Args:
    func: function or class to be annotated.
      If `func` is a function this returns the decorator applied to `func`.
      If `func` is a unit test class this returns that class with the decorator
      applied to all test functions within that class.

  Returns:
    Returns a function or class that will run the decorated test(s)
    in graph mode.
  rM  c                      t        j                         r&t        j                         5   | i |cd d d        S  | i |S # 1 sw Y   y xY wr`   )r$   r  r>  r  r  rJ  s     r]   r  z-deprecated_graph_mode_only.<locals>.decorated?  sT      " %T$V$% % 4"6""% %s   AA)rM   r)  r>  rg  rE  rv  r?  r@  r  r   rA  rB  rC  rL   rw  )rJ  setupr{   r   r  s   `    r]   rv  rv    s    , MMg&EdG7>?}}))+113 ?e
5/
//(-->>
?d6u=>?
 K# 
	$	$T9	55r\   c                     t         }t        |       D ]]  }|j                  t        j                  j
                        r|dk(  r2t        | |d      }t        |      sKt        | | ||             _ | S )z+Execute all tests in a class in graph mode.r  N)	rv  r  r   rA  rB  rC  rD  r  rE  r  s       r]   %run_all_in_deprecated_graph_mode_onlyr~  L  sj    -.#h 0dOOH//@@ACt$Ec4./0 
*r\   c                 D    s	drdnd fd|  |       S S )a  Execute the decorated test only if running in the specified mode.

  This function is intended to be applied to tests that exercise functionality
   that belongs to either only v2, or v1.
   If the test is run in the mode opposite of the specified one, it will simply
   be skipped.

   It shouldn't be used directly, instead, use the `run_v1_only` or
   `run_v2_only` wrappers that call it.

  `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and
  `run_in_graph_and_eager_modes` are available decorators for different
  v1/v2/eager/graph combinations.

  Args:
    func: function to be annotated. If `func` is None, this method returns a
      decorator the can be applied to a function. If `func` is not None this
      returns the decorator applied to `func`.
    v2: a boolean value indicating whether the test should be skipped in v2,
      or v1.
    reason: string giving a reason for limiting the test to a particular mode.

  Returns:
    A decorator that will skip the test method in the specified version.
  zTest is only compatible with zv2 r   c                     t        j                         rOt        j                         D ]5  }|j                  j                  d      }|!t         d |               S   S  fd}t        j                   |      S )NrM  c                 v    t        j                         }|rr|sr| j                          | g|i |S r`   )r   enabledr)  )ri  r  r  tf2_enabledrV  reasonv2s       r]   r  z2_run_vn_only.<locals>.decorator.<locals>.decorated  s:    kkm KB
--
''''r\   )	rM   r)  rq   rG  r>  rg  rE  rL   rw  )rV  r/  r|  r  rt  r  r  s   `   r]   rt  z_run_vn_only.<locals>.decoratorv  s~    ! ! #  )
!Wi.
/
h h( ((I66r\   r[   )rJ  r  r  rt  s    ``@r]   _run_vn_onlyr  Y  s6    4 
,bUd,CDF78 
T?	r\   c                     t        |d|       S )z2Only execute the test if Tensorflow is in v1 mode.FrJ  r  r  r  )r  rJ  s     r]   run_v1_onlyr    s    	4E&	99r\   c                     t        | d|      S )z2Only execute the test if Tensorflow is in v2 mode.Tr  r  )rJ  r  s     r]   run_v2_onlyr    s    	4D	88r\   c                 T     t        j                         rt        d      d fd}|S )aJ  Execute the decorated test only if a GPU is available.

  This function is intended to be applied to tests that require the presence
  of a GPU. If a GPU is absent, it will simply be skipped.

  Args:
    func: function to be annotated.

  Returns:
    Returns a function that will conditionally skip the decorated test method.
  z*`run_gpu_only` only supports test methods.c                 R    t               s| j                  d        | g|i |S )NzTest requires GPUis_gpu_availabler)  ri  r  r  rJ  s      r]   r  zrun_gpu_only.<locals>.decorated  s+    
mm'(&t&v&&r\   r  rM   r)  r   r+  s   ` r]   run_gpu_onlyr    s,     
A
BB' 
r\   c                 T     t        j                         rt        d      d fd}|S )aT  Execute the decorated test only if a GPU is available.

  This function is intended to be applied to tests that require the presence
  of a CUDA GPU. If a CUDA GPU is absent, it will simply be skipped.

  Args:
    func: function to be annotated.

  Returns:
    Returns a function that will conditionally skip the decorated test method.
  z+`run_cuda_only` only supports test methods.c                 V    t        d      s| j                  d        | g|i |S )NT)	cuda_onlyzTest requires CUDA GPUr  r  s      r]   r  z run_cuda_only.<locals>.decorated  s-    d+
mm,-&t&v&&r\   r  r  r+  s   ` r]   run_cuda_onlyr    s,     
B
CC' 
r\   c                 T     t        j                         rt        d      d fd}|S )a%  Execute the decorated test only if a physical GPU or TPU is available.

  This function is intended to be applied to tests that require the presence
  of a physical GPU or TPU. It complies with the following rules:
  - If a GPU is available, the test will run on the GPU.
  - If a GPU is absent and a TPU is available, the test will run on the TPU.
  - If both GPU and TPU are absent, the test will be skipped.

  Args:
    func: function to be annotated.

  Returns:
    Returns a function that will conditionally skip the decorated test method.
  z,`run_gpu_or_tpu` only supports test methods.c                     t        j                  d      r | dg|i |S t        j                  d      r | dg|i |S | j                  d       y )Nrv   TPUzTest requires GPU or TPU)r'   list_physical_devicesr)  r  s      r]   r  z!run_gpu_or_tpu.<locals>.decorated  sZ    ##E*$////##E*$////MM,-r\   r  r  r+  s   ` r]   run_gpu_or_tpur    s,      
C
DD. 
r\   horizonsc                        st        d       D ]3  }|t        |      dk(  rt        d |D              r't        d|z         dt        dt        f   dt        d   f fd	}|S )
aO  Executes the decorated test with the specified forward-compat horizons.

  Args:
    *horizons: A list of (year, month, day) tuples.  If the list includes
      `None`, then the test will also be run with no forward-compatibility
      horizon set.

  Returns:
    A decorator that will execute the test with the specified horizons.
  zExpected at least one horizon.r   c              3   <   K   | ]  }t        |t                y wr`   )r   r  )r#  r|   s     r]   r%  z6with_forward_compatibility_horizons.<locals>.<genexpr>  s     &Kaz!S'9&Ks   zBad horizon value: %rrV  .rX   rT  c                 ~     t        j                         rt        d       fd}t        j                   |      S )NzA`with_forward_compatibility_horizons` only supports test methods.c                      D ]1  }|	 | i | |\  }}}t        |||      5   | i | d d d        3 y # 1 sw Y   >xY wr`   r!   )r  r  horizonyearmonthdayrV  r  s         r]   r  zIwith_forward_compatibility_horizons.<locals>.decorator.<locals>.decorated  sc     '?
T
V
&
4,T5#> tv 
 s	   	9A	rQ  )rV  r  r  s   ` r]   rt  z6with_forward_compatibility_horizons.<locals>.decorator  s=    ! 0 1 1 &&q)44r\   )r   r   allr   r	   )r  r  rt  s   `  r]   #with_forward_compatibility_horizonsr    s{     

5
66 :g_\Q3&K7&K#K.899:
58CH% 5(9*= 5 
r\   z5Use `tf.config.list_physical_devices('GPU')` instead.ztest.is_gpu_availabler  min_cuda_compute_capabilityc                 `   ~ 	 t        j                         D ]@  }|j                  dk(  st        j                  |      }|j
                  xs d}|r||k\  s@ y y# t        j                  $ r>t        fddD              st        j                  t                     Y dydww xY w)a  Returns whether TensorFlow can access a GPU.

  Warning: if a non-GPU version of the package is installed, the function would
  also return False. Use `tf.test.is_built_with_cuda` to validate if TensorFlow
  was build with CUDA support.

  For example,
  >>> gpu_available = tf.test.is_gpu_available()
  >>> is_cuda_gpu_available = tf.test.is_gpu_available(cuda_only=True)
  >>> is_cuda_gpu_min_3 = tf.test.is_gpu_available(True, (3,0))

  Args:
    cuda_only: limit the search to CUDA GPUs.
    min_cuda_compute_capability: a (major,minor) pair that indicates the minimum
      CUDA compute capability required, or None if no requirement.

  Note that the keyword arg name "cuda_only" is misleading (since routine will
  return true when a GPU device is available irrespective of whether TF was
  built with CUDA support or ROCm support. However no changes here because

  ++ Changing the name "cuda_only" to something more generic would break
     backward compatibility

  ++ Adding an equivalent "rocm_only" would require the implementation check
     the build type. This in turn would require doing the same for CUDA and thus
     potentially break backward compatibility

  ++ Adding a new "cuda_or_rocm_only" would not break backward compatibility,
     but would require most (if not all) callers to update the call to use
     "cuda_or_rocm_only" instead of "cuda_only"

  Returns:
    True if a GPU device of the requested kind is available.
  rv   )r   r   TFc              3   8   K   | ]  }|t              v   y wr`   r!  )r#  r|   r$  s     r]   r%  z#is_gpu_available.<locals>.<genexpr>N  s     9qqCF{9r&  )CUDAznot findN)r   rx   ry   r-   #compute_capability_from_device_desccompute_capabilityr,   NotFoundErrorr  r  r  r"  )r  r  local_devicegpu_infoccr$  s        @r]   r  r    s    V "557 		!	!U	*??M((2F*b4O.O 		"	" 9$899gmmCFs(   &A ,A A A B-/4B((B-c              #      K   | rt               rd}nd}t        j                  |      5  d ddd       y# 1 sw Y   yxY ww)&Uses gpu when requested and available./device:GPU:0rA  N)r  r0   r)   )r5  devs     r]   r)   r)   U  s=      !#
C
C
zz# 
	
 
 
s   'A7	AA Ac               #   V   K   t        d      5  d ddd       y# 1 sw Y   yxY ww)r  T)r5  Nr(   r[   r\   r]   r5  r5  `  s'      d 
	
 
 
s   )	)&)c               #   h   K   t        j                  d      5  d ddd       y# 1 sw Y   yxY ww)zForce the gpu to be used.r  Nr0   r)   r[   r\   r]   	force_gpur  g  +      zz/" 
	
 
 
   2&	2/2c               #   h   K   t        j                  d      5  d ddd       y# 1 sw Y   yxY ww)zForce the cpu to be used.rA  Nr  r[   r\   r]   	force_cpur  n  r  r  c               #      K   	 t        j                          d t        j                          y# t        j                          w xY ww)zEnables deterministic ops.N)r'   enable_op_determinismdisable_op_determinismr[   r\   r]   deterministic_opsr  u  s2     $
  "	
!!#F!!#s   A
1 A
AA
c                   (    e Zd ZdZdefdZdefdZy)CapturedWritesz=A utility class to load the captured writes made to a stream.capture_locationc                     || _         y r`   )r  )ri  r  s     r]   __init__zCapturedWrites.__init__  s
    ,Dr\   rX   c                     t        | j                        5 }dj                  |j                               }ddd       |S # 1 sw Y   S xY w)z+Get the captured writes as a single string.rw   N)openr  r  	readlines)ri  tmp_fileoutput_datas      r]   contentszCapturedWrites.contents  sE    	d##	$ 2GGH..01k22s    A  A
N)rr   r  __qualname____doc__r"  r  r  r[   r\   r]   r  r    s    E-s - r\   r  c                       e Zd ZdZd Zd Zy)FakeEagerSessiona  Fake session so tests that conditionally use placeholders can use eager.

  There are a number of tests that conditionally use placeholders for shape
  inference. The pattern is demonstrated here:

  ```python
  with self.cached_session() as sess:
    if static_shape:
      y = math_ops.matmul(x, ...)
      feed_dict = {}
    else:
      x_ph = array_ops.placeholder(...)
      y = math_ops.matmul(x_ph, ...)
      feed_dict = {x_ph: x}
    val = sess.run(y, feed_dict=feed_dict)
  ```

  Since the feed_dict is empty when not using placeholders we should be able to
  call self.evaluate(), however this requires rewriting the test case.
  This class should be considered a stop-gap solution to get tests running with
  eager with minimal changes to the actual test.
  c                     || _         y r`   )
_test_case)ri  	test_cases     r]   r  zFakeEagerSession.__init__  s	    DOr\   c                     |j                  di       }|rt        d      |s|rt        d      | j                  j                  |      S )a=  Evaluate `fetches`.

    Fail if additional args are specified.

    Args:
      fetches: A Tensor or a nested list/tuple of Tensors.
      *args: Positional arguments
      **kwargs: Keyword arguments

    Raises:
      RuntimeError: If args or kwargs are specified.

    Returns:
      Tensors as numpy values.
    	feed_dictzpfeed_dict is not supported when eager execution is enabled (in this case, sess.run(t) is shorthand for t.numpy()zuOptional args are not supported when eager execution is enabled (in this case, sess.run(t) is shorthand for t.numpy())popRuntimeErrorr  evaluate)ri  fetchesr  r  r  s        r]   runzFakeEagerSession.run  s_      

;+IBC C vBC C ??##G,,r\   N)rr   r  r  r  r  r  r[   r\   r]   r  r    s    . -r\   r  c                   "     e Zd ZdZ fdZ xZS )ErrorLoggingSessionz3Wrapper around a Session that logs errors in run().c                     	 t        |   |i |S # t        $ r>}t        |t        j
                        st        j                  t        |              d }~ww xY wr`   )	superr  r  r   r+   OutOfRangeErrorr  r  r"  )ri  r  r  r$  r  s       r]   r  zErrorLoggingSession.run  sQ    W[$)&))  6112c!fs    	A9AA)rr   r  r  r  r  __classcell__r  s   @r]   r  r    s    ;	 	r\   r  c                 :      fd}t        j                   |      S )a%  Disable autotuning during the call to this function.

  Some tests want to base assertions on a graph being isomorphic with a copy.
  To ensure this, this decorator disables autotuning.

  Args:
    func: Function to run with CuDNN autotuning turned off.

  Returns:
    Decorated function.
  c                     t         j                  j                  d      }dt         j                  d<   t         j                  j                  d      }d}|r|dz   |z   }|t         j                  d<    | i |}|t         j                  d= n|t         j                  d<   |t         j                  d= |S |t         j                  d<   |S )NTF_CUDNN_USE_AUTOTUNEfalser  z--xla_gpu_autotune_level=0r  r  )r  r  original_tf_cudnn_use_autotuner  r  r^  rJ  s         r]   r  z)disable_cudnn_autotune.<locals>.decorated  s    %'ZZ^^4K%L"*1BJJ&'40M(3.>m+BJJ{4"6"F&.
**,
-,Jbjj()"
**[
! M !3bjjMr\   rv  r+  s   ` r]   disable_cudnn_autotuner    s    , 
	$	$T9	55r\   descriptionc                     t        | t              s#t        dj                  t	        |                   dt
        dt
        fd}|S )Nz&'description' should be string, got {}rJ  rX   c                 :      fd}t        j                   |      S )zEnable constant folding during the call to this function.

    Some tests fail without constant folding.

    Args:
      func: Function to run with constant folding turned on.

    Returns:
      Decorated function.
    c                      t        j                         }t        j                  d        | i |}t        j                  |       |S rZ   )r    TF_GetXlaConstantFoldingDisabled TF_SetXlaConstantFoldingDisabled)r  r  original_varr^  rJ  s       r]   r  z^enable_tf_xla_constant_folding.<locals>.enable_tf_xla_constant_folding_impl.<locals>.decorated	  sA    &GGIl88?T$V$f88Fmr\   rv  r+  s   ` r]   #enable_tf_xla_constant_folding_implzKenable_tf_xla_constant_folding.<locals>.enable_tf_xla_constant_folding_impl	  s     &&tY77r\   )r   r"  r   r*  rq   rS   )r  r  s     r]   enable_tf_xla_constant_foldingr    sJ    	K	%
=DD[  8 8r 8* 
-,r\   r  c                 ,     dt         dt         f fd}|S )NrJ  rX   c                 >      fd}t        j                   |      S )Nc                      r | i |S y r`   r[   )r  r  r  rJ  s     r]   r  z;_disable_test.<locals>.disable_test_impl.<locals>.decorated	  s    	T$V$$ 
r\   rv  )rJ  r  r  s   ` r]   disable_test_implz(_disable_test.<locals>.disable_test_impl	  s    % &&tY77r\   r  )r  r  s   ` r]   r  r  	  s    8b 8R 8 
r\   c                 .    t                }t        |      S )z3Execute the test method only if xla is not enabled.r^   r  r  r  s     r]   disable_xlar  (	      #%%,	|	$$r\   c                 .    t                }t        |      S )z;Execute the test method only if MLIR bridge is not enabled.)ra   r  r  s     r]   disable_mlir_bridger  /	  s    +--,	|	$$r\   c                 .    t                }t        |      S )z4Execute the test method only if ASAN is not enabled.)rc   r  r  s     r]   disable_asanr  6	      $&&,	|	$$r\   c                 .    t                }t        |      S )z4Execute the test method only if MSAN is not enabled.)rf   r  r  s     r]   disable_msanr   =	  r  r\   c                 .    t                }t        |      S )z4Execute the test method only if TSAN is not enabled.)rh   r  r  s     r]   disable_tsanr  D	  r  r\   c                 .    t                }t        |      S )z5Execute the test method only if UBSAN is not enabled.)rj   r  r  s     r]   disable_ubsanr  K	  s    %'',	|	$$r\   unused_descriptionc                 \    dt         t        t        f   dt         t        t        d f   fd}|S )Ncls_or_funcrX   c                     t        j                  |       r%t        j                         ryt	        t
        |       S t	        t        dt        f   |       fd}t        j                  | |      S )z-Execute the test only if tfrt is not enabled.N.c                  >    t        j                         ry  | i |S r`   )r6   r  r{  s     r]   r  z:disable_tfrt.<locals>.disable_tfrt_impl.<locals>.decorated`	  s"    
t&v&
&r\   )
rM   r)  r6   r  r
   rV   r   r	   rL   rw  )r  r  rJ  s     @r]   disable_tfrt_implz'disable_tfrt.<locals>.disable_tfrt_implV	  s^     +&				C%%(38$k2d' ((i@@r\   )r   rV   rS   )r  r
  s     r]   disable_tfrtr  R	  s3    AU37^ Ac2tm8L A$ 
r\   rt  c                 4     dt         dt         f fd}|S )a  Generate class-level decorator from given method-level decorator.

  It is expected for the given decorator to take some arguments and return
  a method that is then called on the test method to produce a decorated
  method.

  Args:
    decorator: The decorator to apply.
    *args: Positional arguments
    **kwargs: Keyword arguments
  Returns: Function that will decorate a given classes test methods with the
    decorator.
  r/  rX   c                     t        |       D ]K  }t        | |      }t        |      s|j                  d      s-|dk7  s3t	        | |  i |             M | S )z-Apply decorator to all test methods in class.testr  )r  rD  r  r   rE  )r/  r{   r   r  rt  r  s      r]   all_test_methods_implz3for_all_test_methods.<locals>.all_test_methods_impl|	  sd    C >c4 e	%T__
~-T59d5f5e<=	>
 Jr\   )rV   )rt  r  r  r  s   ``` r]   for_all_test_methodsr  k	  s    "   
r\   c                 .    t                }t        |      S )z>This test is not intended to be run with XLA auto jit enabled.r  r  s     r]   no_xla_auto_jitr  	  r  r\   c                 &    dt         dt         fd}|S )NrJ  rX   c                 :      fd}t        j                   |      S )z-Allow fallback to TF even though testing xla.c                      t               r4t        j                  d      } | i |}t        j                  |       |S  | i |S r5  )r^   r   TF_SetXlaEnableLazyCompilation)r  r  	old_valuer^  rJ  s       r]   r  zFxla_allow_fallback.<locals>.xla_allow_fallback_impl.<locals>.decorated	  sM    		 &DDTJ	t&v&88CT$V$$r\   rv  r+  s   ` r]   xla_allow_fallback_implz3xla_allow_fallback.<locals>.xla_allow_fallback_impl	  s    
% &&tY77r\   r  )r  r  s     r]   xla_allow_fallbackr  	  s    8B 82 8" 
! r\   c                 >    dt         dt        f   dt         d   fd}|S )a  Execute test with TensorFloat-32 disabled.

  While almost every real-world deep learning model runs fine with
  TensorFloat-32, many tests use assertAllClose or similar methods.
  TensorFloat-32 matmuls typically will cause such methods to fail with the
  default tolerances.

  Args:
    description: A description used for documentation purposes, describing why
      the test requires TensorFloat-32 to be disabled.

  Returns:
    Decorator which runs a test with TensorFloat-32 disabled.
  rV  .rX   rT  c                 j     t        j                          fd       }t        j                   |      S )Nc                      t        j                         }	 t        j                  d        | i | t        j                  |       y # t        j                  |       w xY wrZ   )r'   !tensor_float_32_execution_enabled enable_tensor_float_32_execution)r  r  allowedrV  s      r]   r  zArun_without_tensor_float_32.<locals>.decorator.<locals>.decorated	  sN    88:g9//6	46//8//8s   A
 
A!)r  r  rL   rw  rl  s   ` r]   rt  z.run_without_tensor_float_32.<locals>.decorator	  s3    __Q9 9 &&q)44r\   ry  )r  rt  s     r]   run_without_tensor_float_32r   	  s+    $58CH% 5(9*= 5 
r\   c                 "    t        t        |       S )z:Execute all tests in a class with TensorFloat-32 disabled.)r  r   )r  s    r]   run_all_without_tensor_float_32r"  	  s    	9;	GGr\   c                 Z   t        j                         ru| j                  dk(  rft        j                  | d      } t        j                  |d      }t        j
                  | |g|i |}t        j                  || j                        S t        j                         ru| j                  dk(  rft        j                  | d      } t        j                  |d      }t        j
                  | |g|i |}t        j                  || j                        S t        j
                  | |g|i |S )a  Run matmul but cast float32 inputs to float64 if TensorFloat-32 is enabled.

  This effectively runs matmul without TensorFloat-32. It should only be used in
  tests when verifying some other op or functions works correctly, e.g. to test
  `tf.linalg.sqrtm` by matrix multiplying the output of the op by itself. In
  such cases, the matmul itself is not being tested so it's OK to run it with
  higher precision.

  If a matmul itself is being tested, or some other op which uses matmul, use
  `run_without_tensor_float_32` instead.

  This also casts complex64 inputs to complex128, since TensorFloat-32 can also
  be used with complex64

  Args:
    a: First input to tf.linalg.matmul
    b: Second input to tf.linalg.matmul
    args: Other positional arguments to tf.linalg.matmul
    **kwargs: Other keyword arguments to tf.linalg.matmul

  Returns:
    A tensor with the same type as `a`.
  float32float64	complex64
complex128)r'   r  dtyper=   r
   matmul)r   r   r  r  rets        r]   matmul_without_tf32r+  	  s    0 --/AGGy4Ha#Aa#A
//!Q
0
0
0C==agg&&//1agg6La&Aa&A
//!Q
0
0
0C==agg&&??1a1$1&11r\   c                       e Zd Zd Zy)EagerSessionWarnerc                     t        d      )NaC  Trying to access properties or call methods on the result of self.session(), self.cached_session(), etc while eager execution is enabled. If you're porting this test case to TF 2.0, either adapt the test to work with eager execution or insert a call to tf.disable_eager_execution() in the main() function of this test file.)r  )ri  r   s     r]   __getattr__zEagerSessionWarner.__getattr__	  s    
	 r\   N)rr   r  r  r/  r[   r\   r]   r-  r-  	  s    r\   r-  ztest.TestCasec                       e Zd ZdZdE fd	Z fdZe fd       Z fdZd Z	de
fdZej                  dee   fd	       ZdFdZ	 	 dFdZej(                  ej*                  d
fdZdGdZd Zd Zdeej8                  ej<                  d
f   fdZej                  	 	 	 	 dHde e!jD                     de e#jH                     de%de%dee&jN                     f
d       Z(ej                  	 	 	 	 dHde e!jD                     de e#jH                     de%de%dee&jN                     f
d       Z)ej                   e*jV                  d
d      	 	 	 	 dHde e!jD                     de e#jH                     de%de%dee&jN                     f
d              Z, G d de-      Z.	 	 dFde/de0f   de e1e0df      de e2e
e0f      de.fd Z3e4dGd!       Z5e4dGd"       Z6d# Z7e4dGd$       Z8d% Z9d& Z:dId'Z;	 	 	 	 dJd(Z<e4dId)       Z=e4	 	 	 	 	 	 	 	 	 dKd*       Z>e4dId+       Z?e4dGd,       Z@e4dGd-       ZAe4d.        ZBe4d/        ZCe4d0        ZDe4d1        ZEdLd2ZFe4	 	 dMd3       ZGe4d4        ZHe4d5        ZIej                  d6        ZJd7 ZKeLj                  fd8ZNdGd9ZOdGd:ZPe4dG fd;	       ZQd< ZRd= ZSdGd>ZTdNd?ZUeVj                  j                  ZYeVj                  j                  Z[ej                  d@e&jN                  de%de%dee&jN                     fdA       Z\de e!jD                     de e#jH                     de%de&jN                  fdBZ]	 	 	 	 dOde e!jD                     de e#jH                     de%dCe%de&jN                  f
dDZ^ xZ_S )PrW   z2Base class for tests that need to test TensorFlow.c                    t         |   |       t        j                          t	               rit        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d       t               rdt        j                         _        n#t               dt        j                         _        g | _        d | _        d | _        d | _        d| _        y )N2r   FT)r  r  rN   disable_traceback_filteringr^   r   TF_SetXlaAutoJitModeTF_SetXlaMinClusterSizer  TF_SetTfXlaCpuGlobalJitr  ra   r$   enable_mlir_bridge_threadsrL  _cached_session_test_start_time_set_default_seed)ri  
methodNamer  s     r]   r  zTensorFlowTestCase.__init__
  s    	GZ //1,,S1//266u=//5 88>
 -1goo*		!	--2goo*DMDMD D "Dr\   c                 d   t         |           | j                          t        j                  t
        j                         t        j                  j	                  t
        j                         t        j                  j                          t        j                          | j                  r#t        j                  t
        j                         t        j                  }d |_        | j#                         j%                  d      r| j'                  d       t)        j(                         | _        y )N.test_sessionzNot a test.)r  rM  _ClearCachedSessionrandomseedr1   DEFAULT_GRAPH_SEEDnpr0   _default_graph_stackr  rJ  r;  set_random_seedr?   _summary_statewriterr  endswithr)  timer:  )ri  summary_stater  s     r]   rM  zTensorFlowTestCase.setUp&
  s    	GMO
KK../IINN;112 ""$!!+"@"@A #11MM wwy/*
mmM" IIKDr\   c                 F    t         |           t        rt        |        y y r`   )r  
setUpClass_ENABLE_AUTO_BOTH_MODESr  )r/  r  s    r]   rL  zTensorFlowTestCase.setUpClass@
  s    	G&s+ r\   c                 8   | j                   Nt        j                  d| j                         t	        t        j
                         | j                   z
  d             | j                  D ]  }|j                           | j                          t        | )          y )Nztime(%s): %ssr   )r:  r  rC  r  roundrI  r8  check_terminationr?  r  rK  )ri  threadr  s     r]   rK  zTensorFlowTestCase.tearDownF
  s}     (ll?DGGIt'<'<<a@B -- ! ! 		Gr\   c                 `    | j                   "| j                   j                          d | _         y y r`   )r9  closeri  s    r]   r?  z&TensorFlowTestCase._ClearCachedSessionS
  s-    '
  "!d (r\   rX   c                     | j                   s-t        j                  t        j                               | _         | j                   S )aR  Returns a unique temporary directory for the test to use.

    If you call this method multiple times during in a test, it will return the
    same folder. However, across different runs the directories will be
    different. This will ensure that across different runs tests will not be
    able to pollute each others environment.
    If you need multiple unique directories within a single test, you should
    use tempfile.mkdtemp as follows:
      tempfile.mkdtemp(dir=self.get_temp_dir()):

    Returns:
      string, the path to the unique temporary directory created for this test.
    r  )rL  tempfilemkdtemprE   
GetTempDirrT  s    r]   get_temp_dirzTensorFlowTestCase.get_temp_dirX
  s0     ==&&:+@+@+BCdm==r\   c              #     K   |j                          |j                         }t        j                  | j	                               \  }}t        j                  |      }t        j                  ||       	 t        |       t        j                  |       t        j                  ||       y# t        j                  |       t        j                  ||       w xY ww)ai  A context manager that captures the writes to a given stream.

    This context manager captures all writes to a given stream inside of a
    `CapturedWrites` object. When this context manager is created, it yields
    the `CapturedWrites` object. The captured contents can be accessed  by
    calling `.contents()` on the `CapturedWrites`.

    For this function to work, the stream must have a file descriptor that
    can be modified using `os.dup` and `os.dup2`, and the stream must support
    a `.flush()` method. The default python sys.stdout and sys.stderr are
    examples of this. Note that this does not work in Colab or Jupyter
    notebooks, because those use alternate stdout streams.

    Example:
    ```python
    class MyOperatorTest(test_util.TensorFlowTestCase):
      def testMyOperator(self):
        input = [1.0, 2.0, 3.0, 4.0, 5.0]
        with self.captureWritesToStream(sys.stdout) as captured:
          result = MyOperator(input).eval()
        self.assertStartsWith(captured.contents(), "This was printed.")
    ```

    Args:
      stream: The stream whose writes should be captured. This stream must have
        a file descriptor, support writing via using that file descriptor, and
        must have a `.flush()` method.

    Yields:
      A `CapturedWrites` object that contains all writes to the specified stream
      made during this context.
    rV  N)
flushfilenorW  mkstemprZ  r  dupdup2r  rS  )ri  streamfdr  tmp_file_pathorig_fds         r]   captureWritesToStreamz(TensorFlowTestCase.captureWritesToStreamj
  s     D LLN	B&..43D3D3FGHmffRjGGGHb=))hhxgggr 	hhxgggrs   A3C6B/ ,C/-CCNc                 h    t        j                  ||      st        j                  | ||d||       yy)ah  Asserts that a and b are the same proto.

    Uses ProtoEq() first, as it returns correct results
    for floating point attributes, and then use assertProtoEqual()
    in case of failure as it provides good error messages.

    Args:
      a: a proto.
      b: another proto.
      msg: Optional message to report on failure.
      relative_tolerance: float. The allowable difference between the two values
        being compared is determined by multiplying the relative tolerance by
        the maximum of the two values. If this is not provided, then all floats
        are compared using string comparison.
    T)normalize_numbersmsgrelative_toleranceN)rQ   ProtoEqassertProtoEqual)ri  r   r   rh  ri  s        r]   _AssertProtoEqualsz%TensorFlowTestCase._AssertProtoEquals
  s7      ??1a 


 / !r\   c                 h   t        |t        |            r|}| j                  ||||       yt        |t        t        f      rP t        |             }t        j                  ||t        j                                | j                  ||||       yJ dt        |      dt        |      d       )a  Asserts that message is same as parsed expected_message_ascii.

    Creates another prototype of message, reads the ascii message into it and
    then compares them using self._AssertProtoEqual().

    Args:
      expected_message_maybe_ascii: proto message in original or ascii form.
      validate_message: the message to validate.
      msg: Optional message to report on failure.
      relative_tolerance: float. The allowable difference between the two values
        being compared is determined by multiplying the relative tolerance by
        the maximum of the two values. If this is not provided, then all floats
        are compared using string comparison.
    )rh  ri  r   zCan't compare protos of type  and .N)	r   rq   rl  r"  bytesr   Merger   Default)ri  expected_message_maybe_asciivalidate_messagerh  ri  expected_messages         r]   r   z$TensorFlowTestCase.assertProtoEquals
  s    * .5E0FG5


/	   
03,	?/./1
&
)1135 

/	  
+
,

  Ur\   c                 <    d|||fz  }| j                  |||       y )Nz.versions { producer: %d min_consumer: %d };
%srh  )r   )ri  r   r   producermin_consumerrh  s         r]   assertProtoEqualsVersionz+TensorFlowTestCase.assertProtoEqualsVersion
  s1     A,D* *H8V5r\   c                 p    |j                  |      s%|d|}||rd|z  ndz  }| j                  |       yy)zAssert that actual.startswith(expected_start) is True.

    Args:
      actual: str
      expected_start: str
      msg: Optional message to report on failure.
    z does not start with z : %rrw   N)r   fail)ri  r   expected_startrh  fail_msgs        r]   assertStartsWithz#TensorFlowTestCase.assertStartsWith
  s?     ^,06GhS'S/b0h
ii -r\   c                    |y t        |      r| j                   |             S 	 t        j                  |      r_t        j                  |j
                  j                         |j                  j                         |j                  j                               S t        j                  |      rHt        j                  | j                  |j                        | j                  |j                              S t        |t         j"                        rst!        j$                  |j                  j                         |j
                  j                         |j                  d       S |j                  j                               S t'        |d      r%t        |j                        r|j                         S t)        j*                  d |d      S # t,        $ r(}t/        dt1        |      j2                  d      |d }~ww xY w)N)r  indicesdense_shapenumpyc                 "    | j                         S r`   )r  )r  s    r]   r  z1TensorFlowTestCase._eval_tensor.<locals>.<lambda>  s    	 r\   T)expand_compositeszUnsupported type ro  )r  _eval_helperr2   	is_sparseSparseTensorValuer  r  r  r  rB   	is_raggedrC   RaggedTensorValue_eval_tensor
row_splitsr   r/   IndexedSlicesIndexedSlicesValuer[  rK   map_structurer  r   rq   rr   )ri  r3   r$  s      r]   r  zTensorFlowTestCase._eval_tensor
  s   ~	&	vx((P""6*001E1E1G171D1D1F171C1C1I1I1KM M $$V,$66. 1 124 4  < <=22]]((*nn**,##+ M M 281C1C1I1I1K	M M VW%(6<<*@<<>! %%&968<> > P,T&\-B-B,EQGHaOPs8   A3G AG 7A-G %G 0G 5G 	G?#G::G?c                 H    |y t        j                  | j                  |      S r`   )rK   r  r  )ri  tensorss     r]   r  zTensorFlowTestCase._eval_helper  s#    d//99r\   c                 ^   t        j                         r| j                  |      S t        j                         }t        j                  |      }|+| j                         5 }|j                  |      }ddd       n|j                  |      }t        j                  |      S # 1 sw Y   xY w)zEvaluates tensors and returns numpy values.

    Args:
      tensors: A Tensor or a nested list/tuple of Tensors.

    Returns:
      tensors numpy values.
    N)
r$   r  r  r0   get_default_sessionrK   r'  r  r  pack_sequence_as)ri  r  sessflattened_tensorsflattened_resultss        r]   r  zTensorFlowTestCase.evaluate   s       "w''$$&d,,w/	  	:D"hh'89
	: 	: !HH%67""7,=>>		: 	:s   !B##B,r   r'   r5  r  c              #      K   t        j                         rt                y| j                  |||      5 }| j	                  |||      5  | ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY ww)as  A context manager for a TensorFlow Session for use in executing tests.

    Note that this will set this session and the graph as global defaults.

    Use the `use_gpu` and `force_gpu` options to control where ops are run. If
    `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
    `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
    possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to
    the CPU.

    Example:

    ``` python
    class MyOperatorTest(test_util.TensorFlowTestCase):
      def testMyOperator(self):
        with self.session():
          valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
          result = MyOperator(valid_input).eval()
          self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
          invalid_input = [-1.0, 2.0, 7.0]
          with self.assertRaisesOpError("negative input not supported"):
            MyOperator(invalid_input).eval()
    ```

    Args:
      graph: Optional graph to use during the returned session.
      config: An optional config_pb2.ConfigProto to use to configure the
        session.
      use_gpu: If True, attempt to run as many ops as possible on GPU.
      force_gpu: If True, pin all ops to `/device:GPU:0`.

    Yields:
      A Session object that should be used as a context manager to surround
      the graph building and execution code in a test case.
    N)r$   r  r-  _create_session"_constrain_devices_and_set_default)ri  r   r'   r5  r  r  s         r]   r   zTensorFlowTestCase.session=  sw     V   "  vy9 T44T7IN 	*	 	 	 s4   5A9A-A!A-	A9!A*	&A--A62A9c              #      K   t        j                         rt        |        y| j                  |||d      }| j	                  |||      5 }| ddd       y# 1 sw Y   yxY ww)a?  Returns a TensorFlow Session for use in executing tests.

    This method behaves differently than self.session(): for performance reasons
    `cached_session` will by default reuse the same session within the same
    test. The session returned by this function will only be closed at the end
    of the test (in the TearDown function).

    Use the `use_gpu` and `force_gpu` options to control where ops are run. If
    `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
    `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
    possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to
    the CPU.

    Example:
    ```python
    class MyOperatorTest(test_util.TensorFlowTestCase):
      def testMyOperator(self):
        with self.cached_session() as sess:
          valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
          result = MyOperator(valid_input).eval()
          self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
          invalid_input = [-1.0, 2.0, 7.0]
          with self.assertRaisesOpError("negative input not supported"):
            MyOperator(invalid_input).eval()
    ```

    Args:
      graph: Optional graph to use during the returned session.
      config: An optional config_pb2.ConfigProto to use to configure the
        session.
      use_gpu: If True, attempt to run as many ops as possible on GPU.
      force_gpu: If True, pin all ops to `/device:GPU:0`.

    Yields:
      A Session object that should be used as a context manager to surround
      the graph building and execution code in a test case.
    Tcrash_if_inconsistent_argsN)r$   r  r  _get_cached_sessionr  ri  r   r'   r5  r  r  cacheds          r]   cached_sessionz!TensorFlowTestCase.cached_sessiono  sp     Z   "T""%%
t & Ed2243<> AG  s   AA'A	A'A$ A'z8Use `self.session()` or `self.cached_session()` instead.c              #     K   | j                         j                  d      r| j                  d       t        j                         rd y|6| j                  |||d      }| j                  |||      5 }| ddd       y| j                  ||||      5 }| ddd       y# 1 sw Y   yxY w# 1 sw Y   yxY ww)zUse cached_session instead.r>  zTests that have the name "test_session" are automatically skipped by TensorFlow test fixture, as the name is reserved for creating sessions within tests. Please rename your test if you have a test with this name.NFr  )r  rH  r)  r$   r  r  r  r   r  s          r]   r  zTensorFlowTestCase.test_session  s      wwy/*
mm
   "j	''69 ( H44T75>@ 	CI,	 	 \\%)< 	*	 			 		 	s6   A4B>6B&;B>B2	B>&B/+B>2B;7B>c                       e Zd ZdZ	 	 ddddedef   deeedf      deee	ef      fd	Z
ddZddZddZd
efdZddZy)!TensorFlowTestCase._CheckedThreadzA wrapper class for Thread that asserts successful completion.

    This class should be created using the TensorFlowTestCase.checkedThread()
    method.
    NtestcaserW   r   .r  r  c                     || _         || _        |dn|| _        |i n|| _        t	        j
                  | j                        | _        d| _        d| _	        y)a  Constructs a new instance of _CheckedThread.

      Args:
        testcase: The TensorFlowTestCase for which this thread is being created.
        target: A callable object representing the code to be executed in the
          thread.
        args: A tuple of positional arguments that will be passed to target.
        kwargs: A dictionary of keyword arguments that will be passed to target.
      Nr[   r   F)
	_testcase_target_args_kwargs	threadingThread_protected_run_thread
_exception_is_thread_joined)ri  r  r   r  r  s        r]   r  z*TensorFlowTestCase._CheckedThread.__init__  sS       dndl*.,BDdj+1>Rvdl%%T-@-@Adldo$dr\   rX   c                     	  | j                   | j                  i | j                   y# t        $ r}|| _        Y d}~yd}~ww xY w)z?Target for the wrapper thread. Sets self._exception on failure.N)r  r  r  r  r  )ri  r$  s     r]   r  z0TensorFlowTestCase._CheckedThread._protected_run  s;    djj1DLL1 s   &) 	A>Ac                 8    | j                   j                          y)zStarts the thread's activity.

      This must be called at most once per _CheckedThread object. It arranges
      for the object's target to be invoked in a separate thread of control.
      N)r  startrT  s    r]   r  z'TensorFlowTestCase._CheckedThread.start  s     llr\   c                     d| _         | j                  j                          | j                  2| j                  j                  dt        | j                        z         yy)zBlocks until the thread terminates.

      Raises:
        self._testcase.failureException: If the thread terminates with due to
          an exception.
      TNzError in checkedThread: %s)r  r  r  r  r  r|  r"  rT  s    r]   r  z&TensorFlowTestCase._CheckedThread.join  sL      $d
ll		$83t;OOP 
%r\   c                 6    | j                   j                         S )zReturns whether the thread is alive.

      This method returns True just before the run() method starts
      until just after the run() method terminates.

      Returns:
        True if the thread is alive, otherwise False.
      )r  is_aliverT  s    r]   r  z*TensorFlowTestCase._CheckedThread.is_alive   s     \\""$$r\   c                     | j                   r| j                         rt        d      y| j                  j	                  d       y)a  Returns whether the checked thread was properly used and did terminate.

      Every checked thread should be "join"ed after starting, and before the
      test tears down. If it is not joined, it is possible the thread will hang
      and cause flaky failures in tests.

      Raises:
        self._testcase.failureException: If check_termination was called before
        thread was joined.

        RuntimeError: If the thread is not terminated. This means thread was not
        joined with the main thread.
      zTThread was not joined with main thread, and is still running when the test finished.z A checked thread was not joined.N)r  r  r  r  r|  rT  s    r]   rP  z3TensorFlowTestCase._CheckedThread.check_termination  sB     
		==?() ) 
 	>?r\   NNrs  )rr   r  r  r  r   r	   r   r  r  r"  r  r  r  r  r  r  rP  r[   r\   r]   _CheckedThreadr    s     +/+/%&% c"% uS#X'	%
 c3h(%2
Q	%$ 	%@r\   r  r   .r  r  c                 l    t         j                  | |||      }| j                  j                  |       |S )af  Returns a Thread wrapper that asserts 'target' completes successfully.

    This method should be used to create all threads in test cases, as
    otherwise there is a risk that a thread will silently fail, and/or
    assertions made in the thread will not be respected.

    Args:
      target: A callable object to be executed in the thread.
      args: The argument tuple for the target invocation. Defaults to ().
      kwargs: A dictionary of keyword arguments for the target invocation.
        Defaults to {}.

    Returns:
      A wrapper for threading.Thread that supports start() and join() methods.
    )rW   r  r8  r   )ri  r   r  r  r*  s        r]   checkedThreadz TensorFlowTestCase.checkedThread!  s1    * 
+
+D&$
GCMMJr\   c           	          | j                  ||k(  xs t        j                  ||z
        |k  d||||d|z  ndfz         y)a  Asserts that two floats are near each other.

    Checks that |f1 - f2| < err and asserts a test failure
    if not.

    Args:
      f1: A float value.
      f2: A float value.
      err: A float value.
      msg: An optional string message to append to the failure message.
    z%f != %f +/- %f%sNz (%s)rw   )
assertTruemathfabs)ri  f1f2errrh  s        r]   
assertNearzTensorFlowTestCase.assertNear;  sN     	OO
b-DIIb2g&#-/B	RsgmB?0@Ar\   c                     | j                  t        |      t        |      |       t        ||      D ],  \  }}| j                  t	        |      t	        |      ||       . y)aJ  Asserts that two float arrays are near each other.

    Checks that for all elements of farray1 and farray2
    |f1 - f2| < err.  Asserts a test failure if not.

    Args:
      farray1: a list of float values.
      farray2: a list of float values.
      err: a float value.
      msg: Optional message to report on failure.
    rw  N)r   r   r   r  float)ri  farray1farray2r  rh  r  r  s          r]   assertArrayNearz"TensorFlowTestCase.assertArrayNearM  sW     	S\3w<S9gw' :B
ooeBirCSo9:r\   c                 L    t         j                  j                  ||z
        |k  S r`   )rC  linalgnorm)ri  ndarray1ndarray2r  s       r]   _NDArrayNearzTensorFlowTestCase._NDArrayNear^  s    99>>(X-.44r\   c                 L    | j                  | j                  |||      |       y)zAsserts that two numpy arrays have near values.

    Args:
      ndarray1: a numpy ndarray.
      ndarray2: a numpy ndarray.
      err: a float. The maximum absolute difference allowed.
      msg: Optional message to report on failure.
    rw  N)r  r  )ri  r  r  r  rh  s        r]   assertNDArrayNearz$TensorFlowTestCase.assertNDArrayNeara  s#     	OOD%%h#>COHr\   c                    t        j                  |      r<t        |t        j                        r|j                         }n| j                  |      }t        |t        j                        s	 t        j                  |      S |S # t        $ r3}dt        |      v r t        j                  |t              cY d }~S  d }~ww xY w)Nzinhomogeneous shaper(  )r5   
is_tf_typer   r0   _EagerTensorBaser  r  rC  ndarrayarrayr   r"  object)ri  r   r$  s      r]   _GetNdArrayzTensorFlowTestCase._GetNdArraym  s    a 	As++	,GGIMM!a$xx{ H   !CF*!6*
*
s$   -B 	C 'B;4C :B;;C c                     t        j                  |      r\t        j                  |      rGt        |t        j                        s-t        |t        j                        s| j                  ||f      S ||fS r`   )r5   r  r   r0   r  r  )ri  r   r   s      r]   evaluate_if_both_tensorsz+TensorFlowTestCase.evaluate_if_both_tensors  sY    q!k&<&<Q&?q#../q#../]]Aq6""Vmr\   c           	         | j                  ||      \  }}| j                  |      }| j                  |      }|j                  |j                  k7  r?|j                  dk  s|j                  dk  r!d|j                  d|j                  d|d}nd|j                  d|j                  d}| j                  |j                  |j                  |       |g}|j                  }t        j                  j                  t        j                  j                  t        j                  j                  t        j                  j                  t        j                  j                  t        j                  j                  f}	|j                  |	v r|j                  t         j"                        n|}|j                  |	v r|j                  t         j"                        n|}t!        j$                  ||||      st!        j&                  t!        j(                  ||z
        ||t!        j(                  |      z  z   kD  t!        j*                  |      t!        j*                  |      k7        }
|j                  rF|t-        |
         }|t-        |
         }|j/                  dj1                  t-        |
                   n||}}|j/                  d	j1                  |             |j/                  d
j1                  |             |j/                  dj1                  t!        j(                  ||z
                     |j/                  dj1                  ||t!        j(                  |      z  z                |j/                  dj1                  ||j                               t         j2                  j5                  ||||dj7                  |      d       y y )Nr     Shape mismatch: expected , got z with contents ro  )rtolatolznot close where = {}znot close lhs = {}znot close rhs = {}znot close dif = {}znot close tol = {}zdtype = {}, shape = {}
T)r  r  err_msg	equal_nan)r  r  r   ndimsizer   r(  r*   bfloat16as_numpy_dtypefloat8_e5m2float8_e4m3fnfloat8_e4m3fnuzfloat8_e4m3b11fnuzfloat8_e5m2fnuzastyperC  r$  allclose
logical_orabsisnanrP   r   r*  testingassert_allcloser  )ri  r   r   r  r  rh  shape_mismatch_msgmsgsa_dtypecustom_dtypescondr|   ys                r]   _assertArrayLikeAllClosez+TensorFlowTestCase._assertArrayLikeAllClose  s   **1a0FQAA 	ww!''qvv{affsl&'ggqww; FGWWEFWWNQWWagg'9:5D ggG__33''66))88++::..==++::<M !"= 8aA != 8aA;;q!$T2 ]]
&&Q-$q	!11
1
((1+!
$&d 
htnhtn*11(4.AB !1
kk&--a01
kk&--a01
kk&--bffQUm<=
kk&--dTBFF1I5E.EFG
kk*11'177CD 	jj  
QTdiio ! O7 3r\   c                 N   t        j                  |      st        j                  |      r| j                  |||||      S |xs g }|rddj                  d |D              z   dz   nd}|r|nd}t	        |d      r|j                         }t	        |d      r|j                         }t        |t        j                        }|t        |t        j                        k7  rt        d|d|d	|      |r| j                  |j                         |j                         d
|d|j                         d|d|j                         d	|
       |D ]3  }	|j                  |	       | j                  ||	   ||	   ||||       |d= 5 y t        |t        t        f      rX	 | j!                  ||      \  }}| j#                  |      }
| j#                  |      }| j%                  |
|||d|d|d	|       y 	 | j%                  ||||d|d|d	|       y # t        t&        t(        f$ r}t+        |      t+        |      k7  r%t        d|t+        |      |t+        |      |fz        t-        t/        ||            D ]<  \  }\  }}|j                  t1        |             | j                  ||||||       |d= > Y d }~y d }~ww xY w# t&        $ rT}d|dt3        |      d|dt3        |      d	|
}|j4                  d   dz   |z   f|j4                  dd  z   |_         d }~ww xY w)N[z][c              3   2   K   | ]  }t        |        y wr`   r!  )r#  r  s     r]   r%  z>TensorFlowTestCase._assertAllCloseRecursive.<locals>.<genexpr>  s      6AQ 6s   ]rw   _asdictz!Can't compare dict to non-dict, az vs b. zmismatched keys: az
 has keys z, but brw  )r  r  r  rh  r   zMismatched value: az is different from br  r  rh  z=Mismatched length: a%s has %d items, but b%s has %d items. %szError: az has r    : r   )rB   r  _assertRaggedCloser  r[  r  r   rO   Mappingr   assertItemsEqualr   r   _assertAllCloseRecursiver  r  r  r  r  r   NotImplementedErrorr   r  r   r"  rq   r  )ri  r   r   r  r  r  rh  path_str	a_is_dictr   a_as_ndarrayb_as_ndarrayr$  r  a_eleb_eles                   r]   r  z+TensorFlowTestCase._assertAllCloseRecursive  s    q!]%<%<Q%?$$Q4s;;:2DAEtyy 6 666<2H#"C q)
))+aq)
))+a1o556IJq/"9"9:: (C1 2 2

&&(
&&(QVVXx38  9
  !A%%aD!A$T4S 	& 	BH	
 
Ae}	%..q!4A''*''*%%x& 	& 	'&%%Hc+ 	& 	- )%89 	q6SVMQ3q63789 9 $-SAY#7 	C%
++c#h


'
'UDt ( F2h			(  $q'8T!Wc;66!9u$s*,qvvabz9	s3   AH 6K K*BJ??K	L$ALL$c                 0    | j                  |||||       y)a  Asserts that two structures of numpy arrays or Tensors, have near values.

    `a` and `b` can be arbitrarily nested structures. A layer of a nested
    structure can be a `dict`, `namedtuple`, `tuple` or `list`.

    Note: the implementation follows
    [`numpy.allclose`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html)
    (and numpy.testing.assert_allclose). It checks whether two arrays are
    element-wise equal within a tolerance. The relative difference
    (`rtol * abs(b)`) and the absolute difference `atol` are added together
    to compare against the absolute difference between `a` and `b`.

    Args:
      a: The expected numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor), or any arbitrarily nested of
        structure of these.
      b: The actual numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor), or any arbitrarily nested of
        structure of these.
      rtol: relative tolerance.
      atol: absolute tolerance.
      msg: Optional message to report on failure.

    Raises:
      ValueError: if only one of `a[p]` and `b[p]` is a dict or
          `a[p]` and `b[p]` have different length, where `[p]` denotes a path
          to the nested structure, e.g. given `a = [(1, 1), {'d': (6, 7)}]` and
          `[p] = [1]['d']`, then `a[p] = (6, 7)`.
    r  N)r  ri  r   r   r  r  rh  s         r]   assertAllClosez!TensorFlowTestCase.assertAllClose  s    > 	!!!QT#!Fr\   c                 &   | j                  ||      \  }}| j                  |      }| j                  |      }|j                  t        j                  k(  sW|j                  t        j                  k(  s:|j                  t        j
                  k(  s|j                  t        j
                  k(  rt        ||      }t        ||      }|j                  t        j                  k(  s|j                  t        j                  k(  rt        ||      }t        ||      }|j                  t        j                  j                  k(  s'|j                  t        j                  j                  k(  rt        ||	      }t        ||
      }| j                  |||||       y)a  Like assertAllClose, but also suitable for comparing fp16 arrays.

    In particular, the tolerance is reduced to 1e-3 if at least
    one of the arguments is of type float16.

    Args:
      a: the expected numpy ndarray or anything can be converted to one.
      b: the actual numpy ndarray or anything can be converted to one.
      rtol: relative tolerance.
      atol: absolute tolerance.
      float_rtol: relative tolerance for float32.
      float_atol: absolute tolerance for float32.
      half_rtol: relative tolerance for float16.
      half_atol: absolute tolerance for float16.
      bfloat16_rtol: relative tolerance for bfloat16.
      bfloat16_atol: absolute tolerance for bfloat16.
      msg: Optional message to report on failure.
    r  N)r  r  r(  rC  r$  r&  maxfloat16r*   r  r  r  )ri  r   r   r  r  
float_rtol
float_atol	half_rtol	half_atolbfloat16_rtolbfloat16_atolrh  s               r]   assertAllCloseAccordingToTypez0TensorFlowTestCase.assertAllCloseAccordingToType3  s$   > **1a0FQAA	2::BJJ!6	2<<177bll#:z"dz"dww"**2:: 5y!dy!d	6??111	6??111}%d}%d14d<r\   c                 v    	 | j                  |||||       |xs d}t        d|z        # t        $ r Y yw xY w)a  Assert that two numpy arrays, or Tensors, do not have near values.

    Args:
      a: The expected numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor), or any arbitrarily nested of
        structure of these.
      b: The actual numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor), or any arbitrarily nested of
        structure of these.
      rtol: relative tolerance.
      atol: absolute tolerance.
      msg: Optional message to report on failure.

    Raises:
      AssertionError: If `a` and `b` are unexpectedly close at all elements.
    r  Nrw   z,The two values are close at all elements. %s)r  r   r  s         r]   assertNotAllClosez$TensorFlowTestCase.assertNotAllClosed  sP    $
!QT#> )C
G#M
NN  s   , 	88c                    t        j                  |      st        j                  |      r| j                  |||      S |r|nd}| j                  ||      \  }}| j	                  |      }| j	                  |      }|j
                  dk  s|j                  dk  rI| j                  |j                  |j                  d|j                  d|j                  d|d|d	       nD| j                  |j                  |j                  d|j                  d|j                  d	|       ||k(  }t        j                  |j                        j                  rPt        j                  |t        j                  t        j                   |      t        j                   |                  }|g}t        j"                  |      st        j$                  |      }|j
                  rF|t'        |         }|t'        |         }|j)                  d
j+                  t'        |                   n||}}|j)                  d|z         |j)                  d|z         |j                  j,                  |j                  j,                  k7  r|j                  j,                  |j                  j,                  hj/                  h d      rg }	g }
|	|j0                  f|
|j0                  ffD ]N  \  }}|D ]D  }t3        |t4              r!|j)                  |j7                  d             4|j)                  |       F P t        j8                  |	      }t        j8                  |
      }t        j:                  j=                  ||dj?                  |             yy)a  Asserts that two numpy arrays or Tensors have the same values.

    Args:
      a: the expected numpy ndarray or anything can be converted to one.
      b: the actual numpy ndarray or anything can be converted to one.
      msg: Optional message to report on failure.
    rw   r   r  r  r  z. Contents: z. 
ro  r   znot equal where = {}znot equal lhs = %rznot equal rhs = %r>   OSUzutf-8r  )r  N) rB   r  _assertRaggedEqualr  r  r  r  r   r   r*   as_dtyper(  is_floatingrC  r  logical_andr  r  logical_notrP   r   r*  kindissubsetflatr   r"  encoder  r  assert_array_equalr  )ri  r   r   rh  samer  r   r|   r  a_listb_listout_listflat_arritems                 r]   assertAllEqualz!TensorFlowTestCase.assertAllEqual}  s    	"m&=&=a&@$$Q3//#"C**1a0FQAA	!qvv|

''177$%GGQWWa>? 
''17777AGGS*+ FDqww++]]4RXXa[!IJd5D66$<^^D!d	
htnhtn*11(4.AB !1
kk&*+
kk&*+
'',,!'',,
&77<<
&
/
/
@ %+AFF#3faff5E"F 	$Hh $d$$oodkk'23ood#	$	$ HHVHHVjj##Aq$))D/#B9 r\   c                 n    	 | j                  ||       |xs d}t        d|z        # t        $ r Y yw xY w)a  Asserts that two numpy arrays or Tensors do not have the same values.

    Args:
      a: the expected numpy ndarray or anything can be converted to one.
      b: the actual numpy ndarray or anything can be converted to one.
      msg: Optional message to report on failure.
    Nrw   z,The two values are equal at all elements. %s)r1  r   )ri  r   r   rh  s       r]   assertNotAllEqualz$TensorFlowTestCase.assertNotAllEqual  sG    
!Q )C
G#M
NN  s   ( 	44c                     | j                  ||      \  }}| j                  |      }| j                  t        j                  |      |       y)zAssert element values are all greater than a target value.

    Args:
      a: The numpy `ndarray`, or anything that can be converted into a numpy
        `ndarray` (including Tensor).
      comparison_target: The target value of comparison.
    N)r  r  assertGreaterrC  minri  r   comparison_targets      r]   assertAllGreaterz#TensorFlowTestCase.assertAllGreater  sF     "::1>OPQArvvay"34r\   c                     | j                  ||      \  }}| j                  |      }| j                  t        j                  |      |       y)zAssert element values are all less than a target value.

    Args:
      a: The numpy `ndarray`, or anything that can be converted into a numpy
        `ndarray` (including Tensor).
      comparison_target: The target value of comparison.
    N)r  r  
assertLessrC  r  r7  s      r]   assertAllLessz TensorFlowTestCase.assertAllLess  sD     "::1>OPQAOOBFF1I01r\   c                     | j                  ||      \  }}| j                  |      }| j                  t        j                  |      |       y)a  Assert element values are all greater than or equal to a target value.

    Args:
      a: The numpy `ndarray`, or anything that can be converted into a numpy
        `ndarray` (including Tensor).
      comparison_target: The target value of comparison.
    N)r  r  assertGreaterEqualrC  r6  r7  s      r]   assertAllGreaterEqualz(TensorFlowTestCase.assertAllGreaterEqual  sF     "::1>OPQABFF1I'89r\   c                     | j                  ||      \  }}| j                  |      }| j                  t        j                  |      |       y)zAssert element values are all less than or equal to a target value.

    Args:
      a: The numpy `ndarray`, or anything that can be converted into a numpy
        `ndarray` (including Tensor).
      comparison_target: The target value of comparison.
    N)r  r  assertLessEqualrC  r  r7  s      r]   assertAllLessEqualz%TensorFlowTestCase.assertAllLessEqual  sF     "::1>OPQA$56r\   c           
      |   g }t        j                  |      }d|z  }t        j                  |      dk(  r|dz   t        |      z   gS t	        j
                  ||      D ]:  }|j                  |t        |      z   dz   t        |t        |               z          < t        |      |kD  r|j                  |dz          |S )a@  Generate a summary of ndarray subscripts as a list of str.

    If limit == N, this method will print up to the first N subscripts on
    separate
    lines. A line of ellipses (...) will be appended at the end if the number of
    subscripts exceeds N.

    Args:
      subscripts: The tensor (np.ndarray) subscripts, of the same format as
        np_where()'s return value, i.e., a tuple of arrays with each array
        corresponding to a dimension. E.g., (array([1, 1]), array([0, 1])).
      value: (np.ndarray) value of the tensor.
      limit: (int) The maximum number of indices to print.
      indent: (int) Number of characters to indent at the beginning of each
        line.

    Returns:
      (list of str) the multi-line representation of the subscripts and values,
        potentially with omission at the end.
    r  r   z[0] : r  z...)	rC  r   r  r"  r  islicer   r  r   )ri  
subscriptsr   limitindentlinesprefix	subscripts           r]   _format_subscriptsz%TensorFlowTestCase._format_subscripts  s    * Ej)J6\F	wwu~x#e*,--%%j%8 1	ll6C	N*U2uU9-./0 11 :ll6E>"Lr\   c           	      6   | j                  |      }t        j                  |j                  t        j                        sIt        j                  |j                  t        j
                        st        d|d|j                        t        t        j                  |            }t        j                  |      rQt        dt        |d         t        j                  |      fz  dj                  | j                  ||            z         |rdndt        |      z   dz   t        |      z   |rd	nd
z   }|rt        j                  ||      nt        j                  ||      }t        j                   ||rt        j"                  ||      nt        j$                  ||            }t        |      }	t        j                  |	      rUt        dt        |	d         t        j                  |      |fz  dz   dj                  | j                  |	|            z         y)a  Assert that elements in a Tensor are all in a given range.

    Args:
      target: The numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor).
      lower_bound: lower bound of the range
      upper_bound: upper bound of the range
      open_lower_bound: (`bool`) whether the lower bound is open (i.e., > rather
        than the default >=)
      open_upper_bound: (`bool`) whether the upper bound is open (i.e., < rather
        than the default <=)

    Raises:
      AssertionError:
        if the value tensor does not have an ordered numeric type (float* or
          int*), or
        if there are nan values, or
        if any of the elements do not fall in the specified range.
    zThe value of z= does not have an ordered numeric type, instead it has type: zS%d of the %d element(s) are NaN. Subscripts(s) and value(s) of the NaN element(s):
r   r  (r  r  )r  z2%d of the %d element(s) are outside the range %s. z5Subscript(s) and value(s) of the offending elements:
N)r  rC  
issubdtyper(  floatingintegerr   rP   r  r  r   r  rK  r"  
less_equallessr  greater_equalgreater)
ri  r   lower_boundupper_boundopen_lower_boundopen_upper_boundnan_subscripts	range_str
violationsviolation_subscriptss
             r]   assertAllInRangez#TensorFlowTestCase.assertAllInRange  s   4 f%FMM&,,4MM&,,

3"FLL23 3 bhhv./N	ww~@~a !2776?
34 ))D++NFC
DEF F *#sc+6FFM[!",<S#GI /?fk*BGGKE!   	-!#FK!@BJ $J/	ww#$
>#A&')
DE
BC ))D++,@&I
JKL L %r\   c                     | j                  |      }t        j                  |j                         t	        |            }t        j
                  |      r$t        dt        j
                  |      ||fz        y)a  Assert that elements of a Tensor are all in a given closed set.

    Args:
      target: The numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor).
      expected_set: (`list`, `tuple` or `set`) The closed set that the elements
        of the value of `target` are expected to fall into.

    Raises:
      AssertionError:
        if any of the elements do not fall into `expected_set`.
    z.%d unique element(s) are not in the set %s: %sN)r  rC  	setdiff1dr'  r  r  r   )ri  r   expected_setr   s       r]   assertAllInSetz!TensorFlowTestCase.assertAllInSetY  sk     f%F <<($|*<=D	wwt}KGGDM<>? @ @ r\   c                     | j                  |      }t        |t              s|g}D ]  }| j                  |j                  |         y)zAssert ndarray data type is equal to expected.

    Args:
      target: The numpy `ndarray`, or anything that can be converted into a
        numpy `ndarray` (including Tensor).
      expected_dtype: Expected data type.
    N)r  r   r  r   r(  )ri  r   expected_dtypearraysarrs        r]   assertDTypeEqualz#TensorFlowTestCase.assertDTypeEqualo  sH     f%Ffd#xf 2
syy.12r\   c           	   #   &  K   t              r}nfd}	 d | j                  |j                  dz          y# t        $ rJ}t	        ||      r ||      s,t        dt        t        |            dt        |            Y d}~yd}~ww xY ww)a  Returns a context manager to enclose code expected to raise an exception.

    If the exception is an OpError, the op stack is also included in the message
    predicate search.

    Args:
      exception_type: The expected type of exception that should be raised.
      expected_err_re_or_predicate: If this is callable, it should be a function
        of one argument that inspects the passed-in exception and returns True
        (success) or False (please fail the test). Otherwise, the error message
        is expected to match this regular expression partially.

    Returns:
      A context manager to surround code that is expected to raise an
      exception.
    c                 t   t        | t        j                        rAt        t        j                  |       } t        t        | j
                        }| j                  }nt	        |       }d }|!|d|j                  z   z  }|j                  }|!t        j                  d|       t        j                  |      S )Nz
Caused by: z0Searching within error strings: '%s' within '%s')r   r+   OpErrorr
   r"  r   r   r{   _original_opr  rC  r   search)r$  err_strr   expected_err_re_or_predicates      r]   	predicatezDTensorFlowTestCase.assertRaisesWithPredicateMatch.<locals>.predicate  s    a(6>>1%!aii('tt"F'"n
_rww.
.'" n 	G17	<yy5w??r\   Nz not raisedzException of type z: )r  r|  rr   r  r   r   r"  rq   )ri  exception_typern  ro  r$  s     `  r]   assertRaisesWithPredicateMatchz1TensorFlowTestCase.assertRaisesWithPredicateMatch  s     & ,-.i@5
ii''-78 5>*)A,!$q'lCF4 5 	5 3?5s,   B"; B	BA B	B	BBc                 B    | j                  t        j                  |      S r`   )rq  r+   rj  )ri  rn  s     r]   assertRaisesOpErrorz&TensorFlowTestCase.assertRaisesOpError  s     ..v~~/KM Mr\   c                 &    | j                  |d      S )NzJIncompatible shapes|Dimensions must be equal|required broadcastable shapes)rq  )ri  rp  s     r]   #assertRaisesIncompatibleShapesErrorz6TensorFlowTestCase.assertRaisesIncompatibleShapesError  s    .. )* *r\   c                 |   t        |t        j                  t        j                  t        j
                  f      st        dt        |             t        |t        j                  t        j                  t        j
                  f      st        dt        |             t        |t        j
                        r|j                         j                         n|j                  }t        |t        j
                        r|j                         j                         n|j                  }| j                  |||       y)a  Asserts that two Numpy or TensorFlow objects have the same shape.

    For Tensors, this compares statically known shapes at compile time, not
    dynamic shapes at runtime.

    Args:
      input_a: A Numpy ndarray, Numpy scalar, or a Tensor.
      input_b: A Numpy ndarray, Numpy scalar, or a Tensor.
      msg: Optional message to report on failure.

    Raises:
      TypeError: If the arguments have the wrong type.
    zLinput_a must be a Numpy ndarray, Numpy scalar, or a Tensor.Instead received zLinput_b must be a Numpy ndarray, Numpy scalar, or a Tensor.Instead received rw  N)r   rC  r  genericr   r   r   rq   	get_shaper  r   r1  )ri  input_ainput_brh  shape_ashape_bs         r]   assertShapeEqualz#TensorFlowTestCase.assertShapeEqual  s    g

BJJ
8I8IJK"7m_./ / g

BJJ
8I8IJK"7m_./ / 0:""0$g!))+)0 /9""0$g!))+)0 c2r\   c           
          t        j                  |      }t        j                  |      }| j                  ||d|d|d|       y)a   Asserts that the two given devices are the same.

    Args:
      device1: A string device name or TensorFlow `DeviceSpec` object.
      device2: A string device name or TensorFlow `DeviceSpec` object.
      msg: Optional message to report on failure.
    zDevices rn  z are not equal. N)pydevcanonical_namer   )ri  device1device2rh  s       r]   assertDeviceEqualz$TensorFlowTestCase.assertDeviceEqual  sB     ""7+G""7+G18'3GIr\   c                    	 t         |   |||       y# t        $ r | j                  |j	                         |j	                                |j                         D ]  \  }}| j                  |||         \  }}| j                  |      }| j                  |      }t        j                  |j                  t        j                        r| j                  |||   |       | j                  |||   |        Y yw xY w)a[  Assert that two given dictionary of tensors are the same.

    Args:
      a: Expected dictionary with numpy ndarray or anything else that can be
        converted to one as values.
      b: Actual dictionary with numpy ndarray or anything else that can be
        converted to one as values.
      msg: Optional message to report on failure.
    rw  N)r  assertDictEqualr  assertSameElementsr   r@  r  r  rC  rO  r(  rP  r  r1  )	ri  r   r   rh  r   va_kb_kr  s	           r]   r  z"TensorFlowTestCase.assertDictEqual  s    .gaC( 	.
affh1'') .$!Q221ad;
cs#s#==BKK0


a11

-


a11

-.	.s    C&C>=C>c                 P   t        |t        j                        r9t        t        j
                  | j                  |            }|j                         S t        |t        j                        r=| j                  |      }t        |t        j                        r|j                         S |S t        |t        j                        r|j                         S t        |t        j
                        r|j                         S t        j                  |t              j                         S )z%Converts `a` to a nested python list.r  )r   rB   RaggedTensorr
   rC   r  r  to_listr   r   rC  r  tolistr  r  )ri  r   s     r]   
_GetPyListzTensorFlowTestCase._GetPyList  s    !]//0
"44dmmA6F
GaYY[	Az((	)
--
a%a4QXXZ;!;	Arzz	"XXZ	A*<<	=YY[XXav&--//r\   c                 |   | j                  |      }| j                  |      }| j                  |||       t        |t        t        f      sqt        |t        t        f      sZt        j                  |      r|j                  nd}t        j                  |      r|j                  nd}| j                  |||       yyy)z*Asserts that two ragged tensors are equal.r   N)r  r   r   r  r  rB   r  ragged_rank)ri  r   r   rh  r,  r-  a_ragged_rankb_ragged_ranks           r]   r!  z%TensorFlowTestCase._assertRaggedEqual  s    __QF__QFVVS)q4-(Jq4-,H'4'>'>q'Aammqm'4'>'>q'Aammqm
}mS9 -I(r\   c                    | j                  |      }| j                  |      }| j                  |||||       t        |t        t        f      sqt        |t        t        f      sZt        j                  |      r|j                  nd}t        j                  |      r|j                  nd}	| j                  ||	|       y y y r  )	r  _assertListCloseRecursiver   r  r  rB   r  r  r   )
ri  r   r   r  r  rh  r,  r-  r  r  s
             r]   r  z%TensorFlowTestCase._assertRaggedClose  s    __QF__QF""664sCq4-(Jq4-,H'4'>'>q'Aammqm'4'>'>q'Aammqm
}mS9 -I(r\   c                 Z   | j                  t        |      t        |             t        |t        t        f      r[| j                  |t        |      d|z         t        t        |            D ]$  }| j                  ||   ||   ||||d|d       & y | j                  ||||||       y )NzLength differs for %sr  r  )
r   rq   r   r  r  	assertLenr   r_  r  r  )ri  r   r   r  r  rh  r  r  s           r]   r  z,TensorFlowTestCase._assertListCloseRecursive!  s    T!Wd1g&!dE]#
nnQA 7$ >?SV} =!&&qtQqT4s37';	== ##Aq$dC@r\   r  c              #     K   t        j                         rd y|j                  j                         5  |j                         5  |r7t	               }|sd}|j                  j                  |      5  | ddd       n/|r| n(|j                  j                  d      5  | ddd       ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   &xY w# 1 sw Y   *xY w# 1 sw Y   yxY ww)zFSet the session and its graph to global default and constrain devices.Nr  rA  )r$   r  r   r  r}   r)   )ri  r  r5  r  gpu_names        r]   r  z5TensorFlowTestCase._constrain_devices_and_set_default6  s     
   "j::  " DOO$5  %&(&Hzz  * J *zz  1 J   
    sd   4C1C%,C3C8+C#C(C0C%8	C1C
CCCC"	C%%C.*C1c                     dt         t        j                     dt        j                  ffd}t        | ||            S )zSee session() for details.r'   rX   c                     }| &t        j                          j                  } || _        n5|s3| j                  r't        j                          j                  }|} d| _        d| j                  j                  _        t        j                  j                  | j                  j                  _
        t        j                  j                  | j                  j                  _        | S )zReturns a config for sessions.

      Args:
        config: An optional config_pb2.ConfigProto to use to configure the
          session.

      Returns:
        A config_pb2.ConfigProto object.
      Fr   )r$   r'   allow_soft_placementgraph_optionsoptimizer_options	opt_levelr   RewriterConfigOFFrewrite_optionsconstant_foldingpin_to_host_optimization)r'   r  config_copyr  s      r]   prepare_configz:TensorFlowTestCase._create_session.<locals>.prepare_configU  s     "+]	"))&:##(C(Coo'..&+# :<f,,6 
,
,
0
0 **; 
,
,
0
0 **Cmr\   )r   r'   )r   r   ConfigProtor  )ri  r   r'   r  r  s      ` r]   r  z"TensorFlowTestCase._create_sessionM  s>    "//0"			"H U>&3IJJr\   r  c                 8   | j                   2| j                  |||      }|| _         || _        || _        || _        |S |r| j                  |urt        d      |r| j                  |urt        d      |r| j                  |urt        d      | j                   S )z'See cached_session() for documentation.)r   r'   r  zThe graph used to get the cached session is different than the one that was used to create the session. Maybe create a new session with self.session()zThe config used to get the cached session is different than the one that was used to create the session. Maybe create a new session with self.session()zThe force_gpu value used to get the cached session is different than the one that was used to create the session. Maybe create a new session with self.session())r9  r  _cached_graph_cached_config_cached_force_gpur   )ri  r   r'   r  r  r  s         r]   r  z&TensorFlowTestCase._get_cached_session{  s     #!!f	 " ;d!d d"d(dk	#(:(:%(G * + 	+ 
$(;(;6(I * + 	+ 
$)?)?-6*7 	
 !!!r\   )runTestr  r`   NNTF)ư>r  N)r  r  NN)	r  r  r  r  MbP?r  {Gz?r  N)
   r   FF)r   )NNFT)`rr   r  r  r  r  rM  classmethodrL  rK  r?  r"  rZ  
contextlibcontextmanagerr   r  re  rl  r   r7   GRAPH_DEF_VERSIONGRAPH_DEF_VERSION_MIN_CONSUMERrz  r  r  r  r   rC   r  r2   r  r  r   r0   r  r   r  r  r   Sessionr   r  rJ   
deprecatedr  r  r  r   r	   r  r  r  rm  r  r  r  r  r  r  r  r  r  r  r  r1  r3  r9  r<  r?  rB  rK  r^  rb  rg  rq  rs  r+   InvalidArgumentErrorru  r}  r  r  r  r!  r  r  rE   TestCaseassertRaisesRegexassertRaisesRegexpassertCountEqualr  r  r  r  r  r  s   @r]   rW   rW   
  s   :"<(4 , ,
"
C $ *Xn-E * *X< -f ))::
	6!PF:
?++%%
?:  $(15/cii / z--./ 	/
 / 		/ /b  $(153cii 3 z--.3 	3
 3 		3 3j ;$ != > $(15cii  z--. 	
  		> :Z@v Z@~ )-)-	sCx  U38_% tCH~&	
 4 A A" : : 5 	I 	I48Oz %)$($(#'GR G G@  *.)-/3/3.2.22626(,.= .=` O O0 9C 9Cv O O 
5 
5 
2 
2 
: 
: 
7 
7B 
 ).(-8L 8Lt @ @* 2 2 +5 +5^M
 "66*38I . .20	::A "**<<  ((99 ))&*7;		 ,,Kcii ,K z--.,K 	,K
 	yy,K` $(15)-""cii "" z--."" 	""
 #'"" 	yy""r\   ASSIGNED_PORTSc                  6   ddl } t        5  	 	 | j                         }|dkD  r>|t        vr6t        j                  |       t        j                  d|       |cddd       S U# | j                  $ r}t	        j
                  d      |d}~ww xY w# 1 sw Y   yxY w)z,Returns an unused and unassigned local port.r   Nz@Flakes in portpicker library do not represent TensorFlow errors.i'  zUsing local port %r)

portpickerlockpick_unused_portNoFreePortFoundErrorrA  rI  r  addr  rC  )r  port	porterrors      r]   r  r    s      

F**, 
$n44 *D1
 

 ,, F !6 7<E	FF	
 
s3   BA"9B!B"B1BBBBztest.create_local_clusternum_workersnum_psprotocolworker_config	ps_configc                    t        |       D cg c]  }t                }}t        |      D cg c]  }t                }}|D cg c]  }d|z  	 c}|D cg c]  }d|z  	 c}d}	t        j                  |	      }
t        |       D cg c]  }t        j                  |
d|||d       }}t        |      D cg c]  }t        j                  |
d|||d       }}||fS c c}w c c}w c c}w c c}w c c}w c c}w )a  Create and start local servers and return the associated `Server` objects.

  "PS" stands for "parameter server": a task responsible for storing and
  updating the model's parameters. Other tasks send updates to these parameters
  as they work on optimizing the parameters. This particular division of labor
  between tasks is not required, but is common for distributed training.

  Read more at https://www.tensorflow.org/guide/extend/architecture

  ![components](https://www.tensorflow.org/images/diag1.svg "components")


  Figure illustrates the interaction of these components.
  "/job:worker/task:0" and "/job:ps/task:0" are both tasks with worker services.


  Example:
  ```python
  workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2)

  worker_sessions = [tf.compat.v1.Session(w.target) for w in workers]

  with tf.device("/job:ps/task:0"):
    ...
  with tf.device("/job:ps/task:1"):
    ...
  with tf.device("/job:worker/task:0"):
    ...
  with tf.device("/job:worker/task:1"):
    ...

  worker_sessions[0].run(...)
  ```

  Args:
    num_workers: Number of worker servers to start.
    num_ps: Number of PS servers to start.
    protocol: Communication protocol. Allowed values are documented in the
      documentation of `tf.distribute.Server`.
    worker_config: (optional) `tf.ConfigProto` to initialize workers. Can be
      used to instantiate multiple devices etc.
    ps_config: (optional) `tf.ConfigProto` to initialize PS servers.

  Returns:
    A tuple `(worker_servers, ps_servers)`.  `worker_servers` is a list
    of `num_workers` objects of type `tf.distribute.Server` (all running
    locally);
    and `ps_servers` is a list of `num_ps` objects of similar type.

  Raises:
    ImportError: if portpicker module was not found at load time
  zlocalhost:%s)workerpsr  T)job_namer  
task_indexr'   r  r  )r_  r  rG   ClusterSpecServer)r  r  r  r  r  rl  worker_portsps_portsr  cluster_dictcsixworkers
ps_serverss                 r]   create_local_clusterr    s&   x /4K.@A"$A,A*/-8Q 8(83?@4$&@/78t^d"8, l+" !&k 2  
'   !&f  
*  
*	7 B8@8s"   C#C(C-C2
"C7;"C<	node_namec                 L    |j                   D ]  }|j                  | k(  s|c S  y)aN  Returns the `NodeDef` instance for given node name in the graph def.

  This method explores only the NodeDefs in `graph_def.node`.

  Args:
    node_name: Name of the NodeDef to search for.
    graph_def: An instance of `GraphDef` proto.

  Returns:
    the `NodeDef` instance whose name field matches the given node_name or None.
  N)r   r{   )r  r   node_defs      r]   get_node_def_from_graphr    s-     .. h}}	!o 
r\   producer_versionc                     t        j                         }||j                  _        | j	                         5  t        j                  |       ddd       | j                  j                  sJ |       y# 1 sw Y   'xY w)z=Sets graph.graph_def_versions.producer to `producer_version`.N)r   r   r7   rx  r  r.   import_graph_defgraph_def_versions)r   r  r   s      r]   set_producer_versionr  $  sj       ") 0) )i()		!	!	*	*<,<<	*) )s   A22A;c               #   >   K   	  G d d      }  |         y# w xY ww)ztf.gradients(...) implemented as tf.GradientTape context manager interface.

  This is useful to test tf.gradients() in tests that uses tf.GradientTape().

  Yields:
    gradient tape instance that's implemented by tf.gradients() underneath.
  c                       e Zd Zd ZddZy)=_fake_gradient_tape_context_manager.<locals>.FakeGradientTapec                      y r`   r[   )ri  r|   s     r]   watchzC_fake_gradient_tape_context_manager.<locals>.FakeGradientTape.watch;  s    r\   Nc                     t        j                  |||      }t        |t        t        f      st        |      dk(  sJ |d   S |S r   )r<   	gradientsr   r  r  r   )ri  r  r|   grad_ysr^  s        r]   gradientzF_fake_gradient_tape_context_manager.<locals>.FakeGradientTape.gradient>  sG    ))!Q8 !dE]+V!
!!
r\   r`   )rr   r  r  r  r  r[   r\   r]   FakeGradientTaper  9  s    	r\   r  Nr[   )r  s    r]   #_fake_gradient_tape_context_managerr  /  s&     	   
Ds    c                   >    e Zd ZdZddZdej                  fdZd Zy)AbstractGradientTapezAbstract GradientTape context manager that has multiple implementations.

  This is useful to test both tf.GradientTape() and tf.gradients() without
  duplicating tests.
  c                      || _         || _        y r`   )	_use_tape_persistent)ri  use_tape
persistents      r]   r  zAbstractGradientTape.__init__U  s    DN!Dr\   rX   c                     | j                   r&t        j                  | j                        | _        nt               | _        | j                  j                         S )N)r  )r  r#   GradientTaper  
_tape_implr  	__enter__rT  s    r]   r  zAbstractGradientTape.__enter__Y  s>    ~~ --9I9IJdo;=do??$$&&r\   c                 >    | j                   j                  |||       y r`   )r  __exit__)ri  exc_typeexc_valexc_tbs       r]   r  zAbstractGradientTape.__exit__`  s    OOXw7r\   Nr  )	rr   r  r  r  r  r#   r  r  r  r[   r\   r]   r  r  N  s#    "'.. '8r\   r  rD  c              #   t  K   t        | t              st        dj                  |             t	        j
                         }|s| rt        j                  d       t        j                         }t        j                  |        	 d t        j                  |       y# t        j                  |       w xY ww)aF  Runs functions eagerly if `run_eagerly` is true.

  WARNING: Setting `run_eagerly` to True in tests running in V1 graph mode
  *WILL NOT* make the tf.function to run eagerly because eager is disabled by
  default in V1. Instead, tf.function will run as a traced graph function.

  Ensures that the state (for running functions eagerly) is back to the initial
  `def_function.RUN_FUNCTIONS_EAGERLY` state.

  Args:
    run_eagerly: Boolean determining whether to run the function eagerly or not.

  Raises:
    ValueError if `run_eagerly` is not a boolean.

  Yields:
    Nothing.
  z*Expected bool for `run_eagerly` but got {}zrRunning tf.function eagerly in V1 graph mode is not supported. tf.function will be run as a traced graph function.N)r   r  r   r*  r$   r  r  warningr%   functions_run_eagerlyrun_functions_eagerly)rD  is_eagerinitial_states      r]   r  r  d  s     ( 
K	&
4;;KHJ J &&((	kOO	>? 446-$$[16	&&}5L&&}5s   BB8B B8B55B8c                   *    e Zd ZdZd ZddZdefdZy)	TestDeltaz5A utility class to track increments to test counters.c                 @    || _         || _        | j                          y r`   )r{   labelReset)ri  r{   r  s      r]   r  zTestDelta.__init__  s    DIDJJJLr\   rX   Nc                 b    t        j                  | j                  | j                        | _        y r`   r&   test_counter_valuer{   r  
last_valuerT  s    r]   r	  zTestDelta.Reset  s!    (;;		4::DOr\   c                 t    t        j                  | j                  | j                        }|| j                  z
  S r`   r  )ri  r   s     r]   GetzTestDelta.Get  s+    11$))TZZHE4??""r\   rs  )rr   r  r  r  r  r	  r  r  r[   r\   r]   r  r    s    =
#3 #r\   r  ztest.experimental.sync_devicesc                  0   t        j                         st        d      t        j                         } | D ]>  }t        j                  |j                        5  t        j                          ddd       @ t        j                          y# 1 sw Y   _xY w)a  Synchronizes all devices.

  By default, GPUs run asynchronously. This means that when you run an op on the
  GPU, like `tf.linalg.matmul`, the op may still be running on the GPU when the
  function returns. Non-GPU devices can also be made to run asynchronously by
  calling `tf.config.experimental.set_synchronous_execution(False)`. Calling
  `sync_devices()` blocks until pending ops have finished executing. This is
  primarily useful for measuring performance during a benchmark.

  For example, here is how you can measure how long `tf.linalg.matmul` runs:

  >>> import time
  >>> x = tf.random.normal((4096, 4096))
  >>> tf.linalg.matmul(x, x)  # Warmup.
  >>> tf.test.experimental.sync_devices()  # Block until warmup has completed.
  >>>
  >>> start = time.time()
  >>> y = tf.linalg.matmul(x, x)
  >>> tf.test.experimental.sync_devices()  # Block until matmul has completed.
  >>> end = time.time()
  >>> print(f'Time taken: {end - start}')

  If the call to `sync_devices()` was omitted, the time printed could be too
  small. This is because the op could still be running asynchronously when
  the line `end = time.time()` is executed.

  Raises:
    RuntimeError: If run outside Eager mode. This must be called in Eager mode,
      outside any `tf.function`s.
  zFsync_devices() must only be called in Eager mode, outside tf.functionsN)r$   r  r  r'   list_logical_devicesr0   r)   r{   r;   
SyncDevice
async_wait)devicesr  s     r]   sync_devicesr    s    @ 
	"	"	$
P   '')'  c	CHH	       
   s   BB	)r[   r  rs  r`   )r   r  rZ   )rw   r  r  )NTNr  )FN)grpcNN(   r  rm   r   collections.abcr   r   r   r   r   r  r  ro   r  r  r  r@  r   rW  r  rI  typingr	   r
   r   r   r   r   rA  absl.testingr   r  rC  google.protobufr   r   r   tensorflow.core.configr   tensorflow.core.frameworkr   r   r   tensorflow.core.protobufr   r   r   tensorflow.pythonr   r   tensorflow.python.clientr   r   r   r   tensorflow.python.compatr    tensorflow.python.compat.compatr"   tensorflow.python.eagerr#   r$   r%   tensorflow.python.frameworkr&   r'   r)   r  r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r   r4   r5   r6   r7   tensorflow.python.opsr8   r9   r:   r;   r<   r=   r>   r?   r@   tensorflow.python.ops.raggedrA   rB   rC   tensorflow.python.platformrD   rE   rF   r  tensorflow.python.trainingrG   tensorflow.python.utilrH   rI   rJ   rK   rL   rM   rN   tensorflow.python.util.compatrO   #tensorflow.python.util.numpy_compatrP   tensorflow.python.util.protobufrQ    tensorflow.python.util.tf_exportrR   rS   rU   rq   rV   r  r^   ,tensorflow.python.framework.is_xla_test_truer  ra   5tensorflow.python.framework.is_mlir_bridge_test_falseImportError4tensorflow.python.framework.is_mlir_bridge_test_truerc   rf   rh   rj   rn   r"  rt   r}   r  r  NodeDefr   r   r   r   r   MetaGraphDefr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r  r  r  r  r+  r.  r2  r:  rG  rM  rR  rz  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r,  r4  r  r  r  rm  rt  rv  run_deprecated_v1r~  r  r  r  r  r  r  r  r  r  r  r5  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r   r"  r+  r-  rM  rW   r   r  __annotations__Lockr  r  r  r  r  r  r  r  r  r  r  r[   r\   r]   <module>r6     s  " !  # N N   	   	  	    @ @  &  + # ' ( / 2 0 / 3 8 / ! / 6 1 . I , + 0 : . 7 . . 3 0 0 6 + 3 5 < 4 3 2 0 + 3 6 . 0 * , 0 + 4 6 < A 1 < 1 4 ) . ' / - 2 9 8 3 6 T#s(+,T]e4 456 
I 	Z- -
- -
- -
.$ .  Dc]DD !"  #*sCx.),	#|##
#$: (R06  6*3*<*<6	6 16, ,-.  #(	11  1 1 !	1
 
1 /1>  #(	..  . . !	.
 	.6(! (!""(! ""(! 
	(!Z 5 y/A/A d   7 Y-?-? D 1T 1- -, ,- -0:d :*d *86
))49456
:d3i'(6*"0 !2!2DI!=>"0	*

T#Y
&'"0J !2!2DI!=>
:d3i'(D6
))49456
:d3i'(6*uXb$h/56 8RD"H;M 4  -1  Y  CcD()  d^	   F r 
tBx DH 
r b 64c 4c 4n "r0B & r 0 rrxS!"HY$778rj;3R ;3B ;3|p8C= ps pt pfM M M`N4CH0E+F N2 	+c3h
  F# #  C C &"r "b "J" " "JB 2   
 #	b 
"X 
 
"	 tBxj$r("# 
 +,""	$r(	 8T"XJR()4834 -.!2 !" !H&s &s &R+S +XrdBh5G ++3 +"r(: +\2
38
2i2j"   
 04$)	
38
Z++,  "	
 i 
 
/3$)	
Z++,  "	
 xS!"HY$778 
 *./3$)	}
8CH%
&}Z++,} } "	}
 hsCx !8I#667Y}B $($)DC=D!D xS!"HY$778DN3b 3R 30 xS1  hy6I  F 
R B  
 
S Xc]  
)6U37^ )6c2g )6X / 
s 
s 
<~:
9
r b 2 r 2  >"c3m,-"xS!"HY$778"J OQ
"#=A77!)%S/!:7 
7 $Q7t 
D 
Xd^ 
 
 
$ 
 
 
8D> 
 
 
8D> 
 
 $8D> $ $
 
6- 6-r!)) #6 #6 #6N- -"r8J ->
 
2$(); 
%S %XrdBh%7 %%S %XrdBh-? %%c %htRx&8 %%c %htRx&8 %%c %htRx&8 %%s %xb'9 %uS"W~c2tm 4452S!seSj<% %2$(); %!C !HbT2X,> !.xS!"HY$778FH H3%*9M H
#2L	 	    ?X",, X" X"v, 5C  y~~$ &' 6:26VVV V J223	V
 
../V 4
!!"D):):$;;<V (Vr(11l""#(=		 =S =T = 	 	<8 8, "6t "6 "6 "6J# #" +,4 -4EA    		[	 			sH   i !i* i'&i'*j0i76j7i?<j>i??jj