
    AVhY                        d 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mZ ddlmZ dZdZ  e!dg      Z" e!g d      Z# ed       eddd      d'd              Z$ G d dejJ                        Z&d'dZ'd  Z(d! Z)d" Z*ejV                  d#        Z, G d$ d%e-      Z.d& Z/y)(z>xla is an experimental library that provides XLA support APIs.    N)xla_ops)xla_ops_grad)attr_value_pb2)summary_op_util)context)def_function)ops)	array_ops)control_flow_ops)variable_scope)
tf_logging)compat)nest)
tf_inspect)collections_abc)
deprecated)	tf_export_xla_compile_id   Placeholder)	AudioSummaryAudioSummaryV2HistogramSummaryImageSummaryMergeSummaryPrintScalarSummaryTensorSummaryTensorSummaryV2zxla.experimental.compilezXxla.experimental.compile is deprecated. Consider using `@tf.function(jit_compile=True)`.T)	warn_oncec                      t        j                         r t        j                   fd       } |       S t	               S )a  Builds an operator that compiles and runs `computation` with XLA.

  NOTE: In eager mode, `computation` will have `@tf.function` semantics.

  Args:
    computation: A Python function that builds a computation to apply to the
      input. If the function takes n inputs, 'inputs' should be a list of n
      `Tensor`s.

      `computation` may return a list of `Tensor`s and `Operation`s.
      `Tensor`s must come before `Operation`s in the returned list.

      All `Operation`s returned from `computation` will be executed when
      evaluating any of the returned output tensors.
    inputs: A list of inputs or `None` (equivalent to an empty list). Each input
      can be a nested structure containing values that can be converted to
      `Tensor`s. Note that passing an N-dimension list of compatible values will
      result in an N-dimension list of scalar `Tensor`s rather than a single
      Rank-N `Tensor`. If you need a different behavior, convert parts of
      `inputs` to `Tensor`s with `tf.convert_to_tensor`.

  Returns:
    List of `Tensor`s corresponding to the `Tensor`s from
      the output of `computation` i.e. the same return value as if
      computation(*inputs) is called directly, with the following exceptions:
      * None output: a NoOp would be returned with a control dependency on
         `computation`.
      * Single value output: a tuple containing the value would be returned.
      * Operation-only outputs: a NoOp would be returned with a control
      dependency on `computation`.
      TODO(b/121383831): Investigate into removing these special cases.

  Raises:
    RuntimeError: When eager execution is enabled.

  Known issues:
    When a tf.random operation is built with XLA, the implementation doesn't
      pass the user provided seed to the XLA compiler. As such, the XLA compiler
      generates a random number and uses it as a seed when compiling the
      operation. This implementation causes a violation of the Tensorflow
      defined semantics in two aspects. First, changing the value of the user
      defined seed doesn't change the numbers generated by the operation.
      Second, when a seed is not specified, running the program multiple times
      will generate the same numbers.
  c                      t               S N)_compile_internal)computationinputss   R/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/compiler/xla/xla.pyxla_compile_wrapperz$compile.<locals>.xla_compile_wrappers   s    {F33    )r   executing_eagerlyr   functionr$   )r%   r&   r(   s   `` r'   compiler,   >   sB    f  4 4   	;	//r)   c                        e Zd ZdZ fdZd Zdej                  fdZdej                  fdZ	d Z
dej                  fdZed	        Zed
        Z xZS )XLACompileContexta  A `ControlFlowContext` for nodes inside an XLA computation cluster.

  THIS IS ONLY FOR TENSORFLOW INTERNAL IMPLEMENTATION, DO NO USE DIRECTLY.

  The primary role of `XLACompileContext` is to mark operators inside a
  xla.compile() computation with attribute "_xla_compile_id=XYZ", where XYZ is
  a unique name.

  `ControlFlowContext` is used to perform the annotation since it integrates
  with Tensorflow constructs like ResourceVariables. For example, if a
  `ResourceVariable` is constructed inside a xla.compile() block, the
  `ResourceVariable` implementation can use
  `with ops.control_dependencies(None)` to build the variable's definition
  outside the compiled computation.
  c                     t         t        |           || _        t	        j
                  |      | _        g | _        || _        y)a  Builds a new XLACompileContext.

    Args:
      name: a unique name for the context, used to populate the
        `_xla_compile_id` attribute.
      pivot: a pivot node. Nodes in the XLACompileContext that do not have any
        inputs will have a control dependency on the pivot node. This ensures
        that nodes are correctly included in any enclosing control flow
        contexts.
    N)	superr.   __init___namer   as_bytes_name_as_bytes_unsupported_ops_pivot)selfnamepivot	__class__s      r'   r1   zXLACompileContext.__init__   s:     

T+-DJ //$/DDDKr)   c           
         | j                   rdj                  | j                   d t         D cg c]  }d|j                  d|j                  d! c}      }t        j                  dt        | j                         |       t        | j                         t        kD  r1t        j                  dt        | j                         t        z
         y y y c c}w )N
z  z ()z$%d unsupported operations found: 
%sz... and %d more)r5   join_MAX_WARNING_LINEStyper8   loggingwarninglen)r7   opop_strs      r'   report_unsupported_operationsz/XLACompileContext.report_unsupported_operations   s    yy))*=+=> "''
* 	f oo=$//0&:	T""	#&8	8)D1125GG	I 
9 s   $CrD   c                    g }g }|j                   D ]R  }d}|j                         }||| k(  rd}n|j                  }||r|j                  |       B|j                  |       T |j	                          |j                  |       ||fS )z2Remove any external control dependency on this op.FT)control_inputs_get_control_flow_context_outer_contextappend_remove_all_control_inputs_add_control_inputs)r7   rD   internal_control_inputsexternal_control_inputsxis_internal_opctxts          r'   _RemoveExternalControlEdgesz-XLACompileContext._RemoveExternalControlEdges   s       *n((*d4<.
""	 
 
&&q)&&q)* !!#23"$;;;r)   c                    |j                   t        v r+t        j                  d|j                   |j                         |j                   t
        v r| j                  j                  |       t        d |j                  D              rt        d|j                  z        t        |j                  j                  v rt        d|j                  z        |j                  t        t!        j"                  | j$                               |j&                  j)                  |       |j&                  j+                  |       | j-                  |      \  }}|j                  s|sv|j/                  | j0                         nZt3        t5        |j                              D ]9  }|j                  |   }| j7                  |      }||us(|j9                  ||       ; |rt;        j<                  d      5  | j?                          |D cg c]:  }|j@                  r,tC        jD                  |j@                  d         jF                  < }}| jI                          ddd       |jK                  |       |j@                  D cg c]  }|j                   }}| }|*|jL                  jO                  |       |jP                  }|*| jP                  r| jP                  jS                  |       yyc c}w # 1 sw Y   xY wc c}w )zFCreate op in XLACompileContext and notifies outer context recursively.zhOperation of type %s (%s) is not supported in XLA. Execution will fail if this op is used in the graph. c              3   H   K   | ]  }|j                   j                    y wr#   )dtype_is_ref_dtype).0rP   s     r'   	<genexpr>z*XLACompileContext.AddOp.<locals>.<genexpr>   s     
4Q177  
4s    "zTNon-resource Variables are not supported inside XLA computations (operator name: %s)z?XLA compiled computations cannot be nested, (operator name: %s))sNr   )*r@   _DENYLISTED_OPSrA   errorr8   _UNSUPPORTED_OPSr5   rK   anyr&   NotImplementedError_XLA_COMPILE_ATTRnode_defattr
ValueError	_set_attrr   	AttrValuer4   graphprevent_feedingprevent_fetchingrS   _add_control_inputr6   rangerC   AddValue_update_inputr	   control_dependenciesEnteroutputsr
   identityrD   ExitrM   _valuesupdaterJ   
AddInnerOp)	r7   rD   rN   rO   indexrP   real_xoutput_namesr   s	            r'   AddOpzXLACompileContext.AddOp   s    
ww/!mm346GGRWWF
 
ww""
""2&

4"))
44 "$''*+ + BKK,,, #%'WW- . . LL>33d6I6IJL HHR HHb! !% @ @ D99$
dkk* RYY( *%IIeq!?


5&
)	*  ##D) 

 -#
yy qyy|,//#
 #

 			 	45 %'JJ/qAFF/L/G

oo\*&&g 
 
$$R( '#
  0s$   ,K*?K% K*9K6%K**K3c                    |j                   | j                  v r+| j                  j                  |j                         }||S |S |}| j                  j	                  |j                          | j
                  r@| j
                  j                  |      }| j                  j	                  |j                          || j                  |j                   <   |S )zCAdd `val` to the current context and its outer context recursively.)r8   rr   _external_valuesgetaddrJ   rk   )r7   valresults      r'   rk   zXLACompileContext.AddValue  s    
xx4<<$$((2fNS..FLLSXX""++C0f
llv{{#&,D#((#Mr)   c                 v    | j                  |       | j                  r| j                  j                  |       y y r#   )rx   rJ   rt   )r7   rD   s     r'   rt   zXLACompileContext.AddInnerOp  s/    JJrN
$$R( r)   c                      y r#    r7   s    r'   
grad_statezXLACompileContext.grad_state!  s     r)   c                 X    | j                         r| j                         j                  S y)z0Forwards to the enclosing while context, if any.F)GetWhileContext	back_propr   s    r'   r   zXLACompileContext.back_prop)  s(     !!#---r)   )__name__
__module____qualname____doc__r1   rF   r	   	OperationrS   rx   rk   rt   propertyr   r   __classcell__)r:   s   @r'   r.   r.   |   ss     "
I<CMM <0G)cmm G)R")3== )
    r)   r.   c           
         |g }t        |t        j                        st        d      t	        j
                  |      }|D cg c]  }t        j                  |       }}t        j                         j                  d      }t        j                  |dz         }t        ||      }	  |j                          t        |      D cg c]+  \  }}t        j                   |dj#                  |            - }}}t	        j$                  ||      }t'        j(                         }	|	j*                  }
|	j-                  d	       t/               5   | | }ddd       |	j-                  |
       t1              }|rt3        |      \  }}nt5        |      \  }} |j6                  |        |j8                           |j:                          |st        j<                  |d
      S t        |      D cg c]+  \  }}t?        j@                  |dj#                  |            - }}}t        jB                  |      5  t        |      D cg c]  \  }}t        j                   |d|z        ! }}}ddd       |st	        j$                  ||      }|S c c}w c c}}w # 1 sw Y   LxY w#  |j8                           |j:                          w xY wc c}}w c c}}w # 1 sw Y   oxY w)aE  Builds graph operators that compiles and symbolically executes computation.

  Args:
    computation: A Python function that builds the computation to compile and
      execute.
    inputs: A list of inputs or `None` (equivalent to an empty list). Each input
      can be a nested structure containing values that are convertible to
      tensors. Note that passing an N-dimension list of compatible values will
      result in a N-dimension list of scalar tensors rather than a single Rank-N
      tensors. If you need different behavior, convert part of inputs to tensors
      with `tf.convert_to_tensor`.

  Returns:
    Same data structure as if computation(*inputs) is called directly with some
    exceptions for correctness. Exceptions include: 1) None output 2) Single
    value output 3) Operation-only outputs
  Raises:
    ValueError: If any element in computation outputs is neither an operations
      or a value that can be converted to tensor.
    ValueError: If computation outputs is non-flat and contains any Operations.
    TypeError: If `inputs` is not a list or tuple.
  Nzinputs must be a listclusterz/pivot)r8   )r8   r9   zinput_{})	structureflat_sequenceToutput_0zoutput{}z	output_%d)"
isinstancer   Sequence	TypeErrorr   flattenr	   convert_to_tensorget_default_graphunique_namer   no_opr.   rn   	enumerater
   rp   formatpack_sequence_asr   get_variable_scopeuse_resourceset_use_resource_disable_summary_contextis_flat_postprocess_flat_outputs_postprocess_non_flat_outputs
ExitResultrF   rq   groupr   xla_cluster_outputrm   )r%   r&   flat_inputsrP   cluster_namer9   r   icomputation_inputsvscopesaved_use_resourcero   outputs_is_flatoutput_tensorscontrol_depsos                   r'   r$   r$   1  s   . ^F	FO44	5
+
,, V$+3>?a&&q)?+?&&(44Y?,

 
 lX&=
>%<u='#GMMO k*Aq 	1:#4#4Q#78K  ..5
 ..0F,,
D!	!	# 1/0g1 ./g&O%>w%G"nl%B7%K"nlG~&)G))+GLLN 
!!,Z@@ N+
!Q   ):):1)=>. 
 - 
 n-Aq 	1;?3N  
**9N 
I @1 1 *G))+GLLN sb   J+J, 
0J:AJ, JAJ, 30K;K
$K.KJ, J)$J, ,$KKK(c                 B   t        | t        j                        rS| D ]N  }t        |t        j                        s1t        |t        j                        st	        |j
                  d      sN y t        | t        j                        ryt	        | j
                  d      ryy)au  Checks if outputs is a flat structure.

    Following structures and values are considered flat:
    1) None
    2) A single object
    3) A list or tuple of Tensors/Operations

    The only structures that this function understands are sequences,
    dictionaries and types defined using the attrs library.  E.g. this means
    that if outputs contains a single user-defined Object, it is considered to
    be flat. Errors are raised later on if that Object cannot be converted to a
    Tensor.

  Args:
    outputs: Output from `computation` inside `xla.compile`.

  Returns:
    A boolean indicates whether outputs is flat.
  __attrs_attrs__FT)r   r   r   Mappinghasattrr:   )ro   r   s     r'   r   r     s    , 112 
Q00
1
Q//
0
!++0
1	 001 W 12 
r)   c                 $   | 
t               } t        | t        j                        s| f} | t	        j
                         fz  } 	 | D cg c]3  }t        |t        j                        r|nt        j                  |      5 } }| D cg c]  }t        |t        j                        s|! }}| D cg c]  }t        |t        j                        r|! }}| ||z   k7  rt        d      g }|D ]\  }t        j                  |j                  r|j                  nd      5  |j                  t        j                  |             ddd       ^ ||fS c c}w # t        $ r}t        dt        |      z        d}~ww xY wc c}w c c}w # 1 sw Y   xY w)zValidates flat outputs and adds back device assignments.

  Args:
    outputs: Output from `computation` inside `xla.compile`.

  Returns:
    Tensors and Operations extracted from outputs.
  NoXLA computation function return values must all either be Operations or convertible to Tensors. Got error: "%s"zdXLA computation function must return zero or more Tensor values followed by zero or more Operations. )tupler   r   r   r   r   r	   r   r   	Exceptionrc   strdevicerK   r
   rp   )ro   r   eoutput_operationsr   new_output_tensorsts          r'   r   r     s     _gG	G_55	6jG 
$$&(('@  3==)s/D/DQ/GGG  #*JQZ3==-IqJJ&K!jCMM.JAK.K!222
	/0 0  7a	AHHb	1 7	 2 21 567 77 
.	../ 
 @
	68;A	?@ @@ KK7 7sN   E 8E?E E<%E</FF%FE 	E9E44E9F	c                    g }t        j                  |       D ]  }t        |t        j                        rt        d|j                  z        	 t        j                  |      }t        j                  |j                  r|j                  nd      5  |j                  t        j                  |             ddd        |g fS # t        $ r}t        dt        |      z        d}~ww xY w# 1 sw Y   xY w)a  Validates non-flat outputs and adds back device assignments.

  Args:
    outputs: Output from `computation` inside `xla.compile`.

  Returns:
    Tensors extracted from outputs and an empty list because Operations are not
    allowed in non-flat outputs..
  zxla.compile does not support Operation as return value in non-flat output structure. You can set returned Operations as control dependencies of returned Tensors so Operations are triggered when Tensors are evaluated. Operation found: "%s"r   Nr   )r   r   r   r	   r   rc   r8   r   r   r   r   rK   r
   rp   )ro   r   r   r   s       r'   r   r     s     <<  7a!S]]#9 <=66BC CL



"a 
AHHb	1 7	 2 21 567 7#7( 
R	  LBDGFKL LL7 7s$   C%C+	C(C##C(+C4	c               #      K   t         j                  } d t         _        	 d | t         _        y# | t         _        w xY ww)a  Enters a context where all summary ops are skipped.

  Summaries are not yet supported in xla.compile(). So we provide this context
  manager that can skip creating summary ops. This is a temporary workaround due
  to XLA not supporting summary ops.

  Yields:
    None.
  c                       y)NTr   r   r)   r'   <lambda>z*_disable_summary_context.<locals>.<lambda>%  s    r)   N)r   skip_summary)original_skip_summary_funcs    r'   r   r     s5       /;;!-/>	#=O #=O s   A 0 A =A c                   "    e Zd ZdZd Zd Zd Zy)_CapturedObjectz#A placeholder to capture an object.c                     d | _         y r#   _objectr   s    r'   r1   z_CapturedObject.__init__0  s	    DLr)   c                 @    | j                   rt        d      || _         y )NzFInternalError: _CapturedObject can capture only once. Please file bug.)r   RuntimeError)r7   r   s     r'   capturez_CapturedObject.capture3  s$    ||  DLr)   c                     | j                   S r#   r   r   s    r'   r{   z_CapturedObject.get;  s    <<r)   N)r   r   r   r   r1   r   r{   r   r)   r'   r   r   -  s    +r)   r   c                 v   d }|}|||j                   z  }t        j                  |       }t        |j                        }|j
                  d}nt        |j
                        }||z
  }||k  r#|dk(  r|j                  	 |d|      S  |d|      S |j                  ||kD  r|dk(  r	 |d|      S  |d|      S y)a  Validate the number of input arguments to an XLA function.

  Args:
    func: the Python function that will be called to generate the body of an XLA
      computation graph.
    input_arity: the number of explicit arguments supplied by the caller.
    infeed_queue: if not None, the infeed queue that will supply
      additional arguments to the function.

  Returns:
    None if function can be called with the supplied number of
      arguments, or an error string if it cannot.
  c                 &    d| ||dk(  rdfz  S dfz  S )Nz%s %d argument%s   r   rZ   r   )	complaintquantitys     r'   format_errorz3check_function_argument_count.<locals>.format_errorM  s6    H$,M 79 !< < <7:!< < <r)   Nr   exactlyzat leastzat most)number_of_tuple_elementsr   
getargspecrC   argsdefaultsvarargs)	funcinput_arityinfeed_queuer   num_args_suppliedarg_specnum_func_argsnum_func_defaultsmin_func_argss	            r'   check_function_argument_countr   ?  s    < ">>>""4((hmm$-H--."33-&A("2"2":)]33*m44"3m"CA)]33)]33 
r)   r#   )0r   
contextlibtensorflow.compiler.jit.opsr   r   tensorflow.core.frameworkr   tensorflow.python.distributer   tensorflow.python.eagerr   r   tensorflow.python.frameworkr	   tensorflow.python.opsr
   r   r   tensorflow.python.platformr   rA   tensorflow.python.utilr   r   r   tensorflow.python.util.compatr   "tensorflow.python.util.deprecationr    tensorflow.python.util.tf_exportr   r`   r?   setr[   r]   r,   XLAControlFlowContextr.   r$   r   r   r   contextmanagerr   objectr   r   r   r)   r'   <module>r      s   E  0 4 4 8 + 0 + + 2 0 < ) ' - 9 9 6%      
 
  %& (60	 '
60rr(>> rjdN'T1/h  F > >&f $-r)   