
    BVh             
          U d Z ddlZddl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mZmZmZmZmZmZmZmZm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)m*Z* ddl)m+Z+ ddl)m,Z, ddl-m.Z. ddl/m0Z0 ddl/m1Z1 ddl/m2Z2 ddl/m3Z3 ddl4m5Z5 ddl4m6Z6 ddl4m7Z8 ddl4m9Z9 ddl4m:Z: ddl4m;Z; ddl4m<Z< dd l4m=Z= dd!l4m>Z? dd"l4m@Z@ dd#l4mAZA dd$l4mBZB dd%l4mCZC dd&l4mDZD dd'lEmFZF dd(lEmGZG dd)lHmIZJ dd*lKmLZM ddlNm1ZO dd+lNmPZP dd,lQmRZR dd-lQmSZS dd.lQmTZT dd/lQmUZU dd0lQmVZV dd1lQmWZW dd2lQmXZX dd3lQmYZY dd4lQmZZZ dd5l[m\Z\ dd6l]m^Z^ dd7l_m`Z` dd8l_maZa  ed9      Zb ed:d;<      Zc ed=d><      Zd ed?d@<      Ze edAdB<      ZfdCZgdCZheiejdD<   dCZkeiejdE<    e2j                  dFdG      Zm e2j                  dHdI      Zn e2j                  dJdK      Zoe9j                  Zqere%j                  e9j                  f   ejdL<   dMefdNZu G dO dPev      Zw G dQ dRej                  d         ZydS ZzdMeifdTZ{dMe|fdUZ}ddMe~fdWZddMefdXZ eadY       G dZ d[e.j                  e?j                               ZdMe?j                  fd\Z G d] dBe?j                  ePj
                  eOj                        Z  ead^g _       e+j                  e            Zdd`dae~dbee~   dMe~fdcZddMefddZ eMj                  de      dddVddde?j                  ffdMeeef   fdf       ZeZedgeeef   f   ejdh<   	 	 	 	 	 ddMeeeef      fdiZ	 ddMeeeef      fdjZ	 ddMeeee6j$                  f   fdkZ	 	 	 ddMeeee6j$                  f   fdlZ	 	 	 ddMeeeee6j$                   ed      f      fdmZ	 ddMeeeee6j$                   ed      f      fdnZdMe~fdoZddMe#j2                  fdpZ e	j6                  dq      Zee~   ejdr<    e	j6                  ds      Zee~   ejdt<    eadug _      eZj<                  	 	 ddMe.j>                  fdv              Z ead@       G dw d@e.jB                               Ze<jF                  ejdx<   e<jF                  ejdy<    e<jF                  dz      xZZ ead{       G d| d{ev             Z eTjN                  d}d~       eadg d_      de~dMdfd              ZeZee~gdf   ejd~<   eZee~gdf   ejd}<   d ZddZ G d d>ev      Z e<jF                  d      Ze<jF                  ejd<    G d dev      ZdMefdZdMe~fdZdZe|ejd<   dZe|ejd<   eXjh                  dMed   fd       Z ead;       G d d;e.jl                               Z eadg_      dMed   fd       Z7 eadg _      dMed   fd       Z eadg_      dMee~   fd       Z	 ddMed   fdZddMed   fdZ eTjx                  dd       eadg_      ddMed   fd              Z ead      dMej|                  fd       Ze=j                  Z	 d	 ddZ G d de=j                  e         Z eë       Zeejd<   dMeeg ee   f   eCj                  f   fdZ ead      eXjh                  dMed   fd              Z eadg_      dMeifd       Z eadg _      dMeifd       Z eadg_      	 	 d	 dd       Z eadg_      dd       Z	 	 	 	 d	 ddZddMefdZ eadg_      dd       Z eadg_      dMefd       ZdMeifdZ eadg _      dMe~fd       ZddZddMefdZ eadg_       G d dev             ZddZ eadg_      dd       Z eadg_      dd       Z eadg_      dMee   fd       Z eadg_      ddMee   fd       ZdMee~   fdÄZ	 ddMeee~      fdĄZ G dń dej                  e~         Z eadg_       G dȄ dej                  ee~                   Z eadg _      dMe~fd˄       Z eadg _       G d̄ dej                  e~                Zdbe~dMe~fd΄Zdbe~dMe~fdτZ eadg_      eXjh                  ddMeee~      fdф              Z e<jF                  dҫ      Z	 	 	 d	 ddӄZdMeeej                        fdԄZdMeeegej                  f      fdՄZdMeeej                  gef      fdքZdMeee   eeg df      f   fdׄZdej                  dMedgef   fdلZdMefdڄZddۄZdMeee?j                  ee?j                     f      fd܄Z G d݄ dej                        Zej                  aeejd<   dMefdZdMeifdZdMeifdZddZdMefdZdMe~fdZdVaeiejd<   ddZddZdMefdZeGj                  ZddZ eaddg_      dMeifd       Z y)z/Classes and functions used to construct graphs.    N)CallableIteratorSequence)	castTypeVarAnyAnyStrNoReturnOptionalPatternUnionContextManager)app)typing)message)attr_value_pb2)full_type_pb2)function_pb2)	graph_pb2)node_def_pb2)
op_def_pb2)	types_pb2)versions_pb2)
config_pb2)pywrap_tensorflow)
pywrap_tfe)tf2)pywrap_tf_session)context)core)
monitoring)record)
c_api_util)composite_tensor)device)dtypes)errors)op_callbacks)registry)stacktensor)tensor_conversion_registry)tensor_shape)tensor_util)traceable_stack)versions)control_flow_util)handle_data_util)
tf_logging)trace)internal)compat)decorator_utils)deprecation)function_utils)	lock_util)object_identity)tf_contextlib)tf_stack)traceback_utils)collections_abc)deprecated_args)
kwarg_only)	tf_export_T	GraphTypeGraph)boundOpStatsTypeOpStatsOperationType	OperationEagerTensorType_EagerTensorBaseT
_USE_C_API_USE_C_SHAPESz#/tensorflow/api/ops_eager_executionz/Whether ops.enable_eager_execution() is called.z&/tensorflow/api/enable_control_flow_v2z+Whether enable_control_flow_v2() is called.z/tensorflow/api/tf_functionzWhether tf.function() is used._DTYPES_INTERN_TABLEreturnc                     | j                   S )z,Returns a unique identifier for this Tensor.)_idr+   s    O/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/framework/ops.py	tensor_idrU   z   s    	    c                   $    e Zd ZdZddZdefdZy)_UserDeviceSpeczEStore user-specified device and provide computation of merged device.rQ   Nc                    || _         t        | j                         | _        || _        d | _        t        |t        j                        r|j                  | _        nt        |      rjd| _        | j                   }t        j                  |      }t        j                  |      }|r|j                  }|j                  }nd}d}d|||fz  | _        nF|d| _        n<|| _        t        j                  |      | _        | j                  j                  | _        t        | j                  t        j                        | _        y )NFunknownz
%s<%s, %d>)_device_name_or_functionstrdisplay_namefunction
raw_string
isinstancepydevMergeDeviceis_null_mergecallabler:   get_func_nameget_func_codeco_filenameco_firstlinenomerge_devicefast_string_merge)selfdevice_name_or_functiondev_func	func_name	func_codefnamelinenos          rT   __init__z_UserDeviceSpec.__init__   s   $;D!D99:D+DMDO)5+<+<=2@@d	)	* d..h ..x8i ..x8i	%%))&)UF)CCd	 	( !d 0do(()@Adm==66d (u7H7HIDrV   c                     | j                   r| j                  j                  |      S t        j                  t        | j                  |                  S N)rk   r_   shortcut_string_merger7   as_str_device_string)rl   node_defs     rT   string_mergez_UserDeviceSpec.string_merge   s=    ]]00::==h(?@AArV   rQ   N)__name__
__module____qualname____doc__rs   r]   rz    rV   rT   rX   rX      s    M#JJBc BrV   rX   c                   (    e Zd ZddZddZdefdZy)NullContextmanagerrQ   Nc                      y ru   r   )rl   argskwargss      rT   rs   zNullContextmanager.__init__       rV   c                      y ru   r   rl   s    rT   	__enter__zNullContextmanager.__enter__   r   rV   c                      yNFr   rl   type_arg	value_argtraceback_args       rT   __exit__zNullContextmanager.__exit__   s    rV   r{   )r|   r}   r~   rs   r   boolr   r   rV   rT   r   r      s    		D rV   r   c                 F    t        | dd      }|rt        |      r |       S y)zConvert `obj` to a graph element if possible, otherwise return `None`.

  Args:
    obj: Object to convert.

  Returns:
    The result of `obj._as_graph_element()` if that method is available;
        otherwise `None`.
  _as_graph_elementN)getattrre   )objconv_fns     rT   r   r      s(     C,d3''"9	rV   c                 6    t        | t        j                        S ru   )ra   core_tf_typesTensor)ts    rT   is_dense_tensor_liker      s    	A}++	,,rV   c                  *    t        j                         S )z1A unique (within this program execution) integer.)r   
TFE_Py_UIDr   rV   rT   uidr      s    				  rV   Fc                    | j                   j                  ri| j                         }|rKt        j                  |      r*t        |t              st        |j                               }nt        |      }nt        |      }nd}d|v rd|z   }|S )z8Human readable representation of a tensor's numpy value.<unprintable>
)
dtypeis_numpy_compatible_numpynpisscalarra   bytesrepritemr]   )r,   is_reprtensor_numpytexts       rT   
numpy_textr      su    \\%%==?L	\	":lE+JL%%'(L!d D	T\$;D	+rV   c                     | j                         r| j                         }|rd|z   }|S t        | |      }|rd|z   }|S )aQ  Either the NumPy value or a custom TensorFlow formatting of `tensor`.

  Custom formatting is used for custom device tensors, e.g. parallel tensors
  with multiple components on different devices.

  Args:
    tensor: The tensor to format.
    is_repr: Controls the style/verbosity of formatting.

  Returns:
    The formatted tensor.
  zvalue=r   znumpy=)_prefer_custom_summarizer_summarize_valuer   )r,   r   r   s      rT   
value_textr      sP     %%'""$D_d
 
+ fg.D_d	+rV   z__internal__.SymbolicTensorc                   "    e Zd ZdZdddZddZy)SymbolicTensorz.A symbolic tensor from a graph or tf.function.Nc                     |
t               }t        j                  j                  t        ||t        j                  |      |      S ru   )r   r   PyTensor__new__r   r&   as_dtype)clsopvalue_indexr   	unique_ids        rT   r   zSymbolicTensor.__new__  s<    %i%%--K)? rV   c                     | j                   }|j                  || j                  | j                  | j                  | j
                        }|j                  j                  | j                         |S ru   )	__class__r   r   r   r   rS   __dict__update)rl   r   results      rT   __copy__zSymbolicTensor.__copy__  sN    
..C[[dggt'7'7TXXNF
OO4==)MrV   ru   )rQ   r   )r|   r}   r~   r   r   r   r   rV   rT   r   r     s    6rV   r   c           	         t               }t        j                         }|j                  j	                  t        j                  | ||||             t        j                  |j                  j                        }||d}	|j                  dg |j                  g|	|      j                  d   }
t        j                         r*t        j                  dt               |	|
f||      }||\  }
|
S )z6Create a graph constant and invoke constant callbacks.)r   shapeverify_shapeallow_broadcasttype)valuer   Const)attrsnamer   )op_namegraph)get_default_graphr   	AttrValuer,   CopyFromr/   make_tensor_protor   _create_op_internalr   outputsr(   should_invoke_op_callbacksinvoke_op_callbackstuple)r   r   r   r   r   r   gtensor_valuedtype_valuer   const_tensorcallback_outputss               rT   _create_graph_constantr     s     !))+,##
uE)+, ((l.A.A.G.GH+ ;
7%&&rK$$%U ' ??FwqJ, ,,. $77%,$aI#'n|	rV   c                       e Zd ZdZdefdZdefdZdefdZ	defdZ
defdZeZdefdZd	 Zd
edefdZd
edefdZdefdZdefdZdefdZd5dej0                  fdZdefdZdej8                  fdZdej8                  fdZede jB                  fd       Z"dej8                  fdZ#ed        Z$de%fdZ&de%fdZ'de%fdZ(de%fdZ)de%fdZ*e+d6d       Z,	 d7d
edefdZ-	 d7d
edefdZ.ede/j`                  fd        Z1de/j`                  fd!Z2de3e   fd"Z4 e5jl                  dd#      d
edefd$       Z7 e5jl                  dd%      d8d
edefd&       Z8d6d'Z9ede%fd(       Z:ede%fd)       Z;ede%fd*       Z<ede%fd+       Z=de%fd,Z>de%fd-Z?de%fd.Z@de%fd/ZAd7de%fd0ZB	 d7d1eCe jB                     d2eCe   deDj                  f fd3ZFdeCeDj                     fd4ZG xZHS )9rM   zBase class for EagerTensor.rQ   c                 4    t        | j                               S ru   )complexr   r   s    rT   __complex__z_EagerTensorBase.__complex__4  s    4;;=!!rV   c                 4    t        | j                               S ru   )intr   r   s    rT   __int__z_EagerTensorBase.__int__7  s    t{{}rV   c                 4    t        | j                               S ru   )floatr   r   s    rT   	__float__z_EagerTensorBase.__float__:  s    rV   c                 n    t        t        j                  | j                               j	                         S ru   )r   r   ndarrayr   	__index__r   s    rT   r   z_EagerTensorBase.__index__=  s"    

DKKM*4466rV   c                     | j                         }t        |t        j                        rt	        |j
                  dkD  xr |      S t	        |      S Nr   )r   ra   r   r   r   sizerl   xs     rT   __bool__z_EagerTensorBase.__bool__@  s<    A!RZZ !&&1*"##!WnrV   c                     | j                         r| j                         j                  |      S | j                  j                  r| j                         j                  |      S dj                  |      S )Nr   )r   r   
__format__r   r   r   )rl   format_specs     rT   r   z_EagerTensorBase.__format__I  s]    %%'""$//<<		'	'[[]%%k22''44rV   c                 0    t         | j                         ffS ru   )convert_to_tensorr   r   s    rT   
__reduce__z_EagerTensorBase.__reduce__R  s    t{{}...rV   rl   c                     | S ru   r   r   s    rT   r   z_EagerTensorBase.__copy__U      KrV   c                     ~| S ru   r   )rl   memos     rT   __deepcopy__z_EagerTensorBase.__deepcopy__Y  s
    KrV   c                 l    dt        | d      d| j                  d| j                  j                  dS )Nz
tf.Tensor(Fr   z, shape=, dtype=))r   r   r   r   r   s    rT   __str__z_EagerTensorBase.__str__^  s(    4'TZZ__F FrV   c           	      l    d| j                   d| j                  j                  dt        | d      dS )Nz<tf.Tensor: shape=r   z, Tr   >)r   r   r   r   r   s    rT   __repr__z_EagerTensorBase.__repr__b  s(    

DJJOOZd%CE ErV   c                     | j                   j                  st        d      	 | j                         d   S # t        j
                  $ r}t	        j                  |      dd}~ww xY w)z8Returns the length of the first dimension in the Tensor.zScalar tensor has no `len()`r   N)r   ndims	TypeError_shape_tupler    _NotOkStatusException_status_to_exceptionrl   es     rT   __len__z_EagerTensorBase.__len__f  s]    ::4553 ##%% 3%%a(d23s   6 A$	AA$Nc                     | j                         }|st        t        j                  |      S t        j                  ||      S )N)r   )r   r   r   r   array)rl   r   as      rT   	__array__z_EagerTensorBase.__array__p  s2    A"**a  88AU##rV   c                     t        d      )Nz;Tensor is unhashable. Instead, use tensor.ref() as the key.)r  r   s    rT   __hash__z_EagerTensorBase.__hash__w  s    
 < = =rV   c                     t               ru   NotImplementedErrorr   s    rT   _numpy_internalz _EagerTensorBase._numpy_internal|      

rV   c                     	 | j                         S # t        j                  $ r}t        j                  |      d d }~ww xY wru   )r  r    r  r  r	  s     rT   r   z_EagerTensorBase._numpy  s?    3!!##%% 3%%a(d23s    A ;A c                 D    t         j                  | j                            S ru   )r&   _INTERN_TABLE_datatype_enumr   s    rT   r   z_EagerTensorBase.dtype  s      3 3 566rV   c                 z    | j                         }t        |t        j                        r|j	                         S |S )a  Copy of the contents of this Tensor into a NumPy array or scalar.

    Unlike NumPy arrays, Tensors are immutable, so this method has to copy
    the contents to ensure safety. Use `memoryview` to get a readonly
    view of the contents without doing a copy:

    >>> t = tf.constant([42])
    >>> np.asarray(memoryview(t))
    array([42], dtype=int32)

    Note that `memoryview` is only zero-copy for Tensors on CPU. If a Tensor
    is on GPU, it will have to be transferred to CPU first in order for
    `memoryview` to work.

    Returns:
      A NumPy array of the same shape and dtype or a NumPy scalar, if this
      Tensor has rank 0.

    Raises:
      ValueError: If the dtype of this Tensor does not have a compatible
        NumPy dtype.
    )r   ra   r   r   copy)rl   	maybe_arrs     rT   numpyz_EagerTensorBase.numpy  s.    0 I))RZZ@9>>OiOrV   c                     t               )a  Returns the name of the device holding this tensor's memory.

    `.backing_device` is usually the same as `.device`, which returns
    the device on which the kernel of the operation that produced this tensor
    ran. However, some operations can produce tensors on a different device
    (e.g., an operation that executes on the GPU but produces output tensors
    in host memory).
    r  r   s    rT   backing_devicez_EagerTensorBase.backing_device       
rV   c                     t               ru   r  r   s    rT   r  z_EagerTensorBase._datatype_enum  r  rV   c                     t               )a  The shape of this Tensor, as a tuple.

    This is more performant than tuple(shape().as_list()) as it avoids
    two list and one object creation. Marked private for now as from an API
    perspective, it would be better to have a single performant way of
    getting a shape rather than exposing shape() and shape_tuple()
    (and heaven forbid, shape_list() etc. as well!). Punting on that for now,
    but ideally one would work things out and remove the need for this method.

    Returns:
      tuple with the shape.
    r  r   s    rT   r  z_EagerTensorBase._shape_tuple  s     
rV   c                     t               )zInteger rank of this Tensor.

    Unlike regular Tensors, the rank is always known for EagerTensors.

    This is more performant than len(self._shape_tuple())

    Returns:
      Integer rank
    r  r   s    rT   _rankz_EagerTensorBase._rank  r!  rV   c                     t               )zNumber of elements of this Tensor.

    Unlike regular Tensors, the number of elements is always known for
    EagerTensors.

    This is more performant than tensor.shape.num_elements

    Returns:
      Long - num elements in the tensor
    r  r   s    rT   _num_elementsz_EagerTensorBase._num_elements  s     
rV   c                     t               ru   r  )rl   device_names     rT   _copy_to_devicez _EagerTensorBase._copy_to_device  r  rV   c                 &    t        t        | |       y ru   )setattrrM   )r   funcs     rT   _override_operatorz#_EagerTensorBase._override_operator  s    dD)rV   c                     |t        j                          }||j                  }	 |j                          | j                  |      }|S # t        j
                  $ r}t	        j                  |      dd}~ww xY w)z?Copies tensor to dest device, but doesn't record the operation.N)r   r)  ensure_initializedr*  r    r  r  )rl   ctxr)  
new_tensorr
  s        rT   _copy_nogradz_EagerTensorBase._copy_nograd  sx    
 {OOcOOk3	''4j  %% 3%%a(d23s   !A	 	A7A22A7c                     | j                  ||      }t        j                         r+| j                  fd}t	        j
                  d|g| g|       |S )zCopies tensor to dest device.c                 H    t        | d      r| j                        gS | gS )N_copyr)  )hasattrr6  )dresultself_devices    rT   grad_funz(_EagerTensorBase._copy.<locals>.grad_fun  s6     w( MMkM2
 	
.5
 	
rV   r6  )r3  r   executing_eagerlyr%   r"   record_operation)rl   r1  r)  r2  r;  r:  s        @rT   r6  z_EagerTensorBase._copy  sQ     ""34J  "KKk
 g
|dVXFrV   c                     | j                   5	 t        j                  | j                               | _         | j                   S | j                   S # t        j
                  $ r}t	        j                  |      d d }~ww xY wru   )_tensor_shaper.   TensorShaper  r    r  r  r	  s     rT   r   z_EagerTensorBase.shape  su    !5 *55d6G6G6IJ 4 '' 5''*45s   (A A<!A77A<c                     | j                   S )zAlias of Tensor.shape.r   r   s    rT   	get_shapez_EagerTensorBase.get_shape      ::rV   c                 4    t        | j                               S )z"The shape of the tensor as a list.)listr  r   s    rT   _shape_as_listz_EagerTensorBase._shape_as_list  s    !!#$$rV   z7Use tf.identity with explicit device placement instead.c                 J    | j                  t        j                         d      S )z:A copy of this Tensor with contents backed by host memory.zCPU:0)r6  r   r   s    rT   cpuz_EagerTensorBase.cpu  s     ::goo'11rV   zUse tf.identity instead.c                 b    | j                  t        j                         dt        |      z         S )a  A copy of this Tensor with contents backed by memory on the GPU.

    Args:
      gpu_index: Identifies which GPU to place the contents on the returned
        Tensor in.

    Returns:
      A GPU-memory backed Tensor object initialized with the same contents
      as this Tensor.
    zGPU:)r6  r   r]   )rl   	gpu_indexs     rT   gpuz_EagerTensorBase.gpu#  s%     ::goo'#i.)@AArV   c                 N   t        j                  |      }|j                  }|y | j                  j                  }t	        |      t	        |      k7  rt        d| j                   d| d      t        ||      D ])  \  }}|	||k7  st        d| j                   d| d       y )NzTensor's shape z' is not compatible with supplied shape .)r.   as_shape_dimsr   len
ValueErrorzip)rl   r   
shape_dims	self_dims	shape_dimself_dims         rT   	set_shapez_EagerTensorBase.set_shape1  s    !!%(EJ

  I
:#i.( 5..3WA7 8 8":y9 :	8		8y#8?4::, 7005wa9 : 	::rV   c                     t        d      )Nz7Tensor.op is undefined when eager execution is enabled.AttributeErrorr   s    rT   r   z_EagerTensorBase.opB  s    
AC CrV   c                     t        d      )Nz:Tensor.graph is undefined when eager execution is enabled.rZ  r   s    rT   r   z_EagerTensorBase.graphG  s    
DF FrV   c                     t        d      )Nz9Tensor.name is undefined when eager execution is enabled.rZ  r   s    rT   r   z_EagerTensorBase.nameL  s    
CE ErV   c                     t        d      )Nz@Tensor.value_index is undefined when eager execution is enabled.rZ  r   s    rT   r   z_EagerTensorBase.value_indexQ  s    
JL LrV   c                     t        d      )Nz>Tensor.consumers is undefined when eager execution is enabled.r  r   s    rT   	consumersz_EagerTensorBase.consumersV  s    
HJ JrV   c                     t        d      )Nz<_add_consumer not supported when eager execution is enabled.r  )rl   consumers     rT   _add_consumerz_EagerTensorBase._add_consumerZ      
FH HrV   c                     t        d      )NzA_as_node_def_input not supported when eager execution is enabled.r  r   s    rT   _as_node_def_inputz#_EagerTensorBase._as_node_def_input^  s    
KM MrV   c                     t        d      )Nz<_as_tf_output not supported when eager execution is enabled.r  r   s    rT   _as_tf_outputz_EagerTensorBase._as_tf_outputb  rd  rV   c                     t        d      )Nz[eval is not supported when eager execution is enabled, is .numpy() what you're looking for?r  rl   	feed_dictsessions      rT   evalz_EagerTensorBase.evalf  s    
	/0 0rV   r   r   c                     t        j                         s?t               }|j                  st	        t        d|            |j                  | |      S t        | !  ||      S )NzAAttempting to capture an EagerTensor without building a function.r   )	r   r<  r   building_functionRuntimeError_add_error_prefixcapturesuper__tf_tensor__)rl   r   r   r   r   s       rT   ru  z_EagerTensorBase.__tf_tensor__k  sf     $$&!e$$' 	
 ]]4d]++7 --rV   c           	          t        d      5  t        j                  |       }|
	 ddd       yt        || j                  | j
                  |dd      }ddd       |S # 1 sw Y   S xY w)z3Capture the EagerTensor to a graph constant tensor.NFT)r   r   r   r   r   )control_dependenciesr/   constant_valuer   r   r   )rl   r   rx  r   s       rT   _capture_as_constz"_EagerTensorBase._capture_as_consty  sq    	d	# 
4"11$7n		 
4 
4 ,


$**4d4l
4 
4 s   A%AA'ru   r{   NNr   )Ir|   r}   r~   r   r   r   r   r   r   r   r   r   r   __nonzero__r]   r   r   rL   r   r   r   r  r  r   r   r  r  npt	ArrayLiker  r   propertyr&   DTyper   r  r   r
   r  r  r%  r'  r*  staticmethodr.  r3  r6  r.   r@  r   rC  rF  rG  r9   
deprecatedrI  rL  rX  r   r   r   r   r`  rc  rf  rh  rm  r   
tensor_libr   ru  ry  __classcell__r   s   @rT   rM   rM   .  sl   #"7 "s    7 7  +5s 5/_   ? 
Fs FE E3s 3$RZZ $= =
 s}}  3cmm 3 7V\\ 7 7
PS]] P6 	  	  h   H  
 X 
  X   H   * * 48$ 48& 
\-- 
 
11 %d3i % ;
EG2 2O 2G2 ;$ :;B B B <B:" C( C C FX F F EH E E L8 L LJ JHx HM( MHX H0( 0 IM.FLL).8@..x
0A0A'B rV   z__internal__.EagerTensor)v1ro  msgr   c                    || S | d|  S )N: r   )r  r   s     rT   rr  rr    s    2TF"SE"22rV   c           	      &   t        | t              st        dt        |              | st	        d      | d   j
                  }| d   j                  }| d   j                  }|t        j                  k(  }t        t        |             D ]  }| |   }t        |t              st        dt        |       d      |j
                  |k7  rt	        d| d| d|j
                         |j                  |k7  rt	        d	| d| d
|j                         |s|j                  |k7  st	        d| d| d|j                          |t        j                         }|j                  |       }|||_        d }	t        j                   d|g| |	       |S )zPack multiple `EagerTensor`s of the same dtype and shape.

  Args:
    tensors: a list of EagerTensors to pack.
    ctx: context.context().

  Returns:
    A packed EagerTensor.
  z"tensors must be a list, but got a z%Cannot pack an empty list of tensors.r   zDAll tensors being packed must be EagerTensor. Found an item of type rN  z4All tensors being packed should have the same dtype z
, but the z-th tensor is of dtype z4All tensors being packed should have the same shape z-th tensor is of shape z:All tensors being packed should have the same handle data z-th tensor is of handle data c                     t        d      )Nz@Computing gradients through pack_eager_tensors is not supported.)rR  _s    rT   r;  z$pack_eager_tensors.<locals>.grad_fun  s    
JL LrV   pack_eager_tensors)ra   rF  r  r   rR  r   r   _handle_datar&   resourcerangerQ  EagerTensorr   r  r"   r=  )
tensorsr1  r   r   handle_datais_resourceir   packed_tensorr;  s
             rT   r  r    s    
GT	"
8gH
II	
<
==
!*

%
!*

%
''+(+W Ga
Aa% //3Awiq: ; ; 	ww%@ HC.qwwi9: : 	ww%@ HC.qwwi9: : q~~4FM C4Q^^4DFG G!G, 	[
//
C ((1-!,ML 	."$ 
rV   r   c                 B    |xs |}t        j                  | |||||      S )z/Implementation of the public convert_to_tensor.)r-   convert)r   r   r   as_refpreferred_dtype
dtype_hintr1  accepted_result_typess           rT   r   r     s/     $1z/	#	+	+UD&/3H
 rV   .internal_convert_to_tensorc           
          t        | t        j                        st        d      g }t	        |       D ]/  \  }}|dnd||fz  }	|j                  t        |||	||             1 |S )a:  Converts `values` to a list of `Tensor` objects.

  Args:
    values: A list of objects that can be consumed by `tf.convert_to_tensor()`.
    dtype: (Optional.) The required `DType` of the returned `Tensor` objects.
    name: (Optional.) A name prefix to used when a new `Tensor` is created, in
      which case element `i` will be given the name `name + '_' + i`.
    as_ref: True if the caller wants the results as ref tensors.
    preferred_dtype: Optional element type for the returned tensors, used when
      dtype is None. In some cases, a caller may not have a dtype in mind when
      converting to a tensor, so preferred_dtype can be used as a soft
      preference.  If the conversion to `preferred_dtype` is not possible, this
      argument has no effect.
    ctx: Unused. Present for API backwards compatibility.

  Returns:
    A list of `Tensor` and/or `IndexedSlices` objects.

  Raises:
    TypeError: If no conversion function is registered for an element in
      `values`.
    RuntimeError: If a registered conversion function returns an invalid
      value.
  values must be a sequence.N%s_%d)r   r   r  r  )ra   r@   r   r  	enumerateappendr   )
valuesr   r   r  r  r1  retr  r   ns
             rT   internal_convert_n_to_tensorr    s|    @ 
FO44	5
0
11
#F# .ha'T1I"5AJJ+	-.. 
*rV   c                 "    t        | |||d      S )a  Converts `values` to a list of `Tensor` objects.

  Args:
    values: A list of objects that can be consumed by `tf.convert_to_tensor()`.
    dtype: (Optional.) The required `DType` of the returned `Tensor` objects.
    name: (Optional.) A name prefix to used when a new `Tensor` is created, in
      which case element `i` will be given the name `name + '_' + i`.
    preferred_dtype: Optional element type for the returned tensors, used when
      dtype is None. In some cases, a caller may not have a dtype in mind when
      converting to a tensor, so preferred_dtype can be used as a soft
      preference.  If the conversion to `preferred_dtype` is not possible, this
      argument has no effect.

  Returns:
    A list of `Tensor` and/or `IndexedSlices` objects.

  Raises:
    TypeError: If no conversion function is registered for an element in
      `values`.
    RuntimeError: If a registered conversion function returns an invalid
      value.
  F)r  r   r   r  r  )r  )r  r   r   r  s       rT   convert_n_to_tensorr    s     2 
&%
 rV   c                      t        | ||d      S )aj  Converts the given object to a `Tensor` or `CompositeTensor`.

  If `value` is a `CompositeTensor` it is returned unmodified. Otherwise, it
  is converted to a `Tensor` using `convert_to_tensor()`.

  Args:
    value: A `CompositeTensor` or an object that can be consumed by
      `convert_to_tensor()`.
    dtype: (Optional.) The required `DType` of the returned `Tensor` or
      `CompositeTensor`.
    name: (Optional.) A name to use if a new `Tensor` is created.

  Returns:
    A `Tensor` or `CompositeTensor`, based on `value`.

  Raises:
    ValueError: If `dtype` does not match the element type of `value`.
  F)r   r   r   r  )'internal_convert_to_tensor_or_composite)r   r   r   s      rT   convert_to_tensor_or_compositer  9  s    * 
1T%
9 9rV   c                    t        | t        j                        rzt        | dd      }|rit	        j
                  |      j                  |      sEt        dt	        j
                  |      j                   d| j                  j                   d|       | S t        | |||t        j                  t        j                  f      S )a  Converts the given object to a `Tensor` or `CompositeTensor`.

  If `value` is a `CompositeTensor` it is returned unmodified.  Otherwise, it
  is converted to a `Tensor` using `convert_to_tensor()`.

  Args:
    value: A `CompositeTensor`, or an object that can be consumed by
      `convert_to_tensor()`.
    dtype: (Optional.) The required `DType` of the returned `Tensor` or
      `CompositeTensor`.
    name: (Optional.) A name to use if a new `Tensor` is created.
    as_ref: True if the caller wants the results as ref tensors.

  Returns:
    A `Tensor` or `CompositeTensor`, based on `value`.

  Raises:
    ValueError: If `dtype` does not match the element type of `value`.
  r   Nz5Tensor conversion dtype mismatch. Requested dtype is z, Tensor has dtype r  )r   r   r  r  )ra   r$   CompositeTensorr   r&   r   is_compatible_withrR  r   r   r   r  r   )r   r   r   r  value_dtypes        rT   r  r  R  s    0 '778%$/KV__U+>>{K --3__U-C-H-H,I J++0;;+;+;*<BuiI J J L/??AB BrV   c           	          t        | t        j                        st        d      g }t	        |       D ]B  \  }}||j                  |       |dnd||fz  }|j                  t        ||||             D |S )aI  Converts `values` to a list of `Tensor` or `CompositeTensor` objects.

  Any `CompositeTensor` objects in `values` are returned unmodified.

  Args:
    values: A list of `None`, `CompositeTensor`, or objects that can be consumed
      by `convert_to_tensor()`.
    dtype: (Optional.) The required `DType` of the returned `Tensor`s or
      `CompositeTensor`s.
    name: (Optional.) A name prefix to used when a new `Tensor` is created, in
      which case element `i` will be given the name `name + '_' + i`.
    as_ref: True if the caller wants the results as ref tensors.

  Returns:
    A list of `Tensor`, `CompositeTensor`, and/or `None` objects.

  Raises:
    TypeError: If no conversion function is registered for an element in
      `values`.
    RuntimeError: If a registered conversion function returns an invalid
      value.
  r  Nr  )r   r   r  )ra   r@   r   r  r  r  r  )r  r   r   r  r  r  r   r  s           rT   )internal_convert_n_to_tensor_or_compositer  {  s    : 
FO44	5
0
11
#F# :ha}	jj,$GtQi$7a	jj
15q9:: 
*rV   c                      t        | ||d      S )a   Converts `values` to a list of `Output` or `CompositeTensor` objects.

  Any `CompositeTensor` objects in `values` are returned unmodified.

  Args:
    values: A list of `None`, `CompositeTensor``, or objects that can be
      consumed by `convert_to_tensor()`.
    dtype: (Optional.) The required `DType` of the returned `Tensor`s or
      `CompositeTensor`s.
    name: (Optional.) A name prefix to used when a new `Tensor` is created, in
      which case element `i` will be given the name `name + '_' + i`.

  Returns:
    A list of `Tensor` and/or `CompositeTensor` objects.

  Raises:
    TypeError: If no conversion function is registered for an element in
      `values`.
    RuntimeError: If a registered conversion function returns an invalid
      value.
  F)r  r   r   r  )r  )r  r   r   s      rT    convert_n_to_tensor_or_compositer    s    2 
35tE
; ;rV   c                 P    t        j                  |       r| j                         S | S ru   )rb   is_device_spec	to_string)dev_specs    rT   rx   rx     s$    
(#OrV   c                     t        j                  t        j                  |       t        j                  |            }|r6|j	                         D ]#  \  }}|j
                  |   j                  |       % |S )a  Create a NodeDef proto.

  Args:
    op_type: Value for the "op" attribute of the NodeDef proto.
    name: Value for the "name" attribute of the NodeDef proto.
    attrs: Dictionary where the key is the attribute name (a string)
      and the value is the respective "attr" attribute of the NodeDef proto (an
      AttrValue).

  Returns:
    A node_def_pb2.NodeDef protocol buffer.
  )r   r   )r   NodeDefr7   as_bytesitemsattrr   )op_typer   r   ry   kvs         rT   _NodeDefr    sc     !!V__W%='-t'<>(
 #1mmA"#	/rV   z!^[A-Za-z0-9.][A-Za-z0-9_.\\/>-]*$_VALID_OP_NAME_REGEXz^[A-Za-z0-9_.\\/>-]*$_VALID_SCOPE_NAME_REGEXz__internal__.create_c_opc           	         || j                  |j                        }t        |||j                        }| j                  j                         5 }t        j                  |t        j                  |j                        t        j                  |j                              }ddd       |j                  r3t        j                  t        j                  |j                               |D ]o  }t        |t        t        f      r3t        j                   |D 	cg c]  }	|	j#                          c}	       Lt        j$                  |j#                                q |D ]"  }
t        j&                  |
j(                         $ |j                  j+                         D ]?  \  }}|j-                         }t        j.                  t        j                  |      |       A 	 t        j0                        }|r*t        j:                  |t=        j>                  d             |S # 1 sw Y   xY wc c}	w # t2        j4                  $ r}t7        |j8                        d}~ww xY w)ah  Creates a TF_Operation.

  Args:
    graph: a `Graph`.
    node_def: `node_def_pb2.NodeDef` for the operation to create.
    inputs: A flattened list of `Tensor`s. This function handles grouping
      tensors into lists as per attributes in the `node_def`.
    control_inputs: A list of `Operation`s to set as control dependencies.
    op_def: Optional. `op_def_pb2.OpDef` for the operation to create. If not
      specified, is looked up from the `graph` using `node_def.op`.
    extract_traceback: if True, extract the current Python traceback to the
      TF_Operation.

  Returns:
    A wrapped TF_Operation*.
  N   )
stacklevel) op_def_for_typer   _reconstruct_sequence_inputsr  _c_graphgetr   TF_NewOperationr7   rw   r   r%   TF_SetDevicera   rF  r   TF_AddInputListrh  TF_AddInputTF_AddControlInput_c_opr  SerializeToStringTF_SetAttrValueProtoTF_FinishOperationr'   InvalidArgumentErrorrR  r   TF_SetOpStackTracer>   extract_stack)r   ry   inputscontrol_inputsop_defextract_tracebackc_graphop_descop_inputr   control_inputr   
attr_value
serializedc_opr
  s                   rT   _create_c_opr    s   0 ^""8;;/F (F&~~ Nw//06hkk0J06hmm0LNGN __""7FMM(//,JK Gh(T5M*''DL(Mq):(MO ##GX-C-C-EFG & Gm((-2E2EFG
 #----/ 7dJ--/J **7FMM$4G+57	7 //8D ((h$$2 
+QN N )N& 
	$	$  
QYY
 s+   AH#H0 H5 #H-5I"II"c                      e Zd ZdZe	 	 	 	 	 	 d+dee   defd       Zedee   defd       Zd,dZ	d-d.dZ
dee   fd	Zdeed
f   fdZd Zd.dZedefd       Zedefd       Zedeej2                     fd       Zedeeej2                  f   fd       Zedee   fd       Zd.dZd.dZd.dZ defdZ!defdZ"d/de#fdZ$ede%e&jN                     fd       Z(edee)jT                     fd       Z+ed        Z,ede-j\                  fd       Z/ede0jb                  fd       Z2d.dZ3d.dZ4d.d Z5d.d!Z6d.d"Z7d.d#Z8d.d$Z9d% Z:de)jT                  fd&Z;de<fd'Z=defd(Z>d.d)Z?d/d.d*Z@y)0rK   a  Represents a graph node that performs computation on tensors.

  An `Operation` is a node in a `tf.Graph` that takes zero or more `Tensor`
  objects as input, and produces zero or more `Tensor` objects as output.
  Objects of type `Operation` are created by calling a Python op constructor
  (such as `tf.matmul`) within a `tf.function` or under a `tf.Graph.as_default`
  context manager.

  For example, within a `tf.function`, `c = tf.matmul(a, b)` creates an
  `Operation` of type "MatMul" that takes tensors `a` and `b` as input, and
  produces `c` as output.

  If a `tf.compat.v1.Session` is used, an `Operation` of a `tf.Graph` can be
  executed by passing it to `tf.Session.run`. `op.run()` is a shortcut for
  calling `tf.compat.v1.get_default_session().run(op)`.
  Nr   rQ   c	           	      "   t        |t              st        dt        |             t        |t        j
                        st        dt        |       d      |j                         dk\  s|j                         dk  rt        d|j                          d      t        j                  |j                        s t        d|j                   d	t         d
      ~|g }n't        |t              st        dt        |             |D ]4  }	t        |	t        j                        rt        dt        |	       d       |$|D 
cg c]  }
|
j                  j                   }}
nSt!        d t#        ||      D              s7t        d|j                  d|D 
cg c]  }
|
j                   c}
d|d      g }|r||D ]w  }d}t        |t$              r|}nOt        |t        j                  t&        j(                  f      r|j*                  }nt        dt        |       d      |j-                  |       y t/        |||||      }t%        |t0              }|j3                  |       ||_        |j7                  |       |S c c}
w c c}
w )a<  Creates an `Operation`.

    NOTE: This constructor validates the name of the `Operation` (passed
    as `node_def.name`). Valid `Operation` names match the following
    regular expression:

        [A-Za-z0-9.][A-Za-z0-9_.\\-/]*

    Args:
      node_def: `node_def_pb2.NodeDef`.  `NodeDef` for the `Operation`. Used for
        attributes of `node_def_pb2.NodeDef`, typically `name`, `op`, and
        `device`.  The `input` attribute is irrelevant here as it will be
        computed when generating the model.
      g: `Graph`. The parent graph.
      inputs: list of `Tensor` objects. The inputs to this `Operation`.
      output_types: list of `DType` objects.  List of the types of the `Tensors`
        computed by this operation.  The length of this list indicates the
        number of output endpoints of the `Operation`.
      control_inputs: list of operations or tensors from which to have a control
        dependency.
      input_types: List of `DType` objects representing the types of the tensors
        accepted by the `Operation`.  By default uses `[x.dtype.base_dtype for x
        in inputs]`.  Operations that expect reference-typed inputs must specify
        these explicitly.
      original_op: Optional. Used to associate the new `Operation` with an
        existing `Operation` (for example, a replica with the op that was
        replicated).
      op_def: Optional. The `op_def_pb2.OpDef` proto that describes the op type
        that this `Operation` represents.

    Raises:
      TypeError: if control inputs are not Operations or Tensors,
        or if `node_def` is not a `NodeDef`,
        or if `g` is not a `Graph`,
        or if `inputs` are not tensors,
        or if `inputs` and `input_types` are incompatible.
      ValueError: if the `node_def` name is not valid.

    Returns:
      Operation object.
    z9Argument g must be a Graph. Received an instance of type zCArgument node_def must be a NodeDef. Received an instance of type: rN          r   zQCannot create a tensor proto whose content is larger than 2GB. Size of tensor is z bytes.`z=` is not a valid node name. Accepted names conform to Regex //NzIArgument inputs shall be a list of Tensors. Received an instance of type zGItems of argument inputs shall be Tensor. Received an instance of type c              3   X   K   | ]"  \  }}|j                  |j                         $ y wru   )r  r   ).0r  r   s      rT   	<genexpr>z*Operation.from_node_def.<locals>.<genexpr>  s*      N,0Aq!

qww
'Ns   (*zIn op 'z', input types (z*) are not compatible with expected types (r   z]Control input must be an Operation, a Tensor, or IndexedSlices. Received an instance of type )r  )input_tensors)ra   rF   r  r   r   r  ByteSizerR  r  matchr   rF  r  r   r   
base_dtypeallrS  rK   r6   IndexedSlicesr   r  r  r   _init_original_op_control_flow_post_processing)r   ry   r   r  output_typesr  input_typesoriginal_opr  r  r  control_input_opsc
control_opr  rl   s                   rT   from_node_defzOperation.from_node_defC  s   j a 66:1gY@ A A h 4 45 77;H~6FaI J Jw'8+<+<+>+B'00237<= =
  %%hmm4hmm_ ..B-C1FG G 	~f% 66:6l^E F F D:,,- 88<QyC D 	DD 178AQWW''8k8 N474LN N!&(AQ(A;P Q 	Q
  
-!
a#*J--x/E/EFGtt* ::>q'!E F F 	  ,
- 8V->vNDT>*DJJqM#D 	&&V&<KC 9 )Bs   JJc                 H    t        |t              }|j                  |       |S )a1  Create an Operation from a TF_Operation.

    For internal use only: This is useful for creating Operation for ops
    indirectly created by C API methods, e.g. the ops created by
    TF_ImportGraphDef.

    Args:
      c_op: a TF_Operation.
      g: A Graph.

    Returns:
      an Operation object.
    )rK   r   r  )r   r  r   rl   s       rT   
_from_c_opzOperation._from_c_op  s      T>*DJJqMKrV   c                     || _         d| _        d| _        d| _        d| _        | j                   j                         | _        d| _        | j                          | j                   j                  |       | _
        y)z*Initializes Operation from a TF_Operation.N)r   r  _inputs_val_device_code_locations_colocation_code_locations_get_control_flow_context_control_flow_context_gradient_function_init_outputs_add_op	_id_value)rl   r   s     rT   r  zOperation._init  sp    DJD D #'D '+D#!%!E!E!GD #DZZ''-DNrV   c                     || j                   }|D ]"  }t        j                  | |j                         $ | j                  | j                  j                  |        yy)a  Add this op to its control flow context.

    This may add new ops and change this op's inputs. self.inputs must be
    available before calling this method.

    Args:
      input_tensors: (Optional.) A list of `Tensors` corresponding to the inputs
        of this op, which should be equivalent to `self.inputs`. Pass this
        argument to avoid evaluating `self.inputs` unnecessarily.
    N)r  r2   CheckInputFromValidContextr   r  AddOp)rl   r  input_tensors      rT   r  z'Operation._control_flow_post_processing  s]     kkm% J224IJ!!-
  &&t, .rV   c                     t        j                  d| j                  z        g}	 | j                  d      }|D cg c]  }|j                  d      r| }}|r|S |S # t        $ r |cY S w xY wc c}w )z0Returns the list of colocation groups of the op.zloc:@%s_classs   loc:@)r7   r  r   get_attrrR  
startswith)rl   default_colocation_group
class_attr
class_nameattr_groupss        rT   colocation_groupszOperation.colocation_groups  s     &	DII0E FG&==*j &0!  * 	K  &;C+CC  & &%&
s   A A-A*)A*.c                 ,    t        | j                        S )zDEPRECATED: Use outputs.)r   r   r   s    rT   r  zOperation.values  s    rV   c                     | j                   S )zWReturns the control flow context of this op.

    Returns:
      A context object.
    r  r   s    rT   r  z#Operation._get_control_flow_context       %%%rV   c                     || _         y)z^Sets the current control flow context of this op.

    Args:
      ctx: a context object.
    Nr  rl   r1  s     rT   _set_control_flow_contextz#Operation._set_control_flow_context       "%DrV   c                     | j                   S )z(The unique integer id of this operation.)r  r   s    rT   rS   zOperation._id!  s     >>rV   c                 @    t        j                  | j                        S )zThe name of the device to which this op has been assigned, if any.

    Returns:
      The string name of the device to which this op has been
      assigned, or an empty string if it has not been assigned to a
      device.
    )r   TF_OperationDevicer  r   s    rT   r%   zOperation.device&  s     //

;;rV   c                 "    | j                   xs g S )a  Code locations for device context managers active at op creation.

    This property will return a list of traceable_stack.TraceableObject
    instances where .obj is a string representing the assigned device
    (or information about the function that would be applied to this op
    to compute the desired device) and the filename and lineno members
    record the location of the relevant device context manager.

    For example, suppose file_a contained these lines:

      file_a.py:
        15: with tf.device('/gpu:0'):
        16:   node_b = tf.constant(4, name='NODE_B')

    Then a TraceableObject t_obj representing the device context manager
    would have these member values:

      t_obj.obj -> '/gpu:0'
      t_obj.filename = 'file_a.py'
      t_obj.lineno = 15

    and node_b.op._device_assignments would return the list [t_obj].

    Returns:
      [str: traceable_stack.TraceableObject, ...] as per this method's
      description, above.
    )r  r   s    rT   _device_assignmentszOperation._device_assignments1  s    : &&,",rV   c                 B    | j                   xs i }|j                         S )a)  Code locations for colocation context managers active at op creation.

    This property will return a dictionary for which the keys are nodes with
    which this Operation is colocated, and for which the values are
    traceable_stack.TraceableObject instances.  The TraceableObject instances
    record the location of the relevant colocation context manager but have the
    "obj" field set to None to prevent leaking private data.

    For example, suppose file_a contained these lines:

      file_a.py:
        14: node_a = tf.constant(3, name='NODE_A')
        15: with tf.compat.v1.colocate_with(node_a):
        16:   node_b = tf.constant(4, name='NODE_B')

    Then a TraceableObject t_obj representing the colocation context manager
    would have these member values:

      t_obj.obj -> None
      t_obj.filename = 'file_a.py'
      t_obj.lineno = 15

    and node_b.op._colocation_dict would return the dictionary

      { 'NODE_A': t_obj }

    Returns:
      {str: traceable_stack.TraceableObject} as per this method's description,
      above.
    )r   r  )rl   locations_dicts     rT   _colocation_dictzOperation._colocation_dictP  s$    @ 44:N  rV   c           
          t        j                  | j                        }t        |      D cg c]/  }t	        t        j
                  | j                  |                  1 }}|S c c}w )aV  List this operation's output types.

    Returns:
      List of the types of the Tensors computed by this operation.
      Each element in the list is an integer whose value is one of
      the TF_DataType enums defined in pywrap_tf_session.h
      The length of this list indicates the number of output endpoints
      of the operation.
    )r   TF_OperationNumOutputsr  r  r   TF_OperationOutputType
_tf_output)rl   num_outputsr  r  s       rT   _output_typeszOperation._output_typess  sc     $::4::FK {# 	44T__Q5GHIL 
 s   4A%c                 ^    | j                  t        j                  t        |                   y)zfSet the device of this operation.

    Args:
      device: string or device..  The device to set.
    N)_set_device_from_stringr7   rw   rx   )rl   r%   s     rT   _set_devicezOperation._set_device  s      	  ~f/E!FGrV   c                 T   t        |t        j                        st        d|z        t	        | |       d| _        | j                  j                  j                         5 }t        j                  ||j                         | j                  |             ddd       y# 1 sw Y   yxY w)a  Update the input to this operation at the given index.

    NOTE: This is for TF internal use only. Please don't use it.

    Args:
      index: the index of the input to update.
      tensor: the Tensor to be used as the input at the given index.

    Raises:
      TypeError: if tensor is not a Tensor,
        or if input tensor type is not convertible to dtype.
      ValueError: if the Tensor is from a different graph.
    tensor must be a Tensor: %sN)ra   r  r   r  _assert_same_graphr  r   r  r  r   
UpdateEdgerh  	_tf_input)rl   indexr,   r  s       rT   _update_inputzOperation._update_input  s     fj//03f<==tV$ D				 	 	" !g""




 
..
!! ! !s    5BB'c                 Z   | j                   j                  j                         5 }|D ]l  }t        |t        j
                        st        d|z        t        | |       d| _        t        j                  ||j                         | j                         n 	 ddd       y# 1 sw Y   yxY w)aH  See AddWhileInputHack in python_api.h.

    NOTE: This is for TF internal use only. Please don't use it.

    Args:
      tensors: list of Tensors

    Raises:
      TypeError: if tensor is not a Tensor,
        or if input tensor type is not convertible to dtype.
      ValueError: if the Tensor is from a different graph.
    r.  N)r   r  r  ra   r  r   r  r/  r  r   AddWhileInputHackrh  r  )rl   r  r  r,   s       rT   _add_while_inputszOperation._add_while_inputs  s     
			 	 	" g 
&&*"3"347&@A
A4(  ++  "JJ	
  s   A2B!!B*c                 ,    t        | j                        S ru   )r]   ry   r   s    rT   r   zOperation.__str__  s    t}}rV   c                 <    d| j                   d| j                  dS )Nz<tf.Operation 'z' type=r  )r   r   r   s    rT   r  zOperation.__repr__  s    ,0IItyyAArV   c                 J    t        dj                  | j                              )zRaises a helpful error.z&can't convert Operation '{}' to Tensor)r  formatr   )rl   r   r   s      rT   ru  zOperation.__tf_tensor__  s    
<CCDIIN
OOrV   c                       j                   6t         fdt        j                   j                        D               _          j                   S )zIThe sequence of `Tensor` objects representing the data inputs of this op.c              3   T   K   | ]  }j                   j                  |       ! y wru   )r   _get_tensor_by_tf_output)r  r  rl   s     rT   r  z#Operation.inputs.<locals>.<genexpr>  s*      E **
-
-a
0Es   %()r  r   r   GetOperationInputsr  r   s   `rT   r  zOperation.inputs  sK      E$77

CE Ed rV   c           
          t        j                  | j                        }t        |      D cg c]9  }t	        j
                  t        j                  | j                  |                  ; }}|S c c}w ru   )r   TF_OperationNumInputsr  r  r&   r   TF_OperationInputTyper1  )rl   
num_inputsr  r  s       rT   _input_typeszOperation._input_types  sj    "88DJ z"  	33DNN14EF	HK 
 s   >A/c                 @    t        j                  | j                        S )z@Returns the call stack from when this operation was constructed.)r   TF_OperationGetStackTracer  r   s    rT   	tracebackzOperation.traceback  s    
 66tzzBBrV   c                 T    t         j                  j                  | j                        S ru   )r   r  
FromString	_node_defr   s    rT   ry   zOperation.node_def  s    **4>>::rV   c                 T    t         j                  j                  | j                        S ru   )r   OpDefrH  _op_defr   s    rT   r  zOperation.op_def  s    &&t||44rV   c                     t        j                  t        j                  |j	                                     }	 | j                  ||       t        j                  |       y# t        j                  |       w xY w)z8Private method used to set an attribute in the node_def.N)r   TF_NewBufferFromStringr7   r  r  _set_attr_with_bufTF_DeleteBuffer)rl   	attr_namer  bufs       rT   	_set_attrzOperation._set_attr  sZ    

2
2
44679C-
i-'','',s   A   A7c                     | j                   j                  j                         5 }t        j                  || j
                  ||       ddd       y# 1 sw Y   yxY w)z8Set an attr in the node_def with a pre-allocated buffer.N)r   r  r  r   SetAttrr  )rl   rQ  attr_bufr  s       rT   rO  zOperation._set_attr_with_buf  sK    				 	 	" JgYIJ J Js   #AAc                 |    t        j                  |      }| j                  |t        j                  |             y)z@Private method used to set a function attribute in the node_def.ro  r-  N)r   NameAttrListrS  r   )rl   rQ  ro   r-  s       rT   _set_func_attrzOperation._set_func_attr  s+    &&I6DNN9n66DABrV   c                     |D cg c]  }t        j                  |       }}t         j                  j                  |      }| j	                  |t        j                  |             yc c}w )zFPrivate method used to set a list(function) attribute in the node_def.ro  rX  rF  N)r   rY  r   	ListValuerS  )rl   rQ  
func_namesro   funcs
funcs_lists         rT   _set_func_list_attrzOperation._set_func_list_attr  sc     )* ((i8 *E *))333?JNN9n66JGH*s   A+c                    |syt        |d   t        j                        r|D cg c]  }|j                   }}t        j
                  j                  |      }| j                  |t	        j
                  |             yc c}w )zBPrivate method used to set a list(type) attribute in the node_def.Nr   r   r\  )ra   r&   r  as_datatype_enumr   r   r]  rS  )rl   rQ  
data_typesdt
types_lists        rT   _set_type_list_attrzOperation._set_type_list_attr  sj    *Q-.2<=BB''=j=))333DJNN9n66JGH >s   Bc                     |D cg c]  }|j                          }}t        j                  j                  |      }| j	                  |t        j                  |             yc c}w )zCPrivate method used to set a list(shape) attribute in the node_def.rB  r\  N)as_protor   r   r]  rS  )rl   rQ  shapessshapes_lists        rT   _set_shape_list_attrzOperation._set_shape_list_attr  sR    $*+qajjl+F+ **4464BKNN9n66KHI ,s   A%c                     | j                   j                  j                         5 }t        j                  || j
                  |       ddd       y# 1 sw Y   yxY w)z:Private method used to clear an attribute in the node_def.N)r   r  r  r   	ClearAttrr  )rl   rQ  r  s      rT   _clear_attrzOperation._clear_attr  sI    				 	 	" Bg!!'4::yAB B Bs   "AAc                 :   d}	 t        j                         5 }t        j                  | j                  ||       t        j
                  |      }ddd       t        j                         }|j                         |j                  d      }|g S |dk(  r~|D ]w  }t        |j                  |      s|dk(  r9|j                  j                   D 	cg c]  }	t#        j$                  |	       c}	c S t        t        |j                  |            c S  g S |dk(  rt#        j$                  |j                         S ||v sJ dt'        |      z          t        ||      S # 1 sw Y   xY w# t        j                  $ r}t        |j                        d}~ww xY wc c}	w )a  Returns the value of the attr of this op with the given `name`.

    Args:
      name: The name of the attr to fetch.

    Returns:
      The value of the attr, as a Python object.

    Raises:
      ValueError: If this op does not have an attr with the given `name`.
    )rk  r  fbr   r   r,   r-  Nr   rF  r   zUnsupported field type in )r#   	tf_bufferr   TF_OperationGetAttrValueProtor  TF_GetBufferr'   r  rR  r   r   r   ParseFromString
WhichOneofr   rF  r   r&   r   r]   )
rl   r   fieldsrR  datar
  r   oneof_valuerr  r   s
             rT   r  zOperation.get_attr#  si    EF"! 3S77

D#N --c23 	  "Ad,,w'Kif ,!1661&[01<1FOOA&<<*++, if__QVV$$& G">Q"GG 1k""/3 3 && "qyy!!" =s4   E( 7EE( FE% E( (F;FFc                     	 t        j                  | j                  |      }t        |   S # t        j
                  $ r}t        |j                        d}~ww xY w)zGReturns the `DType` value of the attr of this op with the given `name`.N)r   TF_OperationGetAttrTyper  rP   r'   r  rR  r   )rl   r   
dtype_enumr
  s       rT   _get_attr_typezOperation._get_attr_typeJ  sM    "$<<TZZNj!*--&& "qyy!!"s   (+ AAAc                     	 t        j                  | j                  |      S # t        j                  $ r}t        |j                        d}~ww xY w)zFReturns the `bool` value of the attr of this op with the given `name`.N)r   TF_OperationGetAttrBoolr  r'   r  rR  r   rl   r   r
  s      rT   _get_attr_boolzOperation._get_attr_boolS  sC    "66tzz4HH&& "qyy!!"   " AA

Ac                     	 t        j                  | j                  |      S # t        j                  $ r}t        |j                        d}~ww xY w)zEReturns the `int` value of the attr of this op with the given `name`.N)r   TF_OperationGetAttrIntr  r'   r  rR  r   r  s      rT   _get_attr_intzOperation._get_attr_int[  sC    "55djj$GG&& "qyy!!"r  c                    | j                   j                  j                         5 }|j                  t        j
                  t        j                  fvr"t        d| j                  d|j                        t        j                  |j                               5 }t        j                  || j                  |       ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w)a:  Sets the corresponding node's `experimental_type` field.

    See the description of `NodeDef.experimental_type` for more info.

    Args:
      type_proto: A FullTypeDef proto message. The root type_if of this object
        must be `TFT_PRODUCT`, even for ops which only have a singlre return
        value.
    zerror setting the type of z): expected TFT_UNSET or TFT_PRODUCT, got N)r   r  r  type_idr   	TFT_UNSETTFT_PRODUCTrR  r   r#   rt  r  r   SetFullTyper  )rl   
type_protor  r  s       rT   experimental_set_typezOperation.experimental_set_typec  s     
			 	 	" Gg


))=+D+DEF5tyyD#++- 	- 
 < < >? G:%%gtzz:FGG GG GG Gs$   A2C"C
9C
C	CCc                 4    t        | || j                  |       y)a~  Runs this operation in a `Session`.

    Calling this method will execute all preceding operations that
    produce the inputs needed for this operation.

    *N.B.* Before invoking `Operation.run()`, its graph must have been
    launched in a session, and either a default session must be
    available, or `session` must be specified explicitly.

    Args:
      feed_dict: A dictionary that maps `Tensor` objects to feed values. See
        `tf.Session.run` for a description of the valid feed values.
      session: (Optional.) The `Session` to be used to run to this operation. If
        none, the default session will be used.
    N)_run_using_default_sessionr   rj  s      rT   runzOperation.runv  s      tY

GDrV   )NNNNNN)r   rF   rQ   Nru   r{   rz  )Ar|   r}   r~   r   classmethodr   rJ   r  r  r  r  rF  r   r  r   r   r  r  r  r  r   rS   r]   r%   r0   TraceableObjectr   dictr#  r)  r,  r3  r6  r   r  r
   ru  r   r  r   r  r&   r  rC  rF  r   r  ry   r   rK  r  rS  rO  rZ  ra  rg  rm  rp  r  r  r   r  r  r  r  r   rV   rT   rK   rK   0  s   " 
 uu u un d=) }  $.4-$De D&eCHo &% 3   <c < < -4(G(G#H - -<  !S/*I*I%I J  !  !D T#Y  $H!64s B BPH P hz001   D.   C C ;,, ; ; 5j&& 5 5-JC
IIJB%#N"FLL ""D ""3 "G&ErV   gradient_registry_gradient_registrygradientRegisterGradientc                   ,    e Zd ZdZdgZd ZdedefdZy)r  a  A decorator for registering the gradient function for an op type.

  This decorator is only used when defining a new op type. For an op
  with `m` inputs and `n` outputs, the gradient function is a function
  that takes the original `Operation` and `n` `Tensor` objects
  (representing the gradients with respect to each output of the op),
  and returns `m` `Tensor` objects (representing the partial gradients
  with respect to each input of the op).

  For example, assuming that operations of type `"Sub"` take two
  inputs `x` and `y`, and return a single output `x - y`, the
  following gradient function would be registered:

  ```python
  @tf.RegisterGradient("Sub")
  def _sub_grad(unused_op, grad):
    return grad, tf.negative(grad)
  ```

  The decorator argument `op_type` is the string type of an
  operation. This corresponds to the `OpDef.name` field for the proto
  that defines the operation.
  _op_typec                 H    t        |t              st        d      || _        y)a  Creates a new decorator with `op_type` as the Operation type.

    Args:
      op_type: The string type of an operation. This corresponds to the
        `OpDef.name` field for the proto that defines the operation.

    Raises:
      TypeError: If `op_type` is not string.
    op_type must be a stringN)ra   r]   r  r  )rl   r  s     rT   rs   zRegisterGradient.__init__  s!     gs#011DMrV   rr  rQ   c                 F    t         j                  || j                         |S )z>Registers the function `f` as gradient function for `op_type`.)r  registerr  rl   rr  s     rT   __call__zRegisterGradient.__call__  s    q$--0HrV   Nr|   r}   r~   r   	__slots__rs   rD   r  r   rV   rT   r  r    s(    0 l) r rV   NotDifferentiable
NoGradientno_gradient)r  r  r  r  c                 f    t        | t              st        d      t        j	                  d|        y)a<  Specifies that ops of type `op_type` is not differentiable.

  This function should *not* be used for operations that have a
  well-defined gradient that is not yet implemented.

  This function is only used when defining a new op type. It may be
  used for ops such as `tf.size()` that are not differentiable.  For
  example:

  ```python
  tf.no_gradient("Size")
  ```

  The gradient computed for 'op_type' will then propagate zeros.

  For ops that have a well-defined gradient but are not yet implemented,
  no declaration should be made, and an error *must* be thrown if
  an attempt to request its gradient is made.

  Args:
    op_type: The string type of an operation. This corresponds to the
      `OpDef.name` field for the proto that defines the operation.

  Raises:
    TypeError: If `op_type` is not a string.

  r  N)ra   r]   r  r  r  )r  s    rT   r  r    s*    < 
GS	!
.
//T7+rV   c                     | j                   sy| j                  }|r|S 	 | j                  d      }t
        j                  |      S # t        $ r | j                  }Y ,w xY w)z6Returns the function that computes gradients for "op".N_gradient_op_type)r  r  r  rR  r   r  lookup)r   gradient_functionr  s      rT   get_gradient_functionr    sb    	++kk-.G 
	!	!'	** 
 ggGs   A AAc                      y)z%No op. TODO(b/74620627): Remove this.Nr   r  s    rT   %set_shape_and_handle_data_for_outputsr    s    rV   c                       e Zd ZdZddgZdddZed        Zej                  d        Zed	        Z	e	j                  d
        Z	de
de
de
fdZy)rI   a6  A holder for statistics about an operator.

  This class holds information about the resource requirements for an op,
  including the size of its weight parameters on-disk and how many FLOPS it
  requires to execute forward inference.

  If you define a new operation, you can create a function that will return a
  set of information about its usage of the CPU and disk space when serialized.
  The function itself takes a Graph object that's been set up so you can call
  methods like get_tensor_by_name to help calculate the results, and a NodeDef
  argument.

  _statistic_type_valueNrQ   c                      || _         || _        y)z4Sets up the initial placeholders for the statistics.N)statistic_typer   )rl   r  r   s      rT   rs   zOpStats.__init__  s    (DDJrV   c                     | j                   S ru   r  r   s    rT   r  zOpStats.statistic_type  s    rV   c                     || _         y ru   r  )rl   r  s     rT   r  zOpStats.statistic_type  s
    )DrV   c                     | j                   S ru   r  r   s    rT   r   zOpStats.value  s    ;;rV   c                     || _         y ru   r  )rl   r   s     rT   r   zOpStats.value  s	    DKrV   rl   otherc                    |j                   | j                   k7  r&t        d| j                   d|j                   d      | j                  |j                  | _        | S |j                  | xj                  |j                  z  c_        | S )NzCan't add an OpStat of type z to one of rN  )r  rR  r   r  )rl   r  s     rT   __iadd__zOpStats.__iadd__!  s{    t222++U-A-AC D Dzz;;dj K 
	 
kkU[[ kKrV   ru   r{   )r|   r}   r~   r   r  rs   r  r  setterr   rH   r  r   rV   rT   rI   rI     s     !(+)
     * *   	<< [   rV   zstatistical functions_stats_registryc                   0    e Zd ZdZddgZd	dZdedefdZy)
RegisterStatisticsaq  A decorator for registering the statistics function for an op type.

  This decorator can be defined for an op type so that it gives a
  report on the resources used by an instance of an operator, in the
  form of an OpStats object.

  Well-known types of statistics include these so far:

  - flops: When running a graph, the bulk of the computation happens doing
    numerical calculations like matrix multiplications. This type allows a node
    to return how many floating-point operations it takes to complete. The
    total number of FLOPs for a graph is a good guide to its expected latency.

  You can add your own statistics just by picking a new type string, registering
  functions for the ops you care about, and then calling get_stats_for_node_def.

  If a statistic for an op is registered multiple times, a KeyError will be
  raised.

  Since the statistics is counted on a per-op basis. It is not suitable for
  model parameters (capacity), which is expected to be counted only once, even
  if it is shared by multiple ops. (e.g. RNN)

  For example, you can define a new metric called doohickey for a Foo operation
  by placing this in your code:

  ```python
  @ops.RegisterStatistics("Foo", "doohickey")
  def _calc_foo_bojangles(unused_graph, unused_node_def):
    return ops.OpStats("doohickey", 20)
  ```

  Then in client code you can retrieve the value by making this call:

  ```python
  doohickey = ops.get_stats_for_node_def(graph, node_def, "doohickey")
  ```

  If the NodeDef is for an op with a registered doohickey function, you'll get
  back the calculated amount in doohickey.value, or None if it's not defined.

  r  r  rQ   Nc                     t        |t              st        d      d|v rt        d      || _        t        |t              st        d      d|v rt        d      || _        y)z,Saves the `op_type` as the `Operation` type.zop_type must be a string.,z!op_type must not contain a comma.z statistic_type must be a string.z(statistic_type must not contain a comma.N)ra   r]   r  r  r  )rl   r  r  s      rT   rs   zRegisterStatistics.__init__]  sd    gs#122
g~9::DMnc*899
n@AA)DrV   rr  c                 f    t         j                  || j                  dz   | j                  z          |S )z7Registers "f" as the statistics function for "op_type".r  )r  r  r  r  r  s     rT   r  zRegisterStatistics.__call__j  s+    Q 3d6J6J JKHrV   r{   r  r   rV   rT   r  r  /  s-    )V ,-)* r rV   r  c                     	 t         j                  |j                  dz   |z         } || |      }|S # t        $ r t	        |      }Y |S w xY w)a_  Looks up the node's statistics function in the registry and calls it.

  This function takes a Graph object and a NodeDef from a GraphDef, and if
  there's an associated statistics method, calls it and returns a result. If no
  function has been registered for the particular node type, it returns an empty
  statistics object.

  Args:
    graph: A Graph object that's been set up with the node's graph.
    node: A NodeDef describing the operator.
    statistic_type: A string identifying the statistic we're interested in.

  Returns:
    An OpStats object containing information about resource usage.
  r  )r  r  r   LookupErrorrI   )r   noder  
stats_funcr   s        rT   get_stats_for_node_defr  p  sW    "% ''#(FGJt$F 
- 
 %^$F	-%s   .2 A
	A
c                 $    | r| d   dk(  r| dd S | S )zReturns the name of an op given the name of its scope.

  Args:
    name: the name of the scope.

  Returns:
    the name of the op (equal to scope name minus any trailing slash).
  r[   r  Nr   ro  s    rT   name_from_scope_namer    s!     RCcr:d:rV   _MUTATION_LOCK_GROUP   _SESSION_RUN_LOCK_GROUPc              #   r   K   t               j                  | |      5  d  d d d        y # 1 sw Y   y xY wwru   )r   _resource_creator_scope)resource_typeresource_creators     rT   resource_creator_scoper    s4     22=3CE 
	
 
 
s   7+	747c                   4
    e Zd ZdZdn fdZed        ZdedefdZdndZ	dedefd	Z
ej                  doded   fd
       Zej                  ded   fd       Zedeeeedef      f   fd       Zej,                  deeeedef      f   ddfd       Zedeeeedef   f      fd       Zej,                  deeeedef   f      ddfd       ZdndZedej8                  fd       Zedee   fd       Zej,                  deddfd       Zede fd       Z!dndZ"dndZ#d Z$dndZ%dndZ&	 dpdee'jP                  ef   fdZ)	 dpde'jP                  fdZ*de fd Z+d! Z,dqdnd"Z-dnd#Z.dnd$Z/ede fd%       Z0 e1dd&d'      e2jf                  	 	 	 	 	 	 	 dr	 dsd)              Z4	 	 	 	 	 	 dt	 dsd*Z5	 du	 dsd+Z6dudnd,Z7duded(   fd-Z8	 dvde9e:jv                  d(f   fd.Z<de9e:jv                  d(f   fd/Z=dsd0Z>dsd1Z?de:jv                  fd2Z@de:jv                  fd3ZAdeBj                  fd4ZDdeEd    fd5ZFedee   fd6       ZGdnd7ZHdnd8ZIdee   fd9ZJdwdee   fd:ZKdee   fd;ZLdnd<ZMej                  ded   fd=       ZNedefd>       ZOeOj,                  d?eddfd@       ZOej                  dee   fdA       ZPdudefdBZQdefdCZRej                  	 dqded   fdD       ZSej                  dqded   fdE       ZT	 dxdeUfdFZVej                  ded   fdG       ZWdndHZXej                  dee   fdI       ZY G dJ dKeZ      Z[dndLZ\dndMZ]de^e_   fdNZ`dee_   fdOZadndPZbde[fdQZcej                  ded   fdR       Zdej                  ded   fdS       Zeej                  ded   fdT       Zfej                  ded   fdU       ZgdndVZhde fdWZidndXZjde fdYZkdndZZledemj                  fd[       Zoed\        Zpdeemj                     fd]Zreoj,                  d^emj                  ddfd_       Zoedemj                  fd`       Zsdeeemj                  f   fdaZtesj,                  dbemj                  ddfdc       Zsedee[   fdd       Zueuj,                  deee[   ddfdf       Zuedee   fdg       Zvevj,                  dhee   ddfdi       Zvedj        Zwewj,                  dk        Zwdexj                  j                  fdlZ{dexj                  j                  fdmZ| xZ}S )yrF   a  A TensorFlow computation, represented as a dataflow graph.

  Graphs are used by `tf.function`s to represent the function's computations.
  Each graph contains a set of `tf.Operation` objects, which represent units of
  computation; and `tf.Tensor` objects, which represent the units of data that
  flow between operations.

  ### Using graphs directly (deprecated)

  A `tf.Graph` can be constructed and used directly without a `tf.function`, as
  was required in TensorFlow 1, but this is deprecated and it is recommended to
  use a `tf.function` instead. If a graph is directly used, other deprecated
  TensorFlow 1 classes are also required to execute the graph, such as a
  `tf.compat.v1.Session`.

  A default graph can be registered with the `tf.Graph.as_default` context
  manager. Then, operations will be added to the graph instead of being executed
  eagerly. For example:

  ```python
  g = tf.Graph()
  with g.as_default():
    # Define operations and tensors in `g`.
    c = tf.constant(30.0)
    assert c.graph is g
  ```

  `tf.compat.v1.get_default_graph()` can be used to obtain the default graph.

  Important note: This class *is not* thread-safe for graph construction. All
  operations should be created from a single thread, or external
  synchronization must be provided. Unless otherwise specified, all methods
  are not thread-safe.

  A `Graph` instance supports an arbitrary number of "collections"
  that are identified by name. For convenience when building a large
  graph, collections can store groups of related objects: for
  example, the `tf.Variable` uses a collection (named
  `tf.GraphKeys.GLOBAL_VARIABLES`) for
  all variables that are created during the construction of a graph. The caller
  may define additional collections by specifying a new name.
  rQ   Nc                    t         |           t        j                         | _        t        j                  d      | _        i | _        d| _	        t        j                         | _        t        j                         | _        d| _        d| _        g | _        i | _        d| _        i | _        i | _        i | _        i | _        d| _        t3        j4                         | _        t9        j:                  t<        j>                  t<        j@                        | _!        d| _"        t        j                         | _#        tI        jJ                         | _&        tO               | _(        i | _)        i | _*        i | _+        i | _,        dt[               fz  | _.        d| _/        d| _0        d| _1        d| _2        d| _3        i | _4        i | _5        tm        jn                         r| jq                          yy)zCreates a new, empty Graph.   )
num_groupsFN)producermin_consumerzgraph-key-%d/ )9rt  rs   	threadingRLock_lockr;   	GroupLock_group_lock_names_in_use_stack_state_is_thread_locallocal_thread_localr0   TraceableStack_graph_device_function_stack_default_original_opr  !_graph_control_dependencies_stack_collections_seed_attr_scope_map_op_to_kernel_label_map_gradient_override_map_gradient_function_map
_finalizedcollectionsOrderedDict
_functionsr   
VersionDefr1   GRAPH_DEF_VERSIONGRAPH_DEF_VERSION_MIN_CONSUMER_graph_def_versions_building_function_graph_colocation_stackr<   ObjectIdentitySet_unfeedable_tensorsset_unfetchable_ops_handle_feeders_handle_readers_handle_movers_handle_deletersr   
_graph_key_last_loss_reduction_is_loss_scaled_by_optimizer
_containerexperimental_acd_manager_add_control_dependencies_op_def_cache_reduced_shape_cacher   enabledswitch_to_thread_localrl   r   s    rT   rs   zGraph.__init__  s   	G "DJ !**a8DD(-D%"*D )8(F(F(HD% $D "&D .0D*DDJD#%D  #%D"$D DO!--/DO+66++<< >D $D $3#A#A#CD .@@BDEDDDDD
 &0DO !%D(-D%DO %)D! &+D" D !#D
{{}
!!# rV   c                     | S ru   r   r   s    rT   r  zGraph._c_graph7  r   rV   rl   c                     | S ru   r   r   s    rT   r   zGraph.__enter__;      KrV   c                      y ru   r   )rl   r   s     rT   r   zGraph.__exit__>  s    
rV   c                     | S ru   r   r   s    rT   r  z	Graph.getA  r  rV   c              #     K   | j                   }t        |      }|j                  ||f       |j                  d        || j                  _         	 d | j                  j                   |urt        d      || j                  _         y# | j                  j                   |urt        d      || j                  _         w xY ww)a  Scope which defines a variable creation function.

    Args:
      creator: A callable taking `next_creator` and `kwargs`. See the
        `tf.variable_creator_scope` docstring.
      priority: Creators with a higher `priority` are called first. Within the
        same priority, creators are called inner-to-outer.

    Yields:
      `_variable_creator_scope` is a context manager with a side effect, but
      doesn't return a value.

    Raises:
      RuntimeError: If variable creator scopes are not properly nested.
    c                     | d   S r   r   )r   s    rT   <lambda>z/Graph._variable_creator_scope.<locals>.<lambda>^  s
    d1g rV   keyNz6Exiting variable_creator_scope without proper nesting.)_variable_creator_stackrF  r  sortr  rq  )rl   creatorpriorityoldnews        rT   _variable_creator_scopezGraph._variable_creator_scopeF  s     & 
&
&C
s)CJJ'"# HH%H&14D.7				3	33	>DF 	F36d0 
			3	33	>DF 	F36d0s   ACB 5C6CCc              #     K   | j                   }t        j                  |      }t        |t        t
        f      r|D ]  }||   j                  |        n||   j                  |       || j                  _         	 d | j                  j                   |urt        d      || j                  _         y# | j                  j                   |urt        d      || j                  _         w xY ww)a  Scope which defines a resource creation function used by some resource.

    The resource should be a subclass of CapturableResource with a class method
    `cls._resource_type`, the output of which is what the `resource_type`
    argument should be. By default, `cls._resource_type` returns the class name,
    `cls.__name__`. Given a scope, creators being added with the same
    `resource_type` argument will be composed together to apply to all classes
    with this `_resource_type`.


    `creator` is expected to be a function with the following signature:

    ```
      def resource_creator(next_creator, *a, **kwargs)
    ```

    The creator is supposed to eventually call the next_creator to create an
    instance if it does want to create an instance and not call
    the class initialization method directly. This helps make creators
    composable. A creator may choose to create multiple instances, return
    already existing instances, or simply register that an instance was created
    and defer to the next creator in line. Creators can also modify keyword
    arguments seen by the next creators.

    Valid keyword arguments in `kwargs` depends on the specific resource
    class. For StaticHashTable, this may be:
    * initializer: The table initializer to use.
    * default_value: The value to use if a key is missing in the table.
    * name: Optional name for the table, default to None.


    Args:
      resource_type: the output of the resource class's `_resource_type` method.
      creator: the passed creator for the resource.

    Yields:
      A scope in which the creator is active

    Raises:
      RuntimeError: If resource_creator_scope is existed without proper nesting.
    Nz6Exiting resource_creator_scope without proper nesting.)	_resource_creator_stackr  deepcopyra   rF  r   r  r  rq  )rl   r  r  r  r  rs         rT   r  zGraph._resource_creator_scopej  s     Z 
&
&C
--
C-$/ !Ag 
-(14D.7				3	33	>DF 	F36d0 
			3	33	>DF 	F36d0s   A9C.<B5  5C.56C++C..c                     t        | j                  d      s(t        j                  t              | j                  _        | j                  j
                  S )Nr  )r8  r  r  defaultdictrF  r  r   s    rT   r  zGraph._resource_creator_stack  s>    4%%'@A3>3J3J43Pd0555rV   resource_creator_stackc                 &    || j                   _        y ru   )r  r  )rl   r   s     rT   r  zGraph._resource_creator_stack      
 2HD.rV   c                 |    t        | j                  d      sg | j                  _        | j                  j                  S )Nr  )r8  r  r  r   s    rT   r  zGraph._variable_creator_stack  s5    4%%'@A35d0& 555rV   variable_creator_stackc                 &    || j                   _        y ru   )r  r  )rl   r$  s     rT   r  zGraph._variable_creator_stack  r"  rV   c                 2    | j                   rt        d      y)z^Check if the graph is finalized.

    Raises:
      RuntimeError: If the graph finalized.
    z*Graph is finalized and cannot be modified.N)r  rq  r   s    rT   _check_not_finalizedzGraph._check_not_finalized  s     EFF rV   c                 T    t         j                  j                  | j                        S )zThe GraphDef version information of this graph.

    For details on the meaning of each version, see
    [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto).

    Returns:
      A `VersionDef`.
    )r   r  rH  _version_defr   s    rT   graph_def_versionszGraph.graph_def_versions  s!     ""--d.?.?@@rV   c                     | j                   S )z*The graph-level random seed of this graph.r  r   s    rT   seedz
Graph.seed  s     ::rV   r-  c                     || _         y ru   r,  )rl   r-  s     rT   r-  z
Graph.seed  s	    DJrV   c                     | j                   S )z&True if this graph has been finalized.r  r   s    rT   	finalizedzGraph.finalized  s     ??rV   c                     d| _         y)a3  Finalizes this graph, making it read-only.

    After calling `g.finalize()`, no new operations can be added to
    `g`.  This method is used to ensure that no operations are added
    to a graph when it is shared between multiple threads, for example
    when using a `tf.compat.v1.train.QueueRunner`.
    TNr0  r   s    rT   finalizezGraph.finalize  s     DOrV   c                     d| _         y)a[  Opposite of `finalize`.

    Internal interface.

    NOTE: Unfinalizing a graph could have negative impact on performance,
    especially in a multi-threaded environment.  Unfinalizing a graph
    when it is in use by a Session may lead to undefined behavior. Ensure
    that all sessions using a graph are closed before calling this method.
    FNr0  r   s    rT   _unsafe_unfinalizezGraph._unsafe_unfinalize	  s     DOrV   c                     | j                   S )zTReturns the current control flow context.

    Returns:
      A context object.
    r  r   s    rT   r  zGraph._get_control_flow_context	  r  rV   c                     || _         y)zSSets the current control flow context.

    Args:
      ctx: a context object.
    Nr  r  s     rT   r  zGraph._set_control_flow_context	  r  rV   c                    |}| j                   j                         D ]  }||j                  j                         z  }|dk\  s|dk  rt	        d      |j
                  j                  j                  |j                  g       t        |dd      sst        j                         }|j                  |_        |j                  |_        |j
                  j                  j                  |g        y)z;If this graph contains functions, copy them to `graph_def`.r  r   z#GraphDef cannot be larger than 2GB.grad_func_nameN)r  r  cached_definitionr  rR  libraryr_   extendr   r   GradientDefr   function_namer9  gradient_funcr  )rl   	graph_defstarting_bytesizebytesizerr  grad_defs         rT   _copy_functions_to_graph_defz"Graph._copy_functions_to_graph_def 	  s     H__##% 	6!%%..00h	g	(Q,>??  '')<)<(=>	$d	+++-!"!"!1!1""))8*5	6rV   c           
      	   | j                   5  |r\| j                  j                         5 }t        j                         }|j                  t        j                  |             ddd       nt        j                         5 }| j                  j                         5 }t        j                  ||       t        j                  |      }ddd       ddd       t        j                         }|j                  t        j                               j                  j                   s|j#                  d       |r|j$                  D ]  }| j'                  |j(                        }	|	j*                  s+|j,                  d   j.                  j0                  j3                  |	j*                  D 
cg c]   }
|
j5                         j7                         " c}
        |j                  j                   D ]e  }| j8                  |j:                  j(                     }	 |j<                  }|j,                  d   }	 |j@                  }tC        |j.                  j0                        dtC        |      fv sJ |j.                  j0                  stE        ||j:                  jF                        D ]~  \  }}|j.                  j0                  jI                         j                  |j5                         j7                                |jJ                  tL        jN                  k(  sstQ        ||        tE        |j*                  |j:                  jR                        D ]/  \  }}|jJ                  tL        jN                  k(  s$tQ        ||       1 |jT                  D ]  }	 |jW                  |j(                        }	|	j*                  }|	jZ                  dk(  r1tC        |j,                  d   j.                  jZ                        }|d| }|j,                  d   j.                  j0                  j3                  |D 
cg c]   }
|
j5                         j7                         " c}
        h ddd       | j\                  fS # 1 sw Y   hxY w# 1 sw Y   xY w# 1 sw Y   xY wc c}
w # t>        $ r Y w xY w# t>        $ r Y w xY w# tX        $ r Y :w xY wc c}
w # 1 sw Y   xxY w)a{  Returns a serialized `GraphDef` representation of this graph.

    The serialized `GraphDef` can be imported into another `Graph`
    (using `tf.import_graph_def`) or used with the
    [C++ Session API](https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/r0.10/tensorflow/g3doc/api_docs/cc/index.md).

    This method is thread-safe.

    Args:
      from_version: Optional.  If this is set, returns a `GraphDef` containing
        only the nodes that were added to this graph since its `version`
        property had the given value.
      add_shapes: If true, adds an "_output_shapes" list attr to each node with
        the inferred shapes of each of its outputs.
      use_pybind11_proto: If true, uses the c++ pybind11_proto api to get the
        GraphDef proto directly from c++, instead of through a TF buffer.

    Returns:
      A tuple containing a
      [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
      protocol buffer, and the version of the graph to which that
      `GraphDef` corresponds.

    Raises:
      ValueError: If the `graph_def` would be too large.

    Nr;  _output_shapes_input_shapesr   StatefulPartitionedCallTout)/r  r  r  r   GraphDefr   r   TF_GraphToGraphDefPybindr#   rt  TF_GraphToGraphDefrv  rw  r7   r  r;  r_   
ClearFieldr  _get_operation_by_namer   r   r  rF  r   r<  rC  ri  r  	signaturer   r[  r  rQ  rS  	input_argaddr   r&   r  _copy_handle_data_to_arg_def
output_argry   get_operation_by_nameKeyErrorr   version)rl   from_version
add_shapesuse_pybind11_protor  r   rR  rz  r  r   outputfunction_defdefined_function
func_graphinput_shapesfunc_graph_inputsr
  arg_defoutput_tensorr   r(  s                        rT   _as_graph_defzGraph._as_graph_def.	  s<   @ 
 CG	]]  	NG$$&%
..*CCGL
M	N 	N !!# 	7s}}  " 7g00#>$11#6D7	7 ""$food34]]###	JJ 	JD**4995"ZZII&',,2299=?ZZH6!!#,,.HJ	J
 "MM22 -	GL!__\-C-C-H-HI
)//J &**?;, * 1 1
 \&&,,-!S9J5K1LL
LL""((),->-9-C-C-M-M*O D%g%%))+44((*3357##v6,\7CD ),J,>,>,8,B,B,M,M)O C$mW""foo5*='BC
 #++ Gd33DII>b jjGww33  		& 1 6 6 ; ;<k-gII&',,2299=DE6!!#,,.EGG?-	G-CGJ $,,G	N 	N
7 7	7 	7 I
    	   ,   FGCG CGs   S9Q-#S R,Q:RB S0:S*%RASR"S2R)>CSAS1SR9*A<S&%S	S-Q7	2S:R?RR	S	R&"S%R&&S)	R62S5R66S9	S	SS	SSc                 D    t         rd}| j                  |||      \  }}|S )a  Returns a serialized `GraphDef` representation of this graph.

    The serialized `GraphDef` can be imported into another `Graph`
    (using `tf.import_graph_def`) or used with the
    [C++ Session API](../../api_docs/cc/index.md).

    This method is thread-safe.

    Args:
      from_version: Optional.  If this is set, returns a `GraphDef` containing
        only the nodes that were added to this graph since its `version`
        property had the given value.
      add_shapes: If true, adds an "_output_shapes" list attr to each node with
        the inferred shapes of each of its outputs.
      use_pybind11_proto: If true, If true, uses the c++ pybind11_proto api to
        get the GraphDef proto directly from c++, instead of through a TF
        buffer. See https://github.com/pybind/pybind11_protobuf for reference.

    Returns:
      A
      [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
      protocol buffer.

    Raises:
      ValueError: If the `graph_def` would be too large.
    F)rY  )is_ossrb  )rl   rW  rX  rY  r   r  s         rT   as_graph_defzGraph.as_graph_def	  s5    >  ""j5G # IFA MrV   c                 D    t        j                  |      | j                  v S )zTests whether 'name' is registered in this graph's function library.

    Args:
      name: string op name.

    Returns:
      bool indicating whether or not 'name' is registered in function library.
    )r7   rw   r  rl   r   s     rT   _is_functionzGraph._is_function	  s     ==$//11rV   c                 `    | j                   j                  t        j                  |      d      S )zReturns the function definition for 'name'.

    Args:
      name: string function name.

    Returns:
      The function def proto.
    N)r  r  r7   rw   rg  s     rT   _get_functionzGraph._get_function	  s$     ??v}}T2D99rV   c                    | j                  |j                        r/|r>| j                  |j                         | j                  |       n| j                  |       t	        |d      rn|j
                  D ]^  }| j                  |j                        r0|s!| j                  |j                         | j                  |       N| j                  |       ` yy)zBAdds function to the graph including other functions in its graph.childrenN)rh  r   _remove_function_add_functionr8  rl  )rl   r_   	overwriterr  s       rT   _add_function_recursivezGraph._add_function_recursive	  s     '	hmm,8$
"x$    !QVV$!!!&&)q!


Q
  %rV   c                    | j                          |j                  }t        |dd      rt        |dd      rt        d|z        | j                  j                         5 }|j                  j                         5 }t        |dd      rE|j                  j                  j                         5 }t        j                  |||       ddd       nt        j                  ||d       ddd       ddd       || j                  t        j                  |      <   | j                  j                  dk  rd| j                  _        yy# 1 sw Y   gxY w# 1 sw Y   kxY w# 1 sw Y   oxY w)aE  Adds a function to the graph.

    After the function has been added, you can call to the function by
    passing the function name in place of an op name to
    `Graph.create_op()`.

    Args:
      function: A `_DefinedFunction` object.

    Raises:
      ValueError: if another function is defined with the same name.
    r9  Npython_grad_funcz&Gradient defined twice for function %s
_grad_func   )r'  r   r   rR  r  r  _c_funcrs  r   TF_GraphCopyFunctionr  r7   rw   r  r  )rl   r_   r   r  r-  r  s         rT   rn  zGraph._add_function	  sO    	==Dx)40W$d6 ?$FGG 
			 F! FT8\40""**..0 LH227D(KL L 
0
0$
EFF ,4DOOFMM$'( ,,r1.0d+ 2L LF FF Fs<   E:2E,E E$EEEE	EE#c                 Z   | j                          | j                  |      st        d|d| d      | j                  j	                         5 }t        j                  |t        j                  |             | j                  t        j                  |      = d d d        y # 1 sw Y   y xY w)Nz	Function z is not found in rN  )r'  rh  rR  r  r  r   TF_GraphRemoveFunctionr7   r  r  rw   )rl   r   r  s      rT   rm  zGraph._remove_function
  s    T"4(*;D81EFF				 /..w8MN
//&---
./ / /s   A
B!!B*c                     | j                   S )z2Returns True iff this graph represents a function.)r  r   s    rT   rp  zGraph.building_function
  s     """rV   zMShapes are always computed; don't use the compute_shapes as it has no effect.compute_shapesrK   c
           
          ~t        |      D ]/  \  }
}t        |t        j                        r!t	        d|
|fz         | j                  ||||||||	      S )a  Creates an `Operation` in this graph.

    This is a low-level interface for creating an `Operation`. Most
    programs will not call this method directly, and instead use the
    Python op constructors, such as `tf.constant()`, which add ops to
    the default graph.

    Args:
      op_type: The `Operation` type to create. This corresponds to the
        `OpDef.name` field for the proto that defines the operation.
      inputs: A list of `Tensor` objects that will be inputs to the `Operation`.
      dtypes: (Optional) A list of `DType` objects that will be the types of the
        tensors that the operation produces.
      input_types: (Optional.) A list of `DType`s that will be the types of the
        tensors that the operation consumes. By default, uses the base `DType`
        of each input in `inputs`. Operations that expect reference-typed inputs
        must specify `input_types` explicitly.
      name: (Optional.) A string name for the operation. If not specified, a
        name is generated based on `op_type`.
      attrs: (Optional.) A dictionary where the key is the attribute name (a
        string) and the value is the respective `attr` attribute of the
        `NodeDef` proto that will represent the operation (an `AttrValue`
        proto).
      op_def: (Optional.) The `OpDef` proto that describes the `op_type` that
        the operation will have.
      compute_shapes: (Optional.) Deprecated. Has no effect (shapes are always
        computed).
      compute_device: (Optional.) If True, device functions will be executed to
        compute the device property of the Operation.

    Raises:
      TypeError: if any of the inputs is not a `Tensor`.
      ValueError: if colocation conflicts with existing device assignment.

    Returns:
      An `Operation` object.
    zInput #%d is not a tensor: %s)r  ra   r  r   r  r   )rl   r  r  r&   r  r   r   r  rz  compute_deviceidxr  s               rT   	create_opzGraph.create_op
  so    h 	F# DQ:,,-73(BCCD ##GVV[$$)6>C CrV   c	                    | j                          ||}|r|d   dk(  rt        |      }n| j                  |      }t        |||      }	t	        d |D              }
| j                  |
      }| j                         5  t        j                  |	| ||||| j                  |      }| j                  ||       ddd       |S # 1 sw Y   S xY w)a  Creates an `Operation` in this graph.

    Implements `Graph.create_op()` without the overhead of the deprecation
    wrapper.

    Args:
      op_type: The `Operation` type to create. This corresponds to the
        `OpDef.name` field for the proto that defines the operation.
      inputs: A list of `Tensor` objects that will be inputs to the `Operation`.
      dtypes: (Optional) A list of `DType` objects that will be the types of the
        tensors that the operation produces.
      input_types: (Optional.) A list of `DType`s that will be the types of the
        tensors that the operation consumes. By default, uses the base `DType`
        of each input in `inputs`. Operations that expect reference-typed inputs
        must specify `input_types` explicitly.
      name: (Optional.) A string name for the operation. If not specified, a
        name is generated based on `op_type`.
      attrs: (Optional.) A dictionary where the key is the attribute name (a
        string) and the value is the respective `attr` attribute of the
        `NodeDef` proto that will represent the operation (an `AttrValue`
        proto).
      op_def: (Optional.) The `OpDef` proto that describes the `op_type` that
        the operation will have.
      compute_device: (Optional.) If True, device functions will be executed to
        compute the device property of the Operation.

    Raises:
      ValueError: if colocation conflicts with existing device assignment.

    Returns:
      An `Operation` object.
    Nr[   r  c              3   4   K   | ]  }|j                     y wru   )r   )r  r   s     rT   r  z,Graph._create_op_internal.<locals>.<genexpr>
  s     )QADD)s   )r  r  r  r  r  r  r|  )r'  r  unique_namer  r   _control_dependencies_for_inputs_mutation_lockrK   r  r  _create_op_helper)rl   r  r  r&   r  r   r   r  r|  ry   	input_opsr  r  s                rT   r   zGraph._create_op_internalV
  s    T 	|d RC!$'dd#du-H)&))I::9EN 
			 A##

'!// $ 	c S@A JA Js   <;CCc                     | j                          t        j                  ||       }|j                  j	                         }|| j
                  vrd| j
                  |<   | j                  ||       |S )a3  Creates an `Operation` in this graph from the supplied TF_Operation.

    This method is like create_op() except the new Operation is constructed
    using `c_op`. The returned Operation will have `c_op` as its _c_op
    field. This is used to create Operation objects around TF_Operations created
    indirectly by the C API (e.g. by TF_ImportGraphDef, TF_FinishWhile).

    This function does not call Operation._control_flow_post_processing or
    Graph._control_dependencies_for_inputs (since the inputs may not be
    available yet). The caller is responsible for calling these methods.

    Args:
      c_op: a wrapped TF_Operation
      compute_device: (Optional.) If True, device functions will be executed to
        compute the device property of the Operation.

    Returns:
      An `Operation` object.
    )r  r   r  r  )r'  rK   r  r   lowerr  r  )rl   r  r|  r  name_keys        rT   _create_op_from_tf_operationz"Graph._create_op_from_tf_operation
  sm    , 	


DD

1C
 xx~~Ht)))%&d"3~>JrV   c                 v   | j                   j                         D ]  \  }}	 |j                  |        	 | j                  |j                     }|j                  dt        j                  t        j                  |                   | j                   j#                  |j                        |_        	 | j&                  |j                     }|j                  dt        j                  t        j                  |                   | j)                  |       |r| j+                  |       | j-                         |_        | j0                  rg }d}| j0                  j3                         D ]O  }		 |j5                  |	j7                                |	j:                  s0|r3|j=                  |	j:                         d}Q t?        tA        |            }|j                  d	t        j                  t        j                  jC                  |      
             | jD                  rf|jF                  rY	 |j                  d      }
|
sD|j                  dt        j                  t        j                  | jD                                     yyyy# t        $ rk t	        |      rH ||j
                        }t        |t        d      t        j                  f      st        d|d|      |r|j                  ||       Y w xY w# t        $ r Y w xY w# t        $ r Y w xY w# t8        $ r Y w xY w# t        $ r Y yw xY w)z.Common logic for creating an op in this graph.NzCallable for scope map key 'zL' must return either None or an AttrValue protocol buffer; but it returned: _kernel)rk  r  FTr  r\  	container)$r  r  r  rR  re   ry   ra   r   r   r   r  rS  r  r7   r  rU  r  r  r  r  '_record_op_seen_by_control_dependencies_apply_device_functions#_snapshot_colocation_stack_metadatar   _colocation_stack	peek_objsr<  r  r[  r%   r,  sortedr  r]  r  _is_stateful)rl   r   r|  r  r   kernel_labelmapped_op_typeall_colocation_groupsis_device_setcolocation_opcontainer_attrs              rT   r  zGraph._create_op_helper
  s    **002 #
U#
C#11"'':lll9!++fool.KLN
 !77;;BGGDB22277;nll&!++foon.MNP
 	004
""2& %)$L$L$NB!  m11;;= 	-	

&
&}'F'F'H
I 
..--
.-	 %S)>%?@ll


"
"!++558M5NPQ 2??3[1
 
,,{N$<$<0%2 3  +K  	#E?$%EDJ0H0H#IJ e  
,,sE
"	#   
  
*  	
	0  s[   JAK< 3AL ,L+L, A0K98K9<	L	L		LL	L)(L),	L87L8c                    | j                          | j                         D cg c]  }| j                  ||       }}|D ]>  }| j                  |j                        }|j                  |       |j                          @ |S c c}w )a%  Creates `Operations` in this graph for any new TF_Operations.

    This is useful for when TF_Operations are indirectly created by the C API
    outside of the Operation constructor (e.g. by TF_ImportGraphDef,
    TF_FinishWhile). This ensures there are corresponding Operations for all
    TF_Operations in the underlying TF_Graph.

    Args:
      compute_devices: (Optional.) If True, device functions will be executed to
        compute the device properties of each new Operation.

    Returns:
      A list of the new `Operation` objects.
    r  )r'  new_operationsr  r  r  _add_control_inputsr  )rl   compute_devicesr  new_opsr   new_control_inputss         rT   _add_new_tf_operationszGraph._add_new_tf_operations  s     	 '') 	))$)OG   )@@K/0&&() Ns   Bc                     | j                   r| j                  |||      S | j                  5  | j                  |||      cddd       S # 1 sw Y   yxY w)a  Returns the object referred to by `obj`, as an `Operation` or `Tensor`.

    This function validates that `obj` represents an element of this
    graph, and gives an informative error message if it is not.

    This function is the canonical way to get/validate an object of
    one of the allowed types from an external argument reference in the
    Session API.

    This method may be called concurrently from multiple threads.

    Args:
      obj: A `Tensor`, an `Operation`, or the name of a tensor or operation. Can
        also be any object with an `_as_graph_element()` method that returns a
        value of one of these types. Note: `_as_graph_element` will be called
        inside the graph's lock and so may not modify the graph.
      allow_tensor: If true, `obj` may refer to a `Tensor`.
      allow_operation: If true, `obj` may refer to an `Operation`.

    Returns:
      The `Tensor` or `Operation` in the Graph corresponding to `obj`.

    Raises:
      TypeError: If `obj` is not a type we support attempting to convert
        to types.
      ValueError: If `obj` is of an appropriate type but invalid. For
        example, an invalid string.
      KeyError: If `obj` is not an object in the graph.
    N)r  _as_graph_element_lockedr  )rl   r   allow_tensorallow_operations       rT   as_graph_elementzGraph.as_graph_element8  sS    @ **3oNN	 O**3oNO O Os   A		Ac                 
   |r|rd}n|rd}n|rd}nt        d      t        |      }||}t        |t        j                        rt        j
                  |      }d|v rD|rB	 |j                  d      \  }}t        |      }	 | j                  |      }		 |	j                  |   S d|v r|st        dt        |      d|d      d|vr|r	 | j                  |      }	|	S d|vr7|s4	 | j                  |      }	dt        |      d|d}|dz  }t        |      yyt        |t        j                        r |r|j                  | urt        d|z        |S t        |t               r |r|j                  | urt        d|z        |S t#        dt%        |      j&                  d|d      #  t        dt        |      z        xY w# t        $ r*}
t        dt        |      d	t        |      d
      |
d}
~
ww xY w#  t        dt        |      d	t        |      dt        |	j                        d      xY w# t        $ r}
t        dt        |      z        |
d}
~
ww xY w# t        $ r dt        |      d|d}Y yw xY w)z+See `Graph.as_graph_element()` for details.zTensor or Operationr   rK   z5allow_tensor and allow_operation can't both be False.N:z|The name %s looks a like a Tensor name, but is not a valid one. Tensor names must be of the form "<op_name>:<output_index>".z	The name z9 refers to a Tensor which does not exist. The operation, z, does not exist in the graph.z, exists but only has z	 outputs.zName z% appears to refer to a Tensor, not a rN  z4The name %s refers to an Operation not in the graph.z refers to an Operation, not a z/ looks like an (invalid) Operation name, not a z= Tensor names must be of the form "<op_name>:<output_index>".z*Tensor %s is not an element of this graph.z-Operation %s is not an element of this graph.zCan not convert a z into a )rR  r   ra   r7   bytes_or_text_typesrw   splitr   r   rN  rU  r   rQ  r  r   r   rK   r  r   r|   )rl   r   r  r  	types_strtemp_objr   r   out_nr   excerr_msgs               rT   r  zGraph._as_graph_element_locked^  s    'i	i	iNOO %Hc #v112]]3d		N::c?.'5e*%
	**73"	GE"
" $;|t*i1 2 	2 d?	**40" 	d??	<**40" 4j)-'
 	 4 	5!! $3? 
C**	+	$	EKLLj	C	#	$	H3NOOj Cy))96 7 7	N @BFt*M N N
  	 t*d7m5 			G t*d7mS_F G G  	DT
 	  	<$(J	;'	<sZ   "F) G G; H: %#I# )G	G8%G33G8;<H7:	I II #JJc                     t        |t              s!t        dt        |      j                  z        t        t        | j                  |dd            }|S )au  Returns the `Operation` with the given `name`.

    This method may be called concurrently from multiple threads.

    Args:
      name: The name of the `Operation` to return.

    Returns:
      The `Operation` with the given `name`.

    Raises:
      TypeError: If `name` is not a string.
      KeyError: If `name` does not correspond to an operation in this graph.
    z1Operation names are strings (or similar), not %s.FTr  r  )ra   r]   r  r   r|   r   rK   r  )rl   r   r   s      rT   rT  zGraph.get_operation_by_name  sY      dC I4j))* + +	dM
B IrV   c                 N    t        j                  |      }| j                  |      S ru   )r   TF_OperationNamerN  )rl   tf_operr   s      rT   _get_operation_by_tf_operationz$Graph._get_operation_by_tf_operation  s#    009G&&w//rV   c                     t        |t              s!t        dt        |      j                  z        t        t        j                  | j                  |dd            }|S )ah  Returns the `Tensor` with the given `name`.

    This method may be called concurrently from multiple threads.

    Args:
      name: The name of the `Tensor` to return.

    Returns:
      The `Tensor` with the given `name`.

    Raises:
      TypeError: If `name` is not a string.
      KeyError: If `name` does not correspond to a tensor in this graph.
    z.Tensor names are strings (or similar), not %s.TFr  )	ra   r]   r  r   r|   r   r  r   r  )rl   r   r,   s      rT   get_tensor_by_namezGraph.get_tensor_by_name  s_      dC F4j))* + +duMF MrV   c                 j    | j                  |j                        }|j                  |j                     S )ao  Returns the `Tensor` representing `tf_output`.

    Note that there is only one such `Tensor`, i.e. multiple calls to this
    function with the same TF_Output value will always return the same `Tensor`
    object.

    Args:
      tf_output: A wrapped `TF_Output` (the C API equivalent of `Tensor`).

    Returns:
      The `Tensor` that represents `tf_output`.
    )r  operr   r2  )rl   	tf_outputr   s      rT   r=  zGraph._get_tensor_by_tf_output  s+     
	,	,Y^^	<B::ioo&&rV   c                     	 | j                   |   S # t        $ rM t        j                  j	                  | j                  |            | j                   |<   | j                   |   cY S w xY w)z9Returns the `OpDef` proto for `type`. `type` is a string.)r  rU  r   rK  rH  _op_def_for_type)rl   r   s     rT   r  zGraph.op_def_for_type  si    &%% &!+!1!1!<!<



%"d %%	&s    AA'&A'c                 ,    t         j                  |       S )a  Returns a context manager that makes this `Graph` the default graph.

    This method should be used if you want to create multiple graphs
    in the same process. For convenience, a global default graph is
    provided, and all ops will be added to this graph if you do not
    create a new graph explicitly.

    Use this method with the `with` keyword to specify that ops created within
    the scope of a block should be added to this graph. In this case, once
    the scope of the `with` is exited, the previous default graph is set again
    as default. There is a stack, so it's ok to have multiple nested levels
    of `as_default` calls.

    The default graph is a property of the current thread. If you
    create a new thread, and wish to use the default graph in that
    thread, you must explicitly add a `with g.as_default():` in that
    thread's function.

    The following code examples are equivalent:

    ```python
    # 1. Using Graph.as_default():
    g = tf.Graph()
    with g.as_default():
      c = tf.constant(5.0)
      assert c.graph is g

    # 2. Constructing and making default:
    with tf.Graph().as_default() as g:
      c = tf.constant(5.0)
      assert c.graph is g
    ```

    If eager execution is enabled ops created under this context manager will be
    added to the graph instead of executed eagerly.

    Returns:
      A context manager for using this graph as the default graph.
    )_default_graph_stackget_controllerr   s    rT   
as_defaultzGraph.as_default  s    P  ..t44rV   c                 ,    t        | j                        S )z9Returns the names of the collections known to this graph.)rF  r  r   s    rT   r  zGraph.collections=  s     !!""rV   c                     | j                          | j                  5  || j                  vr|g| j                  |<   n| j                  |   j                  |       ddd       y# 1 sw Y   yxY w)aY  Stores `value` in the collection with the given `name`.

    Note that collections are not sets, so it is possible to add a value to
    a collection several times.

    Args:
      name: The key for the collection. The `GraphKeys` class contains many
        standard names for collections.
      value: The value to add to the collection.
    N)r'  r  r  r  )rl   r   r   s      rT   add_to_collectionzGraph.add_to_collectionB  se     		 .	T&&	&#('$$&&u-	. . .s   >A$$A-c                 r    t        |t              r|fn
t        |      }|D ]  }| j                  ||        y)a|  Stores `value` in the collections given by `names`.

    Note that collections are not sets, so it is possible to add a value to
    a collection several times. This function makes sure that duplicates in
    `names` are ignored, but it will not check for pre-existing membership of
    `value` in any of the collections in `names`.

    `names` can be any iterable, but if `names` is a string, it is treated as a
    single collection name.

    Args:
      names: The keys for the collections to add to. The `GraphKeys` class
        contains many standard names for collections.
      value: The value to add to the collections.
    N)ra   r]   r  r  )rl   namesr   r   s       rT   add_to_collectionszGraph.add_to_collectionsT  s9    " #5#.UHCJE *
T5)*rV   c                     | j                   5  | j                  j                  |d      }|g }|| j                  |<   |cddd       S # 1 sw Y   yxY w)a  Returns a list of values in the collection with the given `name`.

    If the collection exists, this returns the list itself, which can
    be modified in place to change the collection.  If the collection does
    not exist, it is created as an empty list and the list is returned.

    This is different from `get_collection()` which always returns a copy of
    the collection list if it exists and never creates an empty collection.

    Args:
      name: The key for the collection. For example, the `GraphKeys` class
        contains many standard names for collections.

    Returns:
      The list of values in the collection with the given `name`, or an empty
      list if no value has been added to that collection.
    N)r  r  r  )rl   r   	coll_lists      rT   get_collection_refzGraph.get_collection_refi  sV    $ 
 ##''d3i			"+$  s   1AAc                 |   | j                   5  | j                  j                  |d      }|g cddd       S |t        |      cddd       S g }t	        j
                  |      }|D ]/  }	 |j                  |j                        r|j                  |       1 |cddd       S # t        $ r Y Hw xY w# 1 sw Y   yxY w)a  Returns a list of values in the collection with the given `name`.

    This is different from `get_collection_ref()` which always returns the
    actual collection list if it exists in that it returns a new list each time
    it is called.

    Args:
      name: The key for the collection. For example, the `GraphKeys` class
        contains many standard names for collections.
      scope: (Optional.) A string. If supplied, the resulting list is filtered
        to include only items whose `name` attribute matches `scope` using
        `re.match`. Items without a `name` attribute are never returned if a
        scope is supplied. The choice of `re.match` means that a `scope` without
        special tokens filters by prefix.

    Returns:
      The list of values in the collection with the given `name`, or
      an empty list if no value has been added to that collection. The
      list contains the values in the order under which they were
      collected.
    N)
r  r  r  rF  recompiler  r   r  r[  )rl   r   scope
collectionr  regexr   s          rT   get_collectionzGraph.get_collection  s    , 
 $$((t4j		  
J  

5! 	D{{499%hhtn	 !     s:    B2B2B2*,B#B2#	B/,B2.B//B22B;c                     | j                   5  | j                  D cg c]  }t        |t              s| c}cddd       S c c}w # 1 sw Y   yxY w)z1Returns a list of collections used in this graph.N)r  r  ra   r]   r   s     rT   get_all_collection_keyszGraph.get_all_collection_keys  sH    	 B**AAjC.@aAB BAB Bs    AAAAAAc                     | j                          | j                  5  || j                  v r| j                  |= ddd       y# 1 sw Y   yxY w)zClears all values in a collection.

    Args:
      name: The key for the collection. The `GraphKeys` class contains many
        standard names for collections.
    N)r'  r  r  rg  s     rT   clear_collectionzGraph.clear_collection  sH     		 $	""	"d#$ $ $s   AAc              #   b   K   | j                   }|| _         	 d || _         y# || _         w xY ww)a  Python 'with' handler to help annotate ops with their originator.

    An op may have an 'original_op' property that indicates the op on which
    it was based. For example a replica op is based on the op that was
    replicated and a gradient op is based on the op that was differentiated.

    All ops created in the scope of this 'with' handler will have
    the given 'op' as their original op.

    Args:
      op: The Operation that all ops created in this scope will have as their
        original op.

    Yields:
      Nothing.
    N)r  )rl   r   old_original_ops      rT   r  zGraph._original_op  s3     $ //O "D2"1d/ds   /# /	,/c                 |    t        | j                  d      sd| j                  _        | j                  j                  S )N_name_stackr  )r8  r  r  r   s    rT   r  zGraph._name_stack  s4     4%%}5')d$)))rV   
name_stackc                 &    || j                   _        y ru   )r  r  )rl   r  s     rT   r  zGraph._name_stack  s    %/D"rV   c              #     K   |rt        |t        j                        rt        j                  |      }| j                  r4t
        j                  |      sSt        d| dt
        j                         t        j                  |      st        d| dt        j                         | j                  }|sd}d}n,|d   dk(  rt        |      }|}n| j                  |      }|dz   }|| _        	 | || _        y# || _        w xY ww)a	  Returns a context manager that creates hierarchical names for operations.

    A graph maintains a stack of name scopes. A `with name_scope(...):`
    statement pushes a new name onto the stack for the lifetime of the context.

    The `name` argument will be interpreted as follows:

    * A string (not ending with '/') will create a new name scope, in which
      `name` is appended to the prefix of all operations created in the
      context. If `name` has been used before, it will be made unique by
      calling `self.unique_name(name)`.
    * A scope previously captured from a `with g.name_scope(...) as
      scope:` statement will be treated as an "absolute" name scope, which
      makes it possible to re-enter existing scopes.
    * A value of `None` or the empty string will reset the current name scope
      to the top-level (empty) name scope.

    For example:

    ```python
    with tf.Graph().as_default() as g:
      c = tf.constant(5.0, name="c")
      assert c.op.name == "c"
      c_1 = tf.constant(6.0, name="c")
      assert c_1.op.name == "c_1"

      # Creates a scope called "nested"
      with g.name_scope("nested") as scope:
        nested_c = tf.constant(10.0, name="c")
        assert nested_c.op.name == "nested/c"

        # Creates a nested scope called "inner".
        with g.name_scope("inner"):
          nested_inner_c = tf.constant(20.0, name="c")
          assert nested_inner_c.op.name == "nested/inner/c"

        # Create a nested scope called "inner_1".
        with g.name_scope("inner"):
          nested_inner_1_c = tf.constant(30.0, name="c")
          assert nested_inner_1_c.op.name == "nested/inner_1/c"

          # Treats `scope` as an absolute name scope, and
          # switches to the "nested/" scope.
          with g.name_scope(scope):
            nested_d = tf.constant(40.0, name="d")
            assert nested_d.op.name == "nested/d"

            with g.name_scope(""):
              e = tf.constant(50.0, name="e")
              assert e.op.name == "e"
    ```

    The name of the scope itself can be captured by `with
    g.name_scope(...) as scope:`, which stores the name of the scope
    in the variable `scope`. This value can be used to name an
    operation that represents the overall result of executing the ops
    in a scope. For example:

    ```python
    inputs = tf.constant(...)
    with g.name_scope('my_layer') as scope:
      weights = tf.Variable(..., name="weights")
      biases = tf.Variable(..., name="biases")
      affine = tf.matmul(inputs, weights) + biases
      output = tf.nn.relu(affine, name=scope)
    ```

    NOTE: This constructor validates the given `name`. Valid scope
    names match one of the following regular expressions:

        [A-Za-z0-9.][A-Za-z0-9_.\-/]* (for scopes at the root)
        [A-Za-z0-9_.\-/]* (for other scopes)

    Args:
      name: A name for the scope.

    Returns:
      A context manager that installs `name` as a new name scope.

    Raises:
      ValueError: If `name` is not a valid scope name, according to the rules
        above.
    'zN' is not a valid scope name. A scope name has to match the following pattern: zX' is not a valid root scope name. A root scope name has to match the following pattern: r  r[   r  N)ra   r7   r  rw   r  r  r  rR  patternr  r  r  )rl   r   	old_stack	new_stackreturned_scopes        rT   
name_scopezGraph.name_scope  s    j 	D&44	5}}T"			 ',,T2$ ((?(G(G'HJK K $))$/$ 11E1M1M0NPQ Q   Iin	bS&t,in""4(i 3n D#"dds   C,D/C; 3D;	DDc                 X   | j                   r| j                   dz   |z   }|j                         }| j                  j                  |d      }|r|dz   | j                  |<   |dkD  rF|}|| j                  v rd||fz  }|dz  }|| j                  v r|rd| j                  |<   d||dz
  fz  }|S )a  Return a unique operation name for `name`.

    Note: You rarely need to call `unique_name()` directly.  Most of
    the time you just need to create `with g.name_scope()` blocks to
    generate structured names.

    `unique_name` is used to generate structured names, separated by
    `"/"`, to help identify operations when debugging a graph.
    Operation names are displayed in error messages reported by the
    TensorFlow runtime, and in various visualization tools such as
    TensorBoard.

    If `mark_as_used` is set to `True`, which is the default, a new
    unique name is created and marked as in use. If it's set to `False`,
    the unique name is returned without actually being marked as used.
    This is useful when the caller simply wants to know what the name
    to be created will be.

    Args:
      name: The name for an operation.
      mark_as_used: Whether to mark this name as being used.

    Returns:
      A string to be passed to `create_op()` that will be used
      to name the operation being created.
    r  r   r  r  )r  r  r  r  )rl   r   mark_as_usedr  r  base_name_keys         rT   r  zGraph.unique_nameZ  s    6 #d*d zz|Hx+A%&Ud"1um***mQ//	Q ***
 
'(8$ a!e}$dKrV   c                     | j                   S )aB  Returns the current name scope.

    For example:

    ```python
    with tf.name_scope('scope1'):
      with tf.name_scope('scope2'):
        print(tf.compat.v1.get_default_graph().get_name_scope())
    ```
    would print the string `scope1/scope2`.

    Returns:
      A string representing the current name scope.
    )r  r   s    rT   get_name_scopezGraph.get_name_scope  s     rV   c              #     K   | j                  ||      5  |<t        |       }|*|j                  ||       	 d  |j                  ||       n	d  nd  d d d        y # |j                  ||       w xY w# 1 sw Y   y xY wwru   )colocate_with_get_enclosing_contextEnterGradientColocationExitGradientColocation)rl   r   gradient_uidignore_existingr1  s        rT   _colocate_with_for_gradientz!Graph._colocate_with_for_gradient  s      
		B	0 		!$T*?

%
%b,
79&&r<8
  &&r<8 s2   B"A8A!A8	B!A55A88B=Bc              #     K   ||st        d      t        ||       \  }}| j                  }t        j                         | _        |r%| j
                  }t        j                         | _        |=| j
                  j                  |d       |+| j
                  j                  |d       n|st        d      	 d || _        |6| j
                  j                          || j
                  j                          |r| _        yy# || _        |6| j
                  j                          || j
                  j                          |r| _        w w xY ww)a(  Returns a context manager that specifies an op to colocate with.

    Note: this function is not for public use, only for internal libraries.

    For example:

    ```python
    a = tf.Variable([1.0])
    with g.colocate_with(a):
      b = tf.constant(1.0)
      c = tf.add(a, b)
    ```

    `b` and `c` will always be colocated with `a`, no matter where `a`
    is eventually placed.

    **NOTE** Using a colocation scope resets any existing device constraints.

    If `op` is `None` then `ignore_existing` must be `True` and the new
    scope resets all colocation and device constraints.

    Args:
      op: The op to colocate all created ops with, or `None`.
      ignore_existing: If true, only applies colocation of this op within the
        context, rather than applying all colocation properties on the stack.
        If `op` is `None`, this value must be `True`.

    Raises:
      ValueError: if op is None but ignore_existing is False.

    Yields:
      A context manager that specifies the op with which to colocate
      newly created ops.
    NzGTrying to reset colocation (op is None) but ignore_existing is not True   offset)rR  _op_to_colocate_with_device_function_stackr0   r  r  push_objpop_obj)rl   r   r  device_only_candidatedevice_fn_tmpcurrent_stacks         rT   r  zGraph.colocate_with  se    H 
z/ 5 6 6 4R >B //M"1"@"@"BD,,m.==?d	~ %%b%3		*''(=a'H 5 6 6/ %2d!	&&( ,

 
 
(
(
* 
!. 
 %2d!	&&( ,

 
 
(
(
* 
!. 
s    B7E:D >A
EAEEc                 `    d|z   }t        |      }| j                  j                  ||       |S )z>Add device to stack manually, separate from a context manager.r  r  )rX   r  r  )rl   rm   r  total_offsetspecs        rT   _add_device_to_stackzGraph._add_device_to_stack  s6     v:L23D((l(CKrV   c              #     K   | j                  |d       | j                  j                         }	 d | j                  j                         }||urt        d      | j                  j	                          y# | j                  j                         }||urt        d      | j                  j	                          w xY ww)a-  Returns a context manager that specifies the default device to use.

    The `device_name_or_function` argument may either be a device name
    string, a device function, or None:

    * If it is a device name string, all operations constructed in
      this context will be assigned to the device with that name, unless
      overridden by a nested `device()` context.
    * If it is a function, it will be treated as a function from
      Operation objects to device name strings, and invoked each time
      a new Operation is created. The Operation will be assigned to
      the device with the returned name.
    * If it is None, all `device()` invocations from the enclosing context
      will be ignored.

    For information about the valid syntax of device name strings, see
    the documentation in
    [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h).

    For example:

    ```python
    with g.device('/device:GPU:0'):
      # All operations constructed in this context will be placed
      # on GPU 0.
      with g.device(None):
        # All operations constructed in this context will have no
        # assigned device.

    # Defines a function from `Operation` to device string.
    def matmul_on_gpu(n):
      if n.type == "MatMul":
        return "/device:GPU:0"
      else:
        return "/cpu:0"

    with g.device(matmul_on_gpu):
      # All operations of type "MatMul" constructed in this context
      # will be placed on GPU 0; all other operations will be placed
      # on CPU 0.
    ```

    **N.B.** The device scope may be overridden by op wrappers or
    other library code. For example, a variable assignment op
    `v.assign()` must be colocated with the `tf.Variable` `v`, and
    incompatible device scopes will be ignored.

    Args:
      device_name_or_function: The device name or function to use in the
        context.

    Yields:
      A context manager that specifies the default device to use for newly
      created ops.

    Raises:
      RuntimeError: If device scopes are not properly nested.
    r  r  Nz2Exiting device scope without proper scope nesting.)r  r  peek_top_objrq  r  )rl   rm   old_top_of_stacknew_top_of_stacks       rT   r%   zGraph.device  s     z 	5a@22??A,44AAC	!1	1OPP
!!))+ 44AAC	!1	1OPP
!!))+s   .CA9 AC9AB>>Cc                     d}| j                   j                         D ]F  }|j                  r|j                   n+|j	                  |      }||us4|j                  |       |}H | j                         |_        y)zAApplies the current device function stack to the given operation.N)r  r  rd   r_   rz   r+  (_snapshot_device_function_stack_metadatar  )rl   r   prior_device_stringdevice_specdevice_strings        rT   r  zGraph._apply_device_functionsO  s     22<<> ,		"	"				%!..r2m 
1	1
""=1+, !% M M OBrV   c              #   v   K   | j                   }|| _         	 | j                    || _         y# || _         w xY ww)a  Returns a context manager that specifies the resource container to use.

    Stateful operations, such as variables and queues, can maintain their
    states on devices so that they can be shared by multiple processes.
    A resource container is a string name under which these stateful
    operations are tracked. These resources can be released or cleared
    with `tf.Session.reset()`.

    For example:

    ```python
    with g.container('experiment0'):
      # All stateful Operations constructed in this context will be placed
      # in resource container "experiment0".
      v1 = tf.Variable([1.0])
      v2 = tf.Variable([2.0])
      with g.container("experiment1"):
        # All stateful Operations constructed in this context will be
        # placed in resource container "experiment1".
        v3 = tf.Variable([3.0])
        q1 = tf.queue.FIFOQueue(10, tf.float32)
      # All stateful Operations constructed in this context will be
      # be created in the "experiment0".
      v4 = tf.Variable([4.0])
      q1 = tf.queue.FIFOQueue(20, tf.float32)
      with g.container(""):
        # All stateful Operations constructed in this context will be
        # be placed in the default resource container.
        v5 = tf.Variable([5.0])
        q3 = tf.queue.FIFOQueue(30, tf.float32)

    # Resets container "experiment0", after which the state of v1, v2, v4, q1
    # will become undefined (such as uninitialized).
    tf.Session.reset(target, ["experiment0"])
    ```

    Args:
      container_name: container name string.

    Returns:
      A context manager for defining resource containers for stateful ops,
        yields the container name.
    N)r  )rl   container_nameoriginal_containers      rT   r  zGraph.containeri  s8     Z $DO+OO*do*dos   9- 9	69c                   L    e Zd ZdZd
dZd
dZd
dZed        Zd
dZ	de
fd	Zy)$Graph._ControlDependenciesControllerz-Context manager for `control_dependencies()`.rQ   Nc                     || _         |g | _        d| _        n|| _        d| _        t               | _        d| _        d| _        y)a	  Create a new `_ControlDependenciesController`.

      A `_ControlDependenciesController` is the context manager for
      `with tf.control_dependencies()` blocks.  These normally nest,
      as described in the documentation for `control_dependencies()`.

      The `control_inputs` argument list control dependencies that must be
      added to the current set of control dependencies.  Because of
      uniquification the set can be empty even if the caller passed a list of
      ops.  The special value `None` indicates that we want to start a new
      empty set of control dependencies instead of extending the current set.

      In that case we also clear the current control flow context, which is an
      additional mechanism to add control dependencies.

      Args:
        graph: The graph that this controller is managing.
        control_inputs: List of ops to use as control inputs in addition to the
          current control dependencies.  None to indicate that the dependencies
          should be cleared.
      NTF)_graph_control_inputs_val
_new_stackr  _seen_nodes
_old_stack_old_control_flow_context)rl   r   r  s      rT   rs   z-Graph._ControlDependenciesController.__init__  sH    , dk		#% #1 ddo'+d$rV   c                    | j                   rf| j                  j                  | _        g | j                  _        | j                  j	                         | _        | j                  j                  d        | j                  j                  |        y ru   )r  r  _control_dependencies_stackr  r  r  r  %_push_control_dependencies_controllerr   s    rT   r   z.Graph._ControlDependenciesController.__enter__  s_    	++AA24/)-)N)N)P&--d3
kk77=rV   c                     | j                   j                  |        | j                  rA| j                  | j                   _        | j                   j                  | j                         y y ru   )r  $_pop_control_dependencies_controllerr  r  r  r  r  )rl   unused_typeunused_valueunused_tracebacks       rT   r   z-Graph._ControlDependenciesController.__exit__  sH    
kk66t<	26///--d.L.LM 
rV   c                     | j                   S ru   )r  r   s    rT   r  z3Graph._ControlDependenciesController.control_inputs  s    %%%rV   c                     t        |t        j                        r|j                         }| j                  j                  |       y ru   )ra   r  r   refr  rQ  rl   r   s     rT   add_opz+Graph._ControlDependenciesController.add_op  s1    	B
))	*VVX
2rV   c                 r    t        |t        j                        r|j                         }|| j                  v S ru   )ra   r  r   r  r  r  s     rT   op_in_groupz0Graph._ControlDependenciesController.op_in_group  s.    	B
))	*VVX4####rV   r{   )r|   r}   r~   r   rs   r   r   r  r  r  r   r!  r   rV   rT   _ControlDependenciesControllerr    s;    7,F>N & &
$ $rV   r"  c                 :    | j                   j                  |       y ru   )r  r  rl   
controllers     rT   r  z+Graph._push_control_dependencies_controller  s    $$++J7rV   c                 ^    | j                   d   |u sJ | j                   j                          y )Nr[   )r  popr$  s     rT   r  z*Graph._pop_control_dependencies_controller  s-    ++B/:===$$((*rV   c                     t               }| j                  D ]$  }|j                  D ]  }|j                  |        & |S ru   )r  r  r  rQ  )rl   r  r%  r   s       rT   _current_control_dependenciesz#Graph._current_control_dependencies  sE    
%C66 
)) " JrV   c                     g }| j                   D ]G  }d}D ]  }|j                  |      sd} n |r$|j                  fd|j                  D               I |S )a  For an op that takes `input_ops` as inputs, compute control inputs.

    The returned control dependencies should yield an execution that
    is equivalent to adding all control inputs in
    self._control_dependencies_stack to a newly created op. However,
    this function attempts to prune the returned control dependencies
    by observing that nodes created within the same `with
    control_dependencies(...):` block may have data dependencies that make
    the explicit approach redundant.

    Args:
      input_ops: The data input ops for an op to be created.

    Returns:
      A list of control inputs for the op to be created.
    FTc              3   ,   K   | ]  }|vs|  y wru   r   )r  r  r  s     rT   r  z9Graph._control_dependencies_for_inputs.<locals>.<genexpr>  s     N1I;M1Ns   	)r  r!  r<  r  )rl   r  r  r%  	dominatedr   s    `    rT   r  z&Graph._control_dependencies_for_inputs  ss    " C66 O
 i "!!"%)
  	

Nj77NNO JrV   c                 H    | j                   D ]  }|j                  |        y)zpRecord that the given op depends on all registered control dependencies.

    Args:
      op: An Operation.
    N)r  r  )rl   r   r%  s      rT   r  z-Graph._record_op_seen_by_control_dependencies  s'     66 
rV   c                 B   || j                  | d      S g }| j                         }|D ]  }t        |t        j                        st        |d      rt        |d      r|j                  }| j                  |      }t        |t        j                        r|j                  }nt        |t              st        d|z        ||vs|j                  |       |j                  |       |j                  dt        j                   d              | j                  | |      S )av  Returns a context manager that specifies control dependencies.

    Use with the `with` keyword to specify that all operations constructed
    within the context should have control dependencies on
    `control_inputs`. For example:

    ```python
    with g.control_dependencies([a, b, c]):
      # `d` and `e` will only run after `a`, `b`, and `c` have executed.
      d = ...
      e = ...
    ```

    Multiple calls to `control_dependencies()` can be nested, and in
    that case a new `Operation` will have control dependencies on the union
    of `control_inputs` from all active contexts.

    ```python
    with g.control_dependencies([a, b]):
      # Ops constructed here run after `a` and `b`.
      with g.control_dependencies([c, d]):
        # Ops constructed here run after `a`, `b`, `c`, and `d`.
    ```

    You can pass None to clear the control dependencies:

    ```python
    with g.control_dependencies([a, b]):
      # Ops constructed here run after `a` and `b`.
      with g.control_dependencies(None):
        # Ops constructed here run normally, not waiting for either `a` or `b`.
        with g.control_dependencies([c, d]):
          # Ops constructed here run after `c` and `d`, also not waiting
          # for either `a` or `b`.
    ```

    *N.B.* The control dependencies context applies *only* to ops that
    are constructed within the context. Merely using an op or tensor
    in the context does not add a control dependency. The following
    example illustrates this point:

    ```python
    # WRONG
    def my_func(pred, tensor):
      t = tf.matmul(tensor, tensor)
      with tf.control_dependencies([pred]):
        # The matmul op is created outside the context, so no control
        # dependency will be added.
        return t

    # RIGHT
    def my_func(pred, tensor):
      with tf.control_dependencies([pred]):
        # The matmul op is created in the context, so a control dependency
        # will be added.
        return tf.matmul(tensor, tensor)
    ```

    Also note that though execution of ops created under this scope will trigger
    execution of the dependencies, the ops created under this scope might still
    be pruned from a normal tensorflow graph. For example, in the following
    snippet of code the dependencies are never executed:

    ```python
      loss = model.loss()
      with tf.control_dependencies(dependencies):
        loss = loss + tf.constant(1)  # note: dependencies ignored in the
                                      # backward pass
      return tf.gradients(loss, model.variables)
    ```

    This is because evaluating the gradient graph does not require evaluating
    the constant(1) op created in the forward pass.

    Args:
      control_inputs: A list of `Operation` or `Tensor` objects which must be
        executed or computed before running the operations defined in the
        context.  Can also be `None` to clear the control dependencies.

    Returns:
     A context manager that specifies control dependencies for all
     operations constructed within the context.

    Raises:
      TypeError: If `control_inputs` is not a list of `Operation` or
        `Tensor` objects.
    N_handler   z-Control input must be Operation or Tensor: %s _has_manual_control_dependenciesT)rs  )r"  r)  ra   r6   r  r8  r   r  r  r   rK   r  r  rQ  rS  r   r   )rl   r  control_opscurrentr  s        rT   rw  zGraph.control_dependencies  s	   t 00t<<
 K002G 6 Q..
/1i WQ%5DD



"a	Az((	)DD!Y'G!KLL	
'	1A 	
6",,t4	6)6. ..t[AArV   c              #     K   t        |t              st        d      i }|j                         D ]  \  }}t        |t              r0t        |t        d      t        j                  f      st        |      st        d      	 | j                  |   ||<   || j                  |= t|| j                  |<    	 d |j                         D ]  \  }}	 ||   | j                  |<    y# t        $ r Y ]w xY w# t        $ r | j                  |= Y Cw xY w# |j                         D ]4  \  }}	 ||   | j                  |<   # t        $ r | j                  |= Y 2w xY w w xY ww)a  EXPERIMENTAL: A context manager for setting attributes on operators.

    This context manager can be used to add additional
    attributes to operators within the scope of the context.

    For example:

       with ops.Graph().as_default() as g:
         f_1 = Foo()  # No extra attributes
         with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=False)}):
           f_2 = Foo()  # Additional attribute _a=False
           with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=True)}):
             f_3 = Foo()  # Additional attribute _a=False
             with g._attr_scope({"_a": None}):
               f_4 = Foo()  # No additional attributes.

    Args:
      attr_map: A dictionary mapping attr name strings to AttrValue protocol
        buffers or None.

    Returns:
      A context manager that sets the kernel label to be used for one or more
      ops created in that context.

    Raises:
      TypeError: If attr_map is not a dictionary mapping
        strings to AttrValue protobufs.
    zKattr_map must be a dictionary mapping strings to AttrValue protocol buffersNz}attr_map must be a dictionary mapping strings to AttrValue protocol buffers or callables that emit AttrValue protocol buffers)ra   r  r  r  r]   r   r   r   re   r  rU  )rl   attr_mapsaved_attrsr   r  s        rT   _attr_scopezGraph._attr_scope  s    < h% > ? ? Knn& *
ds#$d^-E-E FG~ I J 	J 006D 
  &%)T"*	) !( )*$	)'24'8$

t
$)    	)""4(	) !( )*$	)'24'8$

t
$ 	)""4(	))s   A?EC&!E6D :EC5#E&	C2/E1C22E5DEDEE)D<;E<E	EE	EEc              #   ^  K   t        |t              st        d      i }|j                         D ]R  \  }}t        |t              rt        |t              st        d      	 | j
                  |   ||<   || j
                  |<   T 	 d |j                         D ]  \  }}	 ||   | j
                  |<    y# t        $ r Y Mw xY w# t        $ r | j
                  |= Y Cw xY w# |j                         D ]4  \  }}	 ||   | j
                  |<   # t        $ r | j
                  |= Y 2w xY w w xY ww)a  EXPERIMENTAL: A context manager for setting kernel labels.

    This context manager can be used to select particular
    implementations of kernels within the scope of the context.

    For example:

        with ops.Graph().as_default() as g:
          f_1 = Foo()  # Uses the default registered kernel for the Foo op.
          with g.kernel_label_map({"Foo": "v_2"}):
            f_2 = Foo()  # Uses the registered kernel with label "v_2"
                         # for the Foo op.
            with g.kernel_label_map({"Foo": "v_3"}):
              f_3 = Foo()  # Uses the registered kernel with label "v_3"
                           # for the Foo op.
              with g.kernel_label_map({"Foo": ""}):
                f_4 = Foo()  # Uses the default registered kernel
                             # for the Foo op.

    Args:
      op_to_kernel_label_map: A dictionary mapping op type strings to kernel
        label strings.

    Returns:
      A context manager that sets the kernel label to be used for one or more
      ops created in that context.

    Raises:
      TypeError: If op_to_kernel_label_map is not a dictionary mapping
        strings to strings.
    zFop_to_kernel_label_map must be a dictionary mapping strings to stringsN)ra   r  r  r  r]   r  rU  )rl   op_to_kernel_label_mapsaved_labelsr  labels        rT   _kernel_label_mapzGraph._kernel_label_map  sb    B ,d3 + , , L0668 	4#&$ - . 	. $ < <W EW /4d""7+	44 388: 4.'5	42>w2G$
&
&w
/4    	4**73	4 388: 4.'5	42>w2G$
&
&w
/ 	4**73	44   AD-"B64D-C! 
D-!C3D-6	C?D-CD-CD-CD-!D*9DD*D%	"D*$D%	%D**D-c              #   f   K   | j                   rJ || _         	 d i | _         y# i | _         w xY ww)z0Specify gradient function for the given op type.N)r  )rl   gradient_function_maps     rT   _override_gradient_functionz!Graph._override_gradient_function  s7      ****"7D'$&d!Bd!s   1% 1	.1c              #   ^  K   t        |t              st        d      i }|j                         D ]R  \  }}t        |t              rt        |t              st        d      	 | j
                  |   ||<   || j
                  |<   T 	 d |j                         D ]  \  }}	 ||   | j
                  |<    y# t        $ r Y Mw xY w# t        $ r | j
                  |= Y Cw xY w# |j                         D ]4  \  }}	 ||   | j
                  |<   # t        $ r | j
                  |= Y 2w xY w w xY ww)a  EXPERIMENTAL: A context manager for overriding gradient functions.

    This context manager can be used to override the gradient function
    that will be used for ops within the scope of the context.

    For example:

    ```python
    @tf.RegisterGradient("CustomSquare")
    def _custom_square_grad(op, grad):
      # ...

    with tf.Graph().as_default() as g:
      c = tf.constant(5.0)
      s_1 = tf.square(c)  # Uses the default gradient for tf.square.
      with g.gradient_override_map({"Square": "CustomSquare"}):
        s_2 = tf.square(s_2)  # Uses _custom_square_grad to compute the
                              # gradient of s_2.
    ```

    Args:
      op_type_map: A dictionary mapping op type strings to alternative op type
        strings.

    Returns:
      A context manager that sets the alternative op type to be used for one
      or more ops created in that context.

    Raises:
      TypeError: If `op_type_map` is not a dictionary mapping strings to
        strings.
    z;op_type_map must be a dictionary mapping strings to stringsN)ra   r  r  r  r]   r  rU  )rl   op_type_mapsaved_mappingsr  r  s        rT   gradient_override_mapzGraph.gradient_override_map*  sd    D k4( + , , N#.#4#4#6 	<#&- - . 	."&"="=g"Fw .<d!!'*	<3 &1%6%6%8 3
!'>	31?1H$
%
%g
.3    	3))'2	3 &1%6%6%8 3
!'>	31?1H$
%
%g
. 	3))'2	33r<  c                 :    | j                   j                  |       y)z5Marks the given `tensor` as unfeedable in this graph.N)r  rQ  rl   r,   s     rT   prevent_feedingzGraph.prevent_feedingi  s      (rV   c                     || j                   vS )z3Returns `True` if and only if `tensor` is feedable.)r  rE  s     rT   is_feedablezGraph.is_feedablem  s    1111rV   c                 :    | j                   j                  |       y)z2Marks the given `op` as unfetchable in this graph.N)r  rQ  r  s     rT   prevent_fetchingzGraph.prevent_fetchingq  s    b!rV   c                     t        |t        j                        r|j                  | j                  vS || j                  vS )z:Returns `True` if and only if `tensor_or_op` is fetchable.)ra   r  r   r   r  )rl   tensor_or_ops     rT   is_fetchablezGraph.is_fetchableu  s8    ,
 1 12__D$9$999!6!666rV   c                 ,    | j                   sd| _         yy)a  Make device, colocation and dependencies stacks thread-local.

    Device, colocation and dependencies stacks are not thread-local be default.
    If multiple threads access them, then the state is shared.  This means that
    one thread may affect the behavior of another thread.

    After this method is called, the stacks become thread-local.  If multiple
    threads access them, then the state is not shared.  Each thread uses its own
    value; a thread doesn't affect other threads by mutating such a stack.

    The initial value for every thread's stack is set to the current value
    of the stack when `switch_to_thread_local()` was first called.
    TN)r  r   s    rT   r  zGraph.switch_to_thread_local|  s     ,,*.d' -rV   c                     | j                   rWt        | j                  d      s+| j                  j	                         }|| j                  _        | j                  j
                  S | j                  S )Nr  )r  r8  r  r  r  r  rl   stack_copy_for_this_threads     rT   r  zGraph._device_function_stack  sa    (( T'')AB%)%F%F%K%K%M"4N1666 ...rV   c                     | j                   j                         }|D cg c]  }|j                   }}t        t	        |            }|S c c}w ru   )r  r  r_   rF  reversed)rl   user_device_specsr  device_functionsdevice_functions_outer_to_inners        rT    _device_functions_outer_to_innerz&Graph._device_functions_outer_to_inner  sL    33==?2CD$DD&*84D+E&F#** Es   A
c                     g }| j                   j                         D ]>  }|j                         }|j                  j                  |_        |j                  |       @ |S )av  Return device function stack as a list of TraceableObjects.

    Returns:
      [traceable_stack.TraceableObject, ...] where each TraceableObject's .obj
      member is a displayable name for the user's argument to Graph.device, and
      the filename and lineno members point to the code location where
      Graph.device was called directly or indirectly by the user.
    )r  peek_traceable_objscopy_metadatar   r^   r  )rl   snapshotr   obj_copys       rT   r  z.Graph._snapshot_device_function_stack_metadata  sY     H**>>@  ""$hWW))hlooh  OrV   device_function_stackc                 N    | j                   r|| j                  _        y || _        y ru   )r  r  r  r  )rl   r]  s     rT   r  zGraph._device_function_stack  s&     ((2Gd/ +@d'rV   c                     | j                   rWt        | j                  d      s+| j                  j	                         }|| j                  _        | j                  j
                  S | j                  S )z-Return thread-local copy of colocation stack.r  )r  r8  r  r  r  r  rP  s     rT   r  zGraph._colocation_stack  sc     (( T'')<=%)%A%A%F%F%H"/I,111 )))rV   c                     | j                   j                         D ci c]'  }|j                  j                  |j	                         ) c}S c c}w )z1Return colocation stack metadata as a dictionary.)r  rY  r   r   rZ  )rl   traceable_objs     rT   r  z)Graph._snapshot_colocation_stack_metadata  sM     "33GGI 	 ; ; ==  s   ,Acolocation_stackc                 N    | j                   r|| j                  _        y || _        y ru   )r  r  r  r  )rl   rb  s     rT   r  zGraph._colocation_stack  s%     ((-=d* &6d"rV   c                     | j                   rJt        | j                  d      s| j                  d d  | j                  _        | j                  j                  S | j                  S )Nr  )r  r8  r  r  r  r   s    rT   r  z!Graph._control_dependencies_stack  sX    (( T'')FG2215 	6;;;333rV   control_deps_controllersc                 N    | j                   r|| j                  _        y || _        y ru   )r  r  r  r  )rl   re  s     rT   r  z!Graph._control_dependencies_stack  s#    
 ((7Od4/Gd,rV   c                 |    t        | j                  d      sg | j                  _        | j                  j                  S )zBA stack to maintain distribution strategy context for each thread._distribution_strategy_stack)r8  r  rh  r   s    rT   rh  z"Graph._distribution_strategy_stack  s5     4%%'EF8:d5:::rV   rh  c                 &    || j                   _        y ru   )r  rh  )rl   rh  s     rT   rh  z"Graph._distribution_strategy_stack  s    
 	% 	3rV   c                 |    t        | j                  d      sd| j                  _        | j                  j                  S )z0For implementing `tf.distribute.set_strategy()`.distribute_strategy_scopeN)r8  r  rk  r   s    rT   !_global_distribute_strategy_scopez'Graph._global_distribute_strategy_scope  s5     4%%'BC59d2777rV   c                 &    || j                   _        y ru   )r  rk  )rl   rk  s     rT   rl  z'Graph._global_distribute_strategy_scope  s    4MD0rV   c                 @    | j                   j                  t              S )zvReturns a lock to guard code that creates & mutates ops.

    See the comment for self._group_lock for more info.
    )r  groupr  r   s    rT   r  zGraph._mutation_lock  s    
 !!"677rV   c                 @    | j                   j                  t              S )zkReturns a lock to guard code for Session.run.

    See the comment for self._group_lock for more info.
    )r  ro  r  r   s    rT   _session_run_lockzGraph._session_run_lock  s    
 !!"9::rV   r{   )d   )NFFF)NNNNNTT)rQ   rK   )NNNNNT)T)TTru   r{  )~r|   r}   r~   r   rs   r  r  rE   r   r   r  r=   contextmanagerr   r  r  r  r]   rF  r   r   r  r  r   r   r  r'  r   r  r*  r   r-  r   r1  r3  r5  r  r  rD  r   rJ  rb  re  rh  rj  rp  rn  rm  rp  rA   r?   filter_tracebackr~  r   r  r  r  r   r  r   r  r  rT  r  r  r=  r   rK  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rX   r  r%   r  r  objectr"  r  r  r  rK   r)  r  r  rw  r6  r;  r?  rC  rF  rH  rJ  rM  r  r0   r  r  rW  r  r  r  r  r  rh  rl  r;   r  _Contextr  rq  r  r  s   @rT   rF   rF     s   )Ve$T  i I 	 i 
 7htn 7  7F :7x~ :7  :7x 6tChsCx6H1I,I'J 6 6
 !!H"3Xc3h-?(@#@AH H "H 6tE#xS7I2I,J'K 6 6. !!H"5hsCx.@)@#ABH H "HG 
A,"9"9 
A 
A HSM   ;;s t     
&%6 EJeY$%eP EJ$$L	2$ 	2	: &&1P/ # # #
 4*+;= ##
 5C *5C $=5Cv F *FR "&  DU3nD<M D 59$OZ+,$OLa7Z+,a7F20
(9(9 2':3D3D ' 
&Z%5%5 
&(5.1 (5T #49 # #.$**S	 2&S	 &PBtCy B

$ 2 2  20 *3 * * 0C 0D 0 0 u# u#  u#r2C 2hc " 27<DTN    L/ L/  L/^ -. D,x~ D,  D,LP4 1+# 1+  1+jD$v D$L8+S^  4	?  DyB%yBx <)Xd^ <)  <)B 94$ 94  94z '~'  ' :3(4. :3  :3|)24 2"7$ 7/" /o&D&D / / + +O++,$   @#2#A#A@@ !@ *!?!? * *C0001 6-<<66 6 	440N+O 	4 	4 %%H $%C DH H &H ;DI ; ;  &&&*.s)&& '& 8 8 %++O ,O8i11:: 8;!4!4!=!= ;rV   r%   c                    t        j                         r+t        |       rt        d      t        j                  |       S t               rt        j                  d        } ||       S t               j	                  |       S )az  Wrapper for `Graph.device()` using the default graph.

  See `tf.Graph.device` for more details.

  Args:
    device_name_or_function: The device name or function to use in the context.

  Returns:
    A context manager that specifies the default device to use for newly
    created ops.

  Raises:
    RuntimeError: If eager execution is enabled and a function is passed in.
  zEtf.device does not support functions when eager execution is enabled.c              3      K   t               j                  |       5  t        |       s#t        j                  |       5  d  d d d        nd  d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wwru   )r   r%   re   r   )rm   s    rT   combinedzdevice.<locals>.combined;  si     %%&=> /0~~56      s3   A0!A$AA$	A0A!	A$$A-)A0)	r   r<  re   rq  r%   #executing_eagerly_outside_functionsr=   rt  r   )rm   rz  s     rT   r%   r%   $  s~       '(  >>122*,!! " +,,%%&=>>rV   c                 D    t        |       rt        d      t        |       S )a  Specifies the device for ops created/executed in this context.

  This function specifies the device to be used for ops created/executed in a
  particular context. Nested contexts will inherit and also create/execute
  their ops on the specified device. If a specific device is not required,
  consider not using this function so that a device can be automatically
  assigned.  In general the use of this function is optional. `device_name` can
  be fully specified, as in "/job:worker/task:1/device:cpu:0", or partially
  specified, containing only a subset of the "/"-separated fields. Any fields
  which are specified will override device annotations from outer scopes.

  For example:

  ```python
  with tf.device('/job:foo'):
    # ops created here have devices with /job:foo
    with tf.device('/job:bar/task:0/device:gpu:2'):
      # ops created here have the fully specified device above
    with tf.device('/device:gpu:1'):
      # ops created here have the device '/job:foo/device:gpu:1'
  ```

  Args:
    device_name: The device name to use in the context.

  Returns:
    A context manager that specifies the default device to use for newly
    created ops.

  Raises:
    RuntimeError: If a function is passed in.
  z%tf.device does not support functions.)re   rq  r%   r7  s    rT   	device_v2r}  H  s$    D k
>
??		rV   r  c                 4    t               j                  |       S )zWrapper for `Graph.container()` using the default graph.

  Args:
    container_name: The container string to use in the context.

  Returns:
    A context manager that specifies the default container to use for newly
    created stateful ops.
  )r   r  )r  s    rT   r  r  o  s     
		&	&~	66rV   c                 Z   t        j                         r8| ,t        | d      st        |       } t	        | j                        S t               S t               }t        | t              r2|j                  r|j	                  | j                        S t        d      |j                  | ||      S )a  Returns a context manager for colocating op gradients with an op.

  Internal API. In eager mode, returns a context manager that sets the default
  device for new ops to the same device as the given op. Does the same if a
  function is currently being built (i.e. the current mode is graph, but the
  overall mode is eager).

  In all other cases, returns a `Graph.colocate_with()` context manager,
  optionally accounting for gradients (if a gradient UID is specified).

  Args:
    op: Operation or Tensor with which to colocate.
    gradient_uid: Optional gradient UID to enable colocation of gradients during
      compilation.
    ignore_existing: See `Graph.colocate_with()`.

  Returns:
    A context manager used to colocate ops and gradients with the specified
    operation.
  r%   zbEncountered an Eager-defined Tensor during graph construction, but a function was not being built.)r  r  )r   r<  r8  r   r%   r   r   ra   r  rp  rR  r  )r   r  r  default_graphs       rT   r  r  }  s    .  	~R"r"BII!!%'M"k"		(	(##BII.. M N 	N44
 5 H HrV   c                     t        | d |      S )N)r  )r  r   r  s     rT   r  r    s    	$R	OOrV   z,Colocations handled automatically by placer.)dateinstructionsr  c                     t        | |      S ru   )r  r  s     rT   _colocate_withr    s     
r?	++rV   rw  c                     t        j                         r&| r| D ]  }t        |      s |         t               S t	               j                  |       S )a#	  Wrapper for `Graph.control_dependencies()` using the default graph.

  See `tf.Graph.control_dependencies` for more details.

  In TensorFlow 2 with eager and/or Autograph, you should not need this method
  most of the times, as ops execute in the expected order thanks to automatic
  control dependencies. Only use it to manually control ordering, for example as
  a workaround to known issues such as `tf.function` with `tf.debugging.assert*`
  and `tf.py_function`.
  For example:

  >>> @tf.function(
  ...   input_signature=[tf.TensorSpec([None, None], tf.float32),
  ...                    tf.TensorSpec([None, None], tf.float32)])
  ... def my_assert_func_1(x, bias):
  ...   # `tf.function` attempts to execute `tf.math.add` in parallel to
  ...   # `assert_equal`. As a result an error can get raised from `tf.math.add`
  ...   # without triggering the assertion error.
  ...   tf.assert_equal(tf.shape(x)[1],
  ...                   tf.shape(bias)[1],
  ...                   message='bad shape')
  ...   return x + bias

  >>> # Error raised in either `add` or `assert`
  >>> my_assert_func_1(tf.ones((2, 5)), tf.ones((2, 7)))
  Traceback (most recent call last):
     ...
  InvalidArgumentError: ...


  >>> @tf.function(
  ...   input_signature=[tf.TensorSpec([None, None], tf.float32),
  ...                    tf.TensorSpec([None, None], tf.float32)])
  ... def my_assert_func_2(x, bias):
  ...   with tf.control_dependencies(
  ...       [tf.assert_equal(tf.shape(x)[1],
  ...                       tf.shape(bias)[1],
  ...                       message='bad shape')]):
  ...     return x + bias

  >>> # Error raised in `assert`
  >>> my_assert_func_2(tf.ones((2, 5)), tf.ones((2, 7)))
  Traceback (most recent call last):
     ...
  InvalidArgumentError: ...

  When eager execution is enabled, any callable object in the `control_inputs`
  list will be called.

  Args:
    control_inputs: A list of `Operation` or `Tensor` objects which must be
      executed or computed before running the operations defined in the context.
      Can also be `None` to clear the control dependencies. If eager execution
      is enabled, any callable object in the `control_inputs` list will be
      called.

  Returns:
   A context manager that specifies control dependencies for all
   operations constructed within the context.
  )r   r<  re   r   r   rw  )r  controls     rT   rw  rw    sO    @  # 'G
) 33NCCrV   c                     |:t        j                         }|t        d      |j                  |ur$t        d      |j                  |urt        d      |j	                  | |       y)a*  Uses the default session to run "operation".

  Args:
    operation: The Operation to be run.
    feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
      numpy ndarrays, TensorProtos, or strings.
    graph: The graph in which "operation" is defined.
    session: (Optional) A different session to use to run "operation".

  Raises:
    ValueError: If no default session is available; the default session
      does not have "graph" as its graph; or if "session" is specified,
      and it does not have "graph" as its graph.
  NzCannot execute operation using `run()`: No default session is registered. Use `with sess.as_default():` or pass an explicit session to `run(session=sess)`zCannot use the default session to execute operation: the operation's graph is different from the session's graph. Pass an explicit session to run(session=sess).zoCannot use the given session to execute operation: the operation's graph is different from the session's graph.)r*   get_default_sessionrR  r   r  )	operationrk  r   rl  s       rT   r  r    s~      _'')G - . . }}E! , - -
 }}E!   ! ! 
++i#rV   c                   |     e Zd ZdZd fdZdefdZdefdZd fdZe	j                  dee   f fd       Z xZS )	_DefaultGraphStackzHA thread-local stack of objects for providing an implicit default graph.rQ   c                 8    t         t        |           d | _        y ru   )rt  r  rs   _global_default_graphr  s    rT   rs   z_DefaultGraphStack.__init__*  s    	
d,.!%DrV   c                     | j                   r| j                   d   S | j                  r| j                  S t               | _        | j                  S )z=Override that returns a global default if the stack is empty.r[   )r*   r  rF   r   s    rT   get_defaultz_DefaultGraphStack.get_default.  sB    zzZZ^		#	#'''#(7d '''rV   c                 P    | j                   t               | _         | j                   S ru   )r  rF   r   s    rT   _GetGlobalDefaultGraphz)_DefaultGraphStack._GetGlobalDefaultGraph8  s&    !!)
 $)7d %%%rV   c                 8    t         t        |           d | _        y ru   )rt  r  resetr  r  s    rT   r  z_DefaultGraphStack.resetA  s    	
d)+!%DrV   c              #     K   t        j                          j                  j                  |j                  |j                  |j
                         	 t        t        | #  |      5 }t        j                         5  | d d d        d d d        t        j                          j                  j                          y # 1 sw Y   >xY w# 1 sw Y   BxY w# t        j                          j                  j                          w xY wwru   )r   context_switchespushrp  r  r  rt  r  r  
graph_moder'  )rl   defaultr   r   s      rT   r  z!_DefaultGraphStack.get_controllerE  s     OO&&++G,E,E,3,>,>,3,J,JL/#&&-.23W5G5G5I  oo((,,.    oo((,,.sN   ADC %C:B<?CC -D<C	CCC .DDr{   )r|   r}   r~   r   rs   rF   r  r  r  r=   rt  r   r  r  r  s   @rT   r  r  '  sM    P&(5 (&e && /x /  /rV   r  r  c                     t               } d}| j                  }t        j                  s$| j                  rt        d      | j                  }n~t        t        j                         j                  j                        D ]*  }|s|j                  }|j                  r|j                  } n |t        j                         j                  }|t        d      ||fS )z2Get the outermost context not building a function.Nz(The global graph is building a function.zNAll graphs are building functions, and no eager context was previously active.)r   r  r  r*   rp  rq  r  rS  r   r  device_stackis_building_functionenter_context_fnr  )r  outer_contextinnermost_nonempty_device_stackstack_entrys       rT   )_get_outer_context_and_inner_device_stackr  Z  s     $%--$1$H$H!		#	# &&CDD!,,M   1 B B H HI ,*5*B*B'--#44 
 +AACNNm
 > ? ? 
7	77rV   
init_scopec            
   #     K   t        j                         r"t        j                         5  d ddd       yt	               j                         } | r| d   dk7  r| dz   } t               \  }}d}d}	  |       5  t        | d      5  t        d      5  t        j                         5  t        }d}t        j                         st	               }|j                  }||_
        nO|M|j                         D ]:  }|j                   n,|j                  st         j                  }|j                  } n  ||      5  d ddd       ddd       ddd       ddd       ddd       |||_
        yy# 1 sw Y   yxY w# 1 sw Y   @xY w# 1 sw Y   DxY w# 1 sw Y   HxY w# 1 sw Y   LxY w# 1 sw Y   PxY w# |||_
        w w xY ww)a  A context manager that lifts ops out of control-flow scopes and function-building graphs.

  There is often a need to lift variable initialization ops out of control-flow
  scopes, function-building graphs, and gradient tapes. Entering an
  `init_scope` is a mechanism for satisfying these desiderata. In particular,
  entering an `init_scope` has three effects:

    (1) All control dependencies are cleared the moment the scope is entered;
        this is equivalent to entering the context manager returned from
        `control_dependencies(None)`, which has the side-effect of exiting
        control-flow scopes like `tf.cond` and `tf.while_loop`.

    (2) All operations that are created while the scope is active are lifted
        into the lowest context on the `context_stack` that is not building a
        graph function. Here, a context is defined as either a graph or an eager
        context. Every context switch, i.e., every installation of a graph as
        the default graph and every switch into eager mode, is logged in a
        thread-local stack called `context_switches`; the log entry for a
        context switch is popped from the stack when the context is exited.
        Entering an `init_scope` is equivalent to crawling up
        `context_switches`, finding the first context that is not building a
        graph function, and entering it. A caveat is that if graph mode is
        enabled but the default graph stack is empty, then entering an
        `init_scope` will simply install a fresh graph as the default one.

    (3) The gradient tape is paused while the scope is active.

  When eager execution is enabled, code inside an init_scope block runs with
  eager execution enabled even when tracing a `tf.function`. For example:

  ```python
  tf.compat.v1.enable_eager_execution()

  @tf.function
  def func():
    # A function constructs TensorFlow graphs,
    # it does not execute eagerly.
    assert not tf.executing_eagerly()
    with tf.init_scope():
      # Initialization runs with eager execution enabled
      assert tf.executing_eagerly()
  ```

  Raises:
    RuntimeError: if graph state is incompatible with this initialization.
  Nr[   r  Fskip_on_eager)r   r<  r"   stop_recordingr   r  r  r  rw  r   r  r  r_   r`   r%   )r  r  r  outer_graphouter_device_stackcontext_managercontext_manager_inputr  s           rT   r  r    s    f  				   
 ..0Erc! cke 	23 3M2 K!@? J
u& ';(**, - $((*
 *++*AA
/N+
,,8<FFH k##+%% 'o&1&<&<# 23 	
	5   > 
	 -?* 
!a V	 	5       > 
	 -?* 
!s   )G	E2AG	2F: 9F.F"F(A*F
	'F
	:E>?F
	FF"F.F: 'G	2E;7G	>FF
	
FFFF""F+	'F..F73F: :GG	r{  c                      t        j                         ryt               \  } } |        5  t        j                         cddd       S # 1 sw Y   yxY w)a}  Returns True if executing eagerly, even if inside a graph function.

  This function will check the outermost context for the program and see if
  it is in eager mode. It is useful comparing to `tf.executing_eagerly()`,
  which checks the current context and will return `False` within a
  `tf.function` body. It can be used to build library that behave differently
  in eager runtime and v1 session runtime (deprecated).

  Example:

  >>> tf.compat.v1.enable_eager_execution()
  >>> @tf.function
  ... def func():
  ...   # A function constructs TensorFlow graphs, it does not execute eagerly,
  ...   # but the outer most context is still eager.
  ...   assert not tf.executing_eagerly()
  ...   return tf.compat.v1.executing_eagerly_outside_functions()
  >>> func()
  <tf.Tensor: shape=(), dtype=bool, numpy=True>

  Returns:
    boolean, whether the outermost context is in eager mode.
  TN)r   r<  r  )r  r  s     rT   r{  r{    sF    2  @BM1	 )&&() ) )s   AAinside_functionc                  *    t               j                  S )a>  Indicates whether the caller code is executing inside a `tf.function`.

  Returns:
    Boolean, True if the caller code is executing inside a `tf.function`
    rather than eagerly.

  Example:

  >>> tf.inside_function()
  False
  >>> @tf.function
  ... def f():
  ...   print(tf.inside_function())
  >>> f()
  True
  )r   rp  r   rV   rT   r  r    s    $ 
		.	..rV   enable_eager_executionc                     t         j                         j                  d       t        j                  dd       t
        j                  t
        j                  k7  rt        | ||d      S y)a  Enables eager execution for the lifetime of this program.

  Eager execution provides an imperative interface to TensorFlow. With eager
  execution enabled, TensorFlow functions execute operations immediately (as
  opposed to adding to a graph to be executed later in a `tf.compat.v1.Session`)
  and
  return concrete values (as opposed to symbolic references to a node in a
  computational graph).

  For example:

  ```python
  tf.compat.v1.enable_eager_execution()

  # After eager execution is enabled, operations are executed as they are
  # defined and Tensor objects hold concrete values, which can be accessed as
  # numpy.ndarray`s through the numpy() method.
  assert tf.multiply(6, 7).numpy() == 42
  ```

  Eager execution cannot be enabled after TensorFlow APIs have been used to
  create or execute graphs. It is typically recommended to invoke this function
  at program startup and not in a library (as most libraries should be usable
  both with and without eager execution).

  @compatibility(TF2)
  This function is not necessary if you are using TF2. Eager execution is
  enabled by default.
  @end_compatibility

  Args:
    config: (Optional.) A `tf.compat.v1.ConfigProto` to use to configure the
      environment in which operations are executed. Note that
      `tf.compat.v1.ConfigProto` is also used to configure graph execution (via
      `tf.compat.v1.Session`) and many options within `tf.compat.v1.ConfigProto`
      are not implemented (or are irrelevant) when eager execution is enabled.
    device_policy: (Optional.) Policy controlling how operations requiring
      inputs on a specific device (e.g., a GPU 0) handle inputs on a different
      device  (e.g. GPU 1 or CPU). When set to None, an appropriate value will
      be picked automatically. The value picked may change between TensorFlow
      releases.
      Valid values:
      - DEVICE_PLACEMENT_EXPLICIT: raises an error if the
        placement is not correct.
      - DEVICE_PLACEMENT_WARN: copies the tensors which are not
        on the right device but logs a warning.
      - DEVICE_PLACEMENT_SILENT: silently copies the tensors.
        Note that this may hide performance problems as there is no notification
        provided when operations are blocked on the tensor being copied between
        devices.
      - DEVICE_PLACEMENT_SILENT_FOR_INT32: silently copies
        int32 tensors, raising errors on the other ones.
    execution_mode: (Optional.) Policy controlling how operations dispatched are
      actually executed. When set to None, an appropriate value will be picked
      automatically. The value picked may change between TensorFlow releases.
      Valid values:
      - SYNC: executes each operation synchronously.
      - ASYNC: executes each operation asynchronously. These
        operations may return "non-ready" handles.

  Raises:
    ValueError: If eager execution is enabled after creating/executing a
     TensorFlow graph, or if options provided conflict with a previous call
     to this function.
  Tr  zEnabling eager executionNconfigdevice_policyexecution_mode
server_def)	_api_usage_gaugeget_cellr  loggingvlogr   default_execution_mode
EAGER_MODEenable_eager_execution_internal)r  r  r  s      rT   r  r     s]    H !!$'	,,q,-##w'9'99*#%	  :rV   disable_eager_executionc                      t         j                         j                  d       t        j                  dd       t
        j                  t
        _        t        j                         } | d| j                  _
        yy)a{  Disables eager execution.

  This function can only be called before any Graphs, Ops, or Tensors have been
  created.

  @compatibility(TF2)
  This function is not necessary if you are using TF2. Eager execution is
  enabled by default. If you want to use Graph mode please consider
  [tf.function](https://www.tensorflow.org/api_docs/python/tf/function).
  @end_compatibility
  Fr  zDisabling eager executionN)r  r  r  r  r  r   
GRAPH_MODEr  context_safe_thread_local_datais_eager)r  s    rT   r  r  n  s^     !!%(	,,q-.#*#5#5' !]$)A! rV   c                    | 1t        | t        j                        st        dt	        |       z        |dt
        j                  t
        j                  t
        j                  t
        j                  fvrt        d      |dt
        j                  t
        j                  fvrt        d      t
        j                  t
        j                  k(  rt        j                   du}|rt        d      t
        j"                  t
        _        t
        j$                  5  t
        j&                  -t        j(                  t        j*                  | |||             n| | t
        j&                  j,                  us<||t
        j&                  j.                  us||t
        j&                  j0                  urft        dt
        j&                  j,                  d| d	t
        j&                  j.                  d
|dt
        j&                  j0                  d|d      dt
        j&                  j2                  _        ddd       t
        j6                  t
        _        y# 1 sw Y   #xY w)a  Enables eager execution for the lifetime of this program.

  Most of the doc string for enable_eager_execution is relevant here as well.

  Args:
    config: See enable_eager_execution doc string
    device_policy: See enable_eager_execution doc string
    execution_mode: See enable_eager_execution doc string
    server_def: (Optional.) A tensorflow::ServerDef proto. Enables execution on
      remote devices. GrpcServers need to be started by creating an identical
      server_def to this, and setting the appropriate task_indexes, so that the
      servers can communicate. It will then be possible to execute operations on
      remote devices.

  Raises:
    ValueError

  Nz+config must be a tf.ConfigProto, but got %sz5device_policy must be one of None, DEVICE_PLACEMENT_*z/execution_mode must be one of None, SYNC, ASYNCz<tf.enable_eager_execution must be called at program startup.r  zKTrying to change the options of an active eager execution. Context config: z, specified config: z. Context device policy: z, specified device policy: z. Context execution mode: z,  specified execution mode rN  T)ra   r   ConfigProtor  r   r   DEVICE_PLACEMENT_EXPLICITDEVICE_PLACEMENT_WARNDEVICE_PLACEMENT_SILENT!DEVICE_PLACEMENT_SILENT_FOR_INT32rR  SYNCASYNCr  r  r  r  r  _context_lock_context_set_context_lockedContext_config_device_policy_execution_moder  r  r  )r  r  r  r  graph_mode_has_been_useds        rT   r  r    s   , 
6:3I3I J
AL! " "4!B!B"88"::"DDF F L
MMD',,>>
I
JJ##w'9'9922$> 
HJ J#*#5#5'  :!!'//%'	#! "
 &0@0@0H0H"H$ 0 0 ? ??%!1!1!A!AA ##VW-=-=-L-L'**::NLM M 6:g))2-:4 (('/5: :s   DIIc                 D    t                t        j                  | |       y)a  Runs the program with an optional main function and argv list.

  The program will run with eager execution enabled.

  Example:
  ```python
  import tensorflow as tf
  # Import subject to future changes:

  def main(_):
    u = tf.constant(6.0)
    v = tf.constant(7.0)
    print(u * v)

  if __name__ == "__main__":
    tfe.run()
  ```

  Args:
    main: the main function to run.
    argv: the arguments to pass to it.
  N)r  r   r  )mainargvs     rT   	eager_runr    s    . ''$rV   reset_default_graphc                  j    t         j                         st        d      t         j                          y)a  Clears the default graph stack and resets the global default graph.

  NOTE: The default graph is a property of the current thread. This
  function applies only to the current thread.  Calling this function while
  a `tf.compat.v1.Session` or `tf.compat.v1.InteractiveSession` is active will
  result in undefined
  behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects
  after calling this function will result in undefined behavior.

  @compatibility(TF2)
  `reset_default_graph` does not work with either eager execution or
  `tf.function`, and you should not invoke it directly. To migrate code that
  uses Graph-related functions to TF2, rewrite the code without them. See the
  [migration guide](https://www.tensorflow.org/guide/migrate) for more
  description about the behavior and semantic changes between Tensorflow 1 and
  Tensorflow 2.
  @end_compatibility

  Raises:
    AssertionError: If this function is called within a nested graph.
  zDo not use tf.reset_default_graph() to clear nested graphs. If you need a cleared graph, exit the nesting and create a new graph.N)r  
is_clearedAssertionErrorr  r   rV   rT   r  r    s3    . 
	(	(	*
 D E E rV   r   c                  *    t         j                         S )a  Returns the default graph for the current thread.

  The returned graph will be the innermost graph on which a
  `Graph.as_default()` context has been entered, or a global default
  graph if none has been explicitly created.

  NOTE: The default graph is a property of the current thread. If you
  create a new thread, and wish to use the default graph in that
  thread, you must explicitly add a `with g.as_default():` in that
  thread's function.

  @compatibility(TF2)
  `get_default_graph` does not work with either eager execution or
  `tf.function`, and you should not invoke it directly. To migrate code that
  uses Graph-related functions to TF2, rewrite the code without them. See the
  [migration guide](https://www.tensorflow.org/guide/migrate) for more
  description about the behavior and semantic changes between Tensorflow 1 and
  Tensorflow 2.
  @end_compatibility

  Returns:
    The default `Graph` being used in the current thread.
  )r  r  r   rV   rT   r   r     s    2 
	)	)	++rV   c                  :    t        t        j                        dk\  S )z)Returns True if there is a default graph.r  )rQ  r  r*   r   rV   rT   has_default_graphr    s    	!''	(A	--rV   z__internal__.get_name_scopec                      t        j                         r-t        j                          j                  j                  d      S t	               j                         S )a%  Returns the current name scope in the default_graph.

  For example:

  ```python
  with tf.name_scope('scope1'):
    with tf.name_scope('scope2'):
      print(tf.get_name_scope())
  ```
  would print the string `scope1/scope2`.

  Returns:
    A string representing the current name scope.
  r  r   r<  
scope_namerstripr   r  r   rV   rT   r  r  #  s@       ??''..s33			+	+	--rV   c           
      z    t        | dd      }t        |dd      }|r|r||urt        |d| d|d|d      yyy)zFail if the 2 items are from different graphs.

  Args:
    original_item: Original item to check against.
    item: Item to check.

  Raises:
    ValueError: if graphs do not match.
  r   Nz  must be from the same graph as z (graphs are z and z).)r   rR  )original_itemr   original_graphr   s       rT   r/  r/  8  sP     ='48.
$
&%."=
	}e^	56 6 #>^rV   c                 r   t               }|j                  r|S t        |       } |rt        |t              st        d|      d}| D ]h  }d}t        |t        t        f      r|}nt        |      }|,|s|}t        |dd      }>|t        ||       M|j                  |us\t        d|z         |xs |S )a&  Returns the appropriate graph to use for the given inputs.

  This library method provides a consistent algorithm for choosing the graph
  in which an Operation should be constructed:

  1. If the default graph is being used to construct a function, we
     use the default graph.
  2. If the "graph" is specified explicitly, we validate that all of the inputs
     in "op_input_list" are compatible with that graph.
  3. Otherwise, we attempt to select a graph from the first Operation-
     or Tensor-valued input in "op_input_list", and validate that all other
     such inputs are in the same graph.
  4. If the graph was not specified and it could not be inferred from
     "op_input_list", we attempt to use the default graph.

  Args:
    op_input_list: A list of inputs to an operation, which may include `Tensor`,
      `Operation`, and other objects that may be converted to a graph element.
    graph: (Optional) The explicit graph to use.

  Raises:
    TypeError: If op_input_list is not a list or tuple, or if graph is not a
      Graph.
    ValueError: If a graph is explicitly passed and not all inputs are from it,
      or if the inputs are from multiple graphs, or we could not find a graph
      and there was no default graph.

  Returns:
    The appropriate graph to use for the given inputs.

  z!Input graph needs to be a Graph: Nr   z#%s is not from the passed-in graph.)r   rp  r   ra   rF   r  rK   r   r   r   r/  r   rR  )op_input_listr   current_default_graphoriginal_graph_elementr  graph_elements         rT   _get_graph_from_inputsr  J  s    @ ,-,,  &-
:eU+
UD
EE   PhM(Y78m'1m !.w5!-1=Ae+>NOOP" 
	'''rV   	GraphKeysc                       e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$eeeeeeeegZ%d#Z&e'jP                   e)jT                  d$d%      d&               Z+y$)'r  a  Standard names to use for graph collections.

  The standard library uses various well-known names to collect and
  retrieve values associated with a graph. For example, the
  `tf.Optimizer` subclasses default to optimizing the variables
  collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is
  specified, but it is also possible to pass an explicit list of
  variables.

  The following standard keys are defined:

  * `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared
    across distributed environment (model variables are subset of these). See
    `tf.compat.v1.global_variables`
    for more details.
    Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`,
    and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.
  * `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each
    machine. Usually used for temporarily variables, like counters.
  * `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the
    model for inference (feed forward).
  * `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will
    be trained by an optimizer. See
    `tf.compat.v1.trainable_variables`
    for more details.
  * `SUMMARIES`: the summary `Tensor` objects that have been created in the
    graph. See
    `tf.compat.v1.summary.merge_all`
    for more details.
  * `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to
    produce input for a computation. See
    `tf.compat.v1.train.start_queue_runners`
    for more details.
  * `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also
    keep moving averages.  See
    `tf.compat.v1.moving_average_variables`
    for more details.
  * `REGULARIZATION_LOSSES`: regularization losses collected during graph
    construction.

  The following standard keys are _defined_, but their collections are **not**
  automatically populated as many of the others are:

  * `WEIGHTS`
  * `BIASES`
  * `ACTIVATIONS`
  	variableslocal_variablesmetric_variablesmodel_variablestrainable_variables	summariesqueue_runnerstable_initializerasset_filepathsmoving_average_variablesregularization_lossesconcatenated_variablessaversweightsbiasesactivations
update_opslossessaveable_objects	resourceslocal_resourcestrainable_resource_variablesinit_oplocal_init_opready_opready_for_local_init_op
summary_opglobal_step	eval_steptrain_opcond_contextwhile_context_SUMMARY_V2streaming_model_portsNz,Use `tf.GraphKeys.GLOBAL_VARIABLES` instead.c                     | j                   S ru   )GLOBAL_VARIABLES)r   s    rT   	VARIABLESzGraphKeys.VARIABLES  s     rV   ),r|   r}   r~   r   r  LOCAL_VARIABLESMETRIC_VARIABLESMODEL_VARIABLESTRAINABLE_VARIABLES	SUMMARIESQUEUE_RUNNERSTABLE_INITIALIZERSASSET_FILEPATHSMOVING_AVERAGE_VARIABLESREGULARIZATION_LOSSESCONCATENATED_VARIABLESSAVERSWEIGHTSBIASESACTIVATIONS
UPDATE_OPSLOSSESSAVEABLE_OBJECTS	RESOURCESLOCAL_RESOURCESTRAINABLE_RESOURCE_VARIABLESINIT_OPLOCAL_INIT_OPREADY_OPREADY_FOR_LOCAL_INIT_OP
SUMMARY_OPGLOBAL_STEP	EVAL_STEPTRAIN_OPCOND_CONTEXTWHILE_CONTEXT_SUMMARY_COLLECTION_VARIABLE_COLLECTIONS_STREAMING_MODEL_PORTSr8   classpropertyr9   r  r  r   rV   rT   r  r    s)   .d ! &/ (%/ .)!-* &/713&'&+*&' ) &/!? '!-(5*+ )(  ,!- & "	 3  ;$ NO  P ! rV   c                 X    | j                   j                          | j                          y)a  Cleans up reference cycles from a `Graph`.

  Helpful for making sure the garbage collector doesn't need to run after a
  temporary `Graph` is no longer needed.

  Args:
    graph: A `Graph` object to destroy. Neither it nor any of its ops are usable
      after this function runs.
  N)r  clear	Dismantler   s    rT   dismantle_graphr9    s      //rV   r  c                 8    t               j                  | |       y)a  Wrapper for `Graph.add_to_collection()` using the default graph.

  See `tf.Graph.add_to_collection`
  for more details.

  Args:
    name: The key for the collection. For example, the `GraphKeys` class
      contains many standard names for collections.
    value: The value to add to the collection.

  @compatibility(eager)
  Collections are only supported in eager when variables are created inside
  an EagerVariableStore (e.g. as part of a layer or template).
  @end_compatibility
  N)r   r  )r   r   s     rT   r  r  *  s    " ''e4rV   r  c                 8    t               j                  | |       y)a  Wrapper for `Graph.add_to_collections()` using the default graph.

  See `tf.Graph.add_to_collections`
  for more details.

  Args:
    names: The key for the collections. The `GraphKeys` class contains many
      standard names for collections.
    value: The value to add to the collections.

  @compatibility(eager)
  Collections are only supported in eager when variables are created inside
  an EagerVariableStore (e.g. as part of a layer or template).
  @end_compatibility
  N)r   r  )r  r   s     rT   r  r  >  s    " ((6rV   r  c                 4    t               j                  |       S )av  Wrapper for `Graph.get_collection_ref()` using the default graph.

  See `tf.Graph.get_collection_ref`
  for more details.

  Args:
    key: The key for the collection. For example, the `GraphKeys` class contains
      many standard names for collections.

  Returns:
    The list of values in the collection with the given `name`, or an empty
    list if no value has been added to that collection.  Note that this returns
    the collection list itself, which can be modified in place to change the
    collection.

  @compatibility(eager)
  Collections are not supported when eager execution is enabled.
  @end_compatibility
  )r   r  r  s    rT   r  r  R  s    * 
		/	/	44rV   r  c                 6    t               j                  | |      S )a  Wrapper for `Graph.get_collection()` using the default graph.

  See `tf.Graph.get_collection`
  for more details.

  Args:
    key: The key for the collection. For example, the `GraphKeys` class contains
      many standard names for collections.
    scope: (Optional.) If supplied, the resulting list is filtered to include
      only items whose `name` attribute matches using `re.match`. Items without
      a `name` attribute are never returned if a scope is supplied and the
      choice or `re.match` means that a `scope` without special tokens filters
      by prefix.

  Returns:
    The list of values in the collection with the given `name`, or
    an empty list if no value has been added to that collection. The
    list contains the values in the order under which they were
    collected.

  @compatibility(eager)
  Collections are not supported when eager execution is enabled.
  @end_compatibility
  )r   r  )r  r  s     rT   r  r  j  s    4 
		+	+C	77rV   c                  2    t               j                         S )z8Returns a list of collections used in the default graph.)r   r  r   rV   rT   r  r    s    			4	4	66rV   c                     t        j                         st        | ||      S |r
t               S | |n| } |r0t	        d |D        d      }||j
                  j                  |       S t        | xs d      S )a5  Internal-only entry point for `name_scope*`.

  Internal ops do not use the public API and instead rely on
  `ops.name_scope` regardless of the execution mode. This function
  dispatches to the correct `name_scope*` implementation based on
  the arguments provided and the current mode. Specifically,

  * if `values` contains a graph tensor `Graph.name_scope` is used;
  * `name_scope_v1` is used in graph mode;
  * `name_scope_v2` -- in eager mode.

  Args:
    name: The name argument that is passed to the op function.
    default_name: The default name to use if the `name` argument is `None`.
    values: The list of `Tensor` arguments that are passed to the op function.
    skip_on_eager: Indicates to return NullContextmanager if executing eagerly.
      By default this is True since naming tensors and operations in eager mode
      have little use and cause unnecessary performance overhead. However, it is
      important to preserve variable names since they are often useful for
      debugging and saved models.

  Returns:
    `name_scope*` context manager.
  Nc              3   8   K   | ]  }t        |      s|  y wru   )is_symbolic_tensor)r  r   s     rT   r  zname_scope.<locals>.<genexpr>  s     @5&8&?@s   r  )r   r<  internal_name_scope_v1r   nextr   r  name_scope_v2)r   default_namer  r  graph_values        rT   r  r    s}    6 
	"	"	$!$f==4$ @F@$K ))$//	tzr	""rV   c                   >    e Zd ZdZed        Zdd	dZdefdZd	dZ	y)
rB  z&Graph-only version of `name_scope_v1`.c                     | j                   S ru   _namer   s    rT   r   zinternal_name_scope_v1.name  rD  rV   NrQ   c                     |'t        |t              st        dt        |      z        ||n|| _        || _        || _        y)^  Initialize the context manager.

    Args:
      name: The name argument that is passed to the op function.
      default_name: The default name to use if the `name` argument is `None`.
      values: The list of `Tensor` arguments that are passed to the op function.

    Raises:
      TypeError: if `default_name` is passed in but not a string.
    Nze`default_name` type (%s) is not a string type. You likely meant to pass this into the `values` kwarg.)ra   r]   r  r   rJ  _default_name_valuesrl   r   rE  r  s       rT   rs   zinternal_name_scope_v1.__init__  sS      J|S$A/15l1CDE E "&4DJ%DDLrV   c                 f   | j                   2| j                  &t        d| j                   d| j                  d      t	               }| j                  r_|j
                  sSt        | j                        }||ur2|}|j                         | _        | j                  j                          nd| _        nd| _        	 |j                  | j                         | _        | j                  j                         S #  | j                  + | j                  j                  t        j                            xY w)zStart the scope block.

    Returns:
      The scope name.

    Raises:
      ValueError: if neither `name` nor `default_name` is provided
        but `values` are.
    NzAt least one of name (z) and default_name (z) must be provided.)rJ  rN  rR  rM  r   rp  r  r  
_g_managerr   r  _name_scoper   sysexc_info)rl   r   g_from_inputss      rT   r   z internal_name_scope_v1.__enter__  s     zzdll6 ZZ++-. . 	A||A// -T\\:m	a	,,.!!#dodjj1d''))		$   #,,.1s   <9C6 6:D0c                      | j                   j                  |  | j                   | j                  j                  |  y y ru   )rR  r   rQ  rl   rT  s     rT   r   zinternal_name_scope_v1.__exit__  s;    Dx("doo) #rV   rz  r{   )
r|   r}   r~   r   r  r   rs   r]   r   r   r   rV   rT   rB  rB    s.    . && &P*rV   rB  r  c                   V    e Zd ZdZddgZed        Zd
ddZdee	   fdZ
dee   fd	Zy)name_scope_v1a  A context manager for use when defining a Python op.

  This context manager validates that the given `values` are from the
  same graph, makes that graph the default graph, and pushes a
  name scope in that graph (see
  `tf.Graph.name_scope`
  for more details on that).

  For example, to define a new Python op called `my_op`:

  ```python
  def my_op(a, b, c, name=None):
    with tf.name_scope(name, "MyOp", [a, b, c]) as scope:
      a = tf.convert_to_tensor(a, name="a")
      b = tf.convert_to_tensor(b, name="b")
      c = tf.convert_to_tensor(c, name="c")
      # Define some computation that uses `a`, `b`, and `c`.
      return foo_op(..., name=scope)
  ```
  rJ  rR  c                     | j                   S ru   rI  r   s    rT   r   zname_scope_v1.name  rD  rV   NrQ   c                 N    t        |||d      | _        ||| _        y|| _        y)rL  Fr  N)r  rR  rJ  rO  s       rT   rs   zname_scope_v1.__init__#  s+     "lF%9D!%DJ4DJrV   c                 6    | j                   j                         S ru   )rR  r   r   s    rT   r   zname_scope_v1.__enter__2  s    %%''rV   c                 4     | j                   j                  | S ru   )rR  r   rW  s     rT   r   zname_scope_v1.__exit__5  s    $4$$h//rV   rz  r{   )r|   r}   r~   r   r  r  r   rs   r   r]   r   r   r   r   rV   rT   rY  rY    sJ    * &) 8(# (08D> 0rV   rY  get_current_name_scopec                      t        j                          } | j                         r| j                  j                  d      S t	               j                         S )a  Returns current full name scope specified by `tf.name_scope(...)`s.

  For example,
  ```python
  with tf.name_scope("outer"):
    tf.get_current_name_scope()  # "outer"

    with tf.name_scope("inner"):
      tf.get_current_name_scope()  # "outer/inner"
  ```

  In other words, `tf.get_current_name_scope()` returns the op name prefix that
  will be prepended to, if an op is created at that place.

  Note that `@tf.function` resets the name scope stack as shown below.

  ```
  with tf.name_scope("outer"):

    @tf.function
    def foo(x):
      with tf.name_scope("inner"):
        return tf.add(x * x)  # Op name is "inner/Add", not "outer/inner/Add"
  ```
  r  r  )r1  s    rT   r^  r^  9  sC    8 	#>>  %%--//rV   c                       e Zd ZdZddgZddZed        ZdefdZ	d	dd
dddde
fdZdeeeedef      f   fdZddZy)rD  aK  A context manager for use when defining a Python op.

  This context manager pushes a name scope, which will make the name of all
  operations added within it have a prefix.

  For example, to define a new Python op called `my_op`:

  ```python
  def my_op(a, b, c, name=None):
    with tf.name_scope("MyOp") as scope:
      a = tf.convert_to_tensor(a, name="a")
      b = tf.convert_to_tensor(b, name="b")
      c = tf.convert_to_tensor(c, name="c")
      # Define some computation that uses `a`, `b`, and `c`.
      return foo_op(..., name=scope)
  ```

  When executed, the Tensors `a`, `b`, `c`, will have names `MyOp/a`, `MyOp/b`,
  and `MyOp/c`.

  Inside a `tf.function`, if the scope name already exists, the name will be
  made unique by appending `_n`. For example, calling `my_op` the second time
  will generate `MyOp_1/a`, etc.
  rJ  	_exit_fnsrQ   Nc                 V    t        |t              st        d      || _        g | _        y)zInitialize the context manager.

    Args:
      name: The prefix to use on all names created within the name scope.

    Raises:
      ValueError: If name is not a string.
    z%name for name_scope must be a string.N)ra   r]   rR  rJ  ra  rg  s     rT   rs   zname_scope_v2.__init__y  s(     dC >??DJDNrV   c                     | j                   S ru   rI  r   s    rT   r   zname_scope_v2.name  rD  rV   c                    t        j                          j                         rbj                  | j                  }|sd}n|d   dk(  r|}nr	|z   dz   }n|dz   }|_        fd}| j                  j                  |       |S t               j                  | j                        }|j                         }| j                  j                  |j                         |S )z?Start the scope block.

    Returns:
      The scope name.
    r  r[   r  c                      _         y ru   )r  )r  r1  old_names    rT   _restore_name_scopez4name_scope_v2.__enter__.<locals>._restore_name_scope  s
    !rV   )
r   r<  r  rJ  ra  r  r   r  r   r   )rl   r   r  rg  r  r1  rf  s        @@rT   r   zname_scope_v2.__enter__  s     //
C

 hZZd
8s?
_s*
CZ
!cn" nn/0
   !,,TZZ8e??$j
nnENN+rV   r   r   r   c                 H     | j                   j                         |||       yr   )ra  r'  r   s       rT   r   zname_scope_v2.__exit__  s"     DNN9m<rV   .c                 2    | j                   | j                  fS ru   rJ  ra  r   s    rT   __getstate__zname_scope_v2.__getstate__  s    ::t~~%%rV   c                 ,    |d   | _         |d   | _        y )Nr   r  rj  )rl   states     rT   __setstate__zname_scope_v2.__setstate__  s    qDJ1XDNrV   r{   )r|   r}   r~   r   r  rs   r  r   r]   r   r   r   r   rF  r   r   rk  rn  r   rV   rT   rD  rD  \  s    2 $)     D'+<@&E#tHS#X,>'?"?@ &rV   rD  c                     |rB|d   dk(  r|dd }	 d|z   dz   }t        j                  |dt        j                  |       d      S | S # t        $ r!}t        j                  |       | cY d}~S d}~ww xY w)	zRemoves name scope from a name.

  Args:
    name: A `string` name.
    export_scope: Optional `string`. Name scope to remove.

  Returns:
    Name with name scope removed, or the original name if export_scope
    is None.
  r[   r  Nz([\^]|loc:@|^)z	[\/]+(.*)z\1\2r  )countr  subr7   rw   r  r  warning)r   export_scopestr_to_replacer
  s       rT   strip_name_scoperv    s~     B3!#2&l )<7,FnVVNGV]]4-@JJ K  ooaks   3A 	A1A,&A1,A1c                     |r@|d   dk(  r|dd }	 d}t        j                  |d|z   dz   t        j                  |             S | S # t        $ r!}t        j                  |       | cY d}~S d}~ww xY w)zPrepends name scope to a name.

  Args:
    name: A `string` name.
    import_scope: Optional `string`. Name scope to add.

  Returns:
    Name with name scope added, or the original name if import_scope
    is None.
  r[   r  Nz([\^]|loc:@|^)(.*)z\1z/\2rq  )r   import_scoperu  r
  s       rT   prepend_name_scopery    s     B3!#2&l,nVVNEL$86$AMM$') ) K  ooaks   1A 	A/A*$A/*A/op_scopec              #      K   t        j                  d       t        |||       5 }| ddd       y# 1 sw Y   yxY ww)zDDEPRECATED. Same as name_scope above, just different argument order.zdtf.op_scope(values, name, default_name) is deprecated, use tf.name_scope(name, default_name, values))rE  r  N)r  warnr  )r  r   rE  r  s       rT   rz  rz    sB      
,, @ A$\&A U
K  s   $A 4	A =A zproto functionsc                     |rt        |      st        d      |rt        |      st        d      t        j                  |||f|        y)ax  Registers `to_proto` and `from_proto` functions for collection_name.

  `to_proto` function converts a Python object to the corresponding protocol
  buffer, and returns the protocol buffer.

  `from_proto` function converts protocol buffer into a Python object, and
  returns the object..

  Args:
    collection_name: Name of the collection.
    proto_type: Protobuf type, such as `saver_pb2.SaverDef`,
      `variable_pb2.VariableDef`, `queue_runner_pb2.QueueRunnerDef`..
    to_proto: Function that implements Python object to protobuf conversion.
    from_proto: Function that implements protobuf to Python object conversion.
  zto_proto must be callable.zfrom_proto must be callable.N)re   r  _proto_function_registryr  )collection_name
proto_typeto_proto
from_protos       rT   register_proto_functionr    sJ    & hx(
0
11,
2
33##Z:$F$35rV   c                 R    	 t         j                  |       d   S # t        $ r Y yw xY w)z+Returns the proto_type for collection_name.r   Nr~  r  r  r  s    rT   get_collection_proto_typer    /    #**?;A>>	     	&&c                 R    	 t         j                  |       d   S # t        $ r Y yw xY w)z2Returns the to_proto function for collection_name.r  Nr  r  s    rT   get_to_proto_functionr  '  r  r  c                 R    	 t         j                  |       d   S # t        $ r Y yw xY w)z4Returns the from_proto function for collection_name.r  Nr  r  s    rT   get_from_proto_functionr  1  r  r  c                 l   | yt        | t              r| dfS t        | d      rt        | j                  t        j
                        rpd }| j                  |_        | j                  |_        |j                  r'|j                  | j                        j                  |fS | j                  j                  |fS t        | t              r-t        j                         st        | d      j                  dfS t        | t        j                         r| j                  dfS t        | d      j                  dfS )zFOperation object corresponding to v to use for colocation constraints.Nrz  handlec                       y ru   r   r   rV   rT   r  z&_op_to_colocate_with.<locals>.<lambda>P  s    rV   T)r  )ra   rK   r8  r  r  r   r%   r   rp  rs  r   r  r   r<  r   r6   NativeObject)r  r   r  s      rT   r  r  ;  s     Y9d7N Qj:3D3DE(#$88 !"]]188$'')>>>XX[[///;(A(A(CQt,//55!X**+44:Qt,//55rV   rr  c                     t        j                  | j                  | j                  | j                  | j
                  | j                        } t        |       S )zMake a given op wrapper function `f` raw.

  Raw op wrappers can only be called with keyword arguments.

  Args:
    f: An op wrapper function to make raw.

  Returns:
    Raw `f`.
  )typesFunctionType__code____globals__r|   __defaults____closure__rB   )rr  s    rT   	to_raw_opr  b  s=     Q]]AJJ(!	ArV   c                 x    | xj                   dt        ||nd      z   z  c_         t        j                  |       d )Nz name: r  )r   r]   r    r  )r
  r   s     rT   raise_from_not_ok_statusr  t  s4    ))	C(8bAAB)!!!$$.rV   c                     t               }|j                  st        dj                  |            |j	                  |        y)a  Add a callback to run when the default function graph goes out of scope.

  Usage:

  ```python
  @tf.function
  def fn(x, v):
    expensive = expensive_object(v)
    add_exit_callback_to_default_func_graph(lambda: expensive.release())
    return g(x, expensive)

  fn(x=tf.constant(...), v=...)
  # `expensive` has been released.
  ```

  Args:
    fn: A callable that takes no arguments and whose output is ignored.
      To be executed when exiting func graph scope.

  Raises:
    RuntimeError: If executed when the current default graph is not a FuncGraph,
      or not currently executing in function creation mode (e.g., if inside
      an init_scope).
  zPCannot add scope exit callbacks when not building a function.  Default graph: {}N)r   r  rq  r:  _add_scope_exit_callback)fnr  s     rT   'add_exit_callback_to_default_func_graphr  y  sA    2 $%-		)	)
	"F=13 3 ((,rV   c                    g }d}| j                   D ]  }|j                  r||j                     j                  }d}n?|j                  r/t	        ||j                     j
                  j                        }d}nd}d}|r|j                  ||||z           n|j                  ||          ||z  } |t	        |      k(  sJ |S )a  Regroups a flat list of input tensors into scalar and sequence inputs.

  Args:
    op_def: The `op_def_pb2.OpDef` (for knowing the input types)
    inputs: a list of input `Tensor`s to the op.
    attrs: mapping from attr name to `attr_value_pb2.AttrValue` (these define
      how long each sequence is)

  Returns:
    A list of `Tensor`s (corresponding to scalar inputs) and lists of
    `Tensor`s (corresponding to sequence inputs).
  r   Tr  F)rP  number_attrr  type_list_attrrQ  rF  r   r  )r  r  r   grouped_inputsr  rP  	input_lenis_sequences           rT   r  r    s     .!## i	--.00ik		!	!eI445::??@ikikF1Q]34F1I&NA" 
c&k			rV   c                   F    e Zd ZU dZeed<   dZeed<   dZeed<   dZeed<   y	)
	PromoModer   OFFr  LEGACYr  SAFEr  ALLN)	r|   r}   r~   r  r   __annotations__r  r  r  r   rV   rT   r  r    s&    #s,&#/$-#s,rV   r  _dtype_conversion_modec                      t         S ru   )r  r   rV   rT   get_dtype_conversion_moder    s    	rV   c                  b    t         t        j                  k(  xs t         t        j                  k(  S ru   )r  r  r  r  r   rV   rT    is_auto_dtype_conversion_enabledr    s$    	- 2	9>>	1rV   c                  0    t         t        j                  k(  S ru   )r  r  r  r   rV   rT   is_numpy_style_type_promotionr    s    	9#3#3	33rV   c                     t        |       ay)zEnables the specified dtype conversion mode.

  Args:
    dtype_conversion_mode: a string that specifies dtype conversion mode. This
      string corresponds to a PromoMode Enum and can be 'off', 'legacy', 'safe'
      or 'all'.
  N)_get_promo_mode_enumr  dtype_conversion_modes    rT   set_dtype_conversion_moder    s     00EFrV   c                     | dk(  rt         j                  S | dk(  rt         j                  S | dk(  rt         j                  S | dk(  rt         j                  S t        d|  d      )z;Returns the corresponding PromoMode enum value from string.offlegacysafer  The provided promotion mode zy does not exist. Make sure the provided dtype conversion mode is one of the followings: 'off', 'legacy', 'safe' or 'all'.r  r  r  r  r  rR  r  s    rT   r  r    sl    e#==h&&>>%==

&'<&= >9 	9 rV   c                     | t         j                  k(  ry| t         j                  k(  ry| t         j                  k(  ry| t         j                  k(  ryt        d|  d      )zEReturns the corresponding PromoMode string value from PromoMode enum.r  r  r  r  r  z does not exist.r  )promo_safety_mode_enums    rT   promo_mode_enum_to_stringr    s\    y}},y////.

&'=&>>NO rV   _numpy_style_slicingc                      da y)zuIf called, follows NumPy's rules for slicing Tensors.

  Used for enabling NumPy behavior on slicing for TF NumPy.
  TN)r  r   rV   rT   enable_numpy_style_slicingr    s
     rV   c                     t         j                  j                  |      }| j                  |t        j                  |             y)zETF internal method used to set a list(int) attribute in the node_def.)r  r\  N)r   r   r]  rS  )r   rQ  ints	ints_lists       rT   set_int_list_attrr    s4    &&00408),,y.22	BCrV   c                     | y | j                   | j                   S | j                  r"t        | d      rt        | j                        S y y )Nr  )r  rp  r8  r  r  r8  s    rT   r  r     sM    
]
  ,&&&
!>!%"3"344 "?rV   c                     t        j                  |       }|j                  rm|j                  d   }|j                  j	                         }|j
                  |_        |j                  j                  |j                  d   j                         y y r   )r3   get_resource_handle_datashape_and_typer  rQ  r   r   r   )r,   r`  r  r  protos        rT   rR  rR  0  st     99&A+ //2N##%E &&EK	KK33A6<<=	  rV   rA  c                 "    t        | t              S )zTest if `tensor` is a symbolic Tensor.

  Args:
    tensor: a tensor-like object

  Returns:
    True if `tensor` is a symbolic tensor (not an eager tensor).
  )ra   r   r+   s    rT   rA  rA  9  s     
FN	++rV   rs  ru   )NNFNN)NNNrz  )NNF)NTr{   )NNNN)NNT(  r   r  collections.abcr   r   r   
contextlibr  enumr  rS  r  r  r   r   r   r   r	   r
   r   r   r   r   abslr   r  r   r}  google.protobufr   tensorflow.core.frameworkr   r   r   r   r   r   r   r   tensorflow.core.protobufr   tensorflow.pythonr   r   r   tensorflow.python.clientr   tensorflow.python.eagerr   r    r!   r"   tensorflow.python.frameworkr#   r$   r%   rb   r&   r'   r(   r)   r*   r,   r  r-   r.   r/   r0   r1   tensorflow.python.opsr2   r3   tensorflow.python.platformr4   r  tensorflow.python.profilerr5   profiler_tracetensorflow.python.typesr   r6   tensorflow.python.utilr7   r8   r9   r:   r;   r<   r=   r>   r?   tensorflow.python.util.compatr@   "tensorflow.python.util.deprecationrA    tensorflow.python.util.tf_exportrB   rC   rD   rE   rH   rJ   rL   rd  rN   r   r  rO   	BoolGauger  _control_flow_api_gauge_tf_function_api_gauger  rP   r  DataTyper  rU   rv  rX   AbstractContextManagerr   r   r   r   r   r]   r   r   r   r   r   r   r  ValuerM   TFE_Py_InitEagerTensorr  rr  r  trace_wrapperr   r  rF  r  r  r  r  r  r   r  r  rx   r  r  r  r  r  ru  TF_Operationr  PyOperationrK   Registryr  r  r  deprecated_endpointsr  r  r  r  r  rI   r  r  r  r  r  r  rt  r  PyGraphrF   r}  r  r  r  r  r  r"  rw  r  r  DefaultStackr  r  r   r  r  r  r{  r  r  r  r  r  r  r   r  r  r/  r  r  r9  r  r  r  r  r  r  rB  rY  r^  rD  rv  ry  rz  r~  r  Messager  r  r  r  r  r  r  r  r  Enumr  r  r  r  r  r  r  r  r  r  r  r  r  r  rR  rA  r   rV   rT   <module>r     s   6  8 8    	 
   a a a    # 4 3 2 / 2 0 / 2 / 0 ( ! 6 + ( . * 2 8 7 . . 4 0 - < B 4 3 7 0 3 2 < > 9 , ) 2 . 1 , 2 0 + 2 9 > 7 6T]Kw/	m95{;+3EF 
 
D t  (:'')57  /*..,13  .--!$&   d9--v||;< 
 
,Bf ,B^	::4@ 	"-t -!S !
 * 4 ()&//1B1B  *"2Xx,,m.A.AX~
 ;i2r:%J%%&679 :> 33 3# 3# 39[ 9x 12 	%,,. ;&' 3( 0A H{N*	++- A 	, eK789,` 48
5n,-.D !9
;(8(H(HHI94 	&B ;(8(H(HHI	&BV 		(
 
%!1!A!A4:MO P(X ";	%!1!A!A4:MO P;: <+?+? . &0RZZ(&* gcl *(2

)   %"-!!
 #'D
 ->,J,JD " .DN ;U	E!-- U	E U	En $$ $%% %):):)::)F F & ,v , ,^ "!!"5|D
=OP, , , Q E,D %0
HcUD[! /+6 8SE4K( 6+ 
.f .b &7X%6%67N%O"" O> >B3 2	;# 	;  c      
x~ 
 
 7|%;%% |%; |%;FL xj ?~d';  ?  ?F 8#nT2 # #L {m
7!4 
7 
7 ','HD'HZPt0D P 	JL
 ,1E , !L, !"GD
))GD #GDT //  *.!$26!$H*/++E2 */Z ,>+? ( ?#8
8Bu--.0N0NNO#8N <d@HTN d@  d@N 456)T ) 7)@ $/ / %/( '()6:*.J37J *JZ ()** +*( ,02637/3B) 9=B)Jx 6 $%& ': "#$,5 , %,6.4 . (R0. . 1.(6$?( ?(D {mL  L  L ^ "#$5 %5& #$%7 &7& #$%5tCy 5 &5.  !8tCy 8 "887c 7 9=,#HSM",#^E*Z>>sC E*V |n/0J55hsmD /0 /0d #+0 0 ,0D <B[J55c: [  [|3  8S 3 : zl(3-1H    -8,,->?  (,%)'+5 1558d7??#$hugoo-./h(#-./!6
8I"d(); <<=!6N## c(: $/ /
-B#	%
!!4
(9(9#::
;<#V		  %.MM 	 1 9  $ 4t 4	G9 $   # d "D	5S 	5 ,DD > %9$:;	,$ 	, <	,rV   