
    =Vh9[                        d 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 eZeZeZej8                  Zd Z eej<                        Z eej>                        Z eej@                        Z  eejB                        Z! eejD                        Z" eejF                        Z# eejH                        Z$ eejJ                        Z% eejL                        Z& eejN                        Z' eejP                        Z( eejR                        Z) eejT                        Z* eejV                        Z+ eejX                        Z, eejZ                        Z- eej\                        Z. eej^                        Z/ eej`                        Z0 eejb                        Z1 eejd                        Z2 eejf                        Z3 eejh                        Z4 eejj                        Z5 eejl                        Z6 eejn                        Z7 eejp                        Z8d Z9e	jt                  e	jv                  e	jx                  e	jz                  e	j|                  e	j~                  e	j                  e	j                  iZBe	jv                  e	jt                  e	jz                  e	jx                  e	j~                  e	j|                  e	j                  e	j                  iZCd8dZDd8dZE e9ej                        ZF e9ej                        ZG e9ej                        ZH e9ej                        ZI e9ej                        ZK e9ej                        Z e9ej                        Z e9ej                        ZN e9ej                        ZO e9ej                        ZP e9ej                        ZQ e9ej                        ZR e9ej                        ZT e9ej                        ZV e9ej                        ZX e9ej                        ZZ e9ej                        Z\ e9ej                        Z^ e9ej                        Z_ e9ej                        Za e9eD      Zb e9eE      Zc e9ej                        Zd e9ej                        Ze e9ej                        Zf e9ej                        Zg e9ej                        Zh e9ej                        Zid Zj ejej                        Zk ejej                        Zmej                  Zod8dZpd8dZqej                  Zs	 	 	 	 	 	 d9dZtej                  Zvd8dZwej                  Zxej                  Zy	 	 	 	 d:dZzd Z{d8dZ|ej                  Z~ej                  Zej                  Zej                  Zd8dZd8d Zd! Zej                  Zej                  Zej                  Z e
j                  d"       	 	 	 	 	 d;d#Zej                   Zej$                  Zej(                  Zej,                  Zd<d$Zd8d%Zej4                  Zej8                  Zd& Zej<                  Z e
j@                  d'      d(        ZejD                  ZejH                  Z e
j@                  d)      d*        Z e
j@                  d+      d,        ZejP                  ZejT                  ZejX                  Zej\                  Zej`                  Zejd                  Z	 	 	 d=d-Zd.d/d/dd/d0d1Zd2 Zd3 Z	 	 d>d4Z	 	 d>d5Zd6 Zd7 Zy)?a-  Experimental library that exposes XLA operations directly in TensorFlow.

It is sometimes useful to be able to build HLO programs directly from
TensorFlow. This file provides Tensorflow operators that mirror the semantics of
HLO operators as closely as possible.

Note: Most of the operators defined in this module are used by the jax2tf
converter (see go/jax2tf for details) and are used in SavedModel produced
by jax2tf. Hence, we need to maintain backwards compatibility for these
operators. Please reach out to the JAX team if you want to make changes.
    )gen_xla_ops)xla_data_pb2)attr_value_pb2)constant_op)dtypes)ops)	array_ops)bitwise_ops)gen_math_ops)gen_random_ops)math_ops)
random_ops)random_ops_util)special_math_ops)np_utilsc                      d fd	}|S ):Wrapper that restricts `fn` to have the correct signature.c                      | |      S Nname )xr   fns     U/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/compiler/tf2xla/python/xla.pyunary_op_wrapperz#_unary_op.<locals>.unary_op_wrapperI   s    ad    Nr   )r   r   s   ` r   	_unary_opr   F   s     
r   c                      d fd	}|S )zGWraps a binary Tensorflow operator and performs XLA-style broadcasting.c                     |xs g }t        j                  |t        j                        }t	        j
                  | ||      \  } } | ||      S )zInner wrapper function.r   )r   convert_to_tensorr   int64r   xla_broadcast_helper)r   ybroadcast_dimsr   r   s       r   broadcasting_binary_op_wrapperz?_broadcasting_binary_op.<locals>.broadcasting_binary_op_wrapper{   sL    #)rN**>6<<HN ++Aq.ADAqar   NNr   )r   r'   s   ` r   _broadcasting_binary_opr)   x   s     
('r   Nc                 2   |j                   | j                   k(  sJ | j                   }|t        v }|r5t        |   }t        j                  | |      } t        j                  ||      }t	        j
                  | ||      }|rt        j                  ||      }|S )zCPerforms an integer right logical shift irrespective of input type.r   )dtype_SIGNED_TO_UNSIGNED_TABLEr   castr
   right_shift)r   r%   r   r+   signedunsigned_dtypeoutputs          r   _shift_right_logical_helperr2      s    	
AGG		
''%--&.u5Na(Aa(A""1ad3&]]65)F	-r   c                 2   |j                   | j                   k(  sJ | j                   }|t        v }|r5t        |   }t        j                  | |      } t        j                  ||      }t	        j
                  | ||      }|rt        j                  ||      }|S )zFPerforms an integer right arithmetic shift irrespective of input type.r   )r+   _UNSIGNED_TO_SIGNED_TABLEr   r-   r
   r.   )r   r%   r   r+   unsignedsigned_dtyper1   s          r   _shift_right_arithmetic_helperr7      s    	
AGG		
''%//(,U3La&Aa&A""1ad3&]]65)F	-r   c                      d fd	}|S )r   c                      | ||      S r   r   )r   r%   r   r   s      r   binary_op_wrapperz%_binary_op.<locals>.binary_op_wrapper   s    ar   r   r   )r   r:   s   ` r   
_binary_opr;      s     
r   c                     t        j                  |       } t        j                  t	        j
                  |      t        j                  |       gd      }t        j                  | ||      S )Nr   )axisr   )r   r"   r	   concatr   constantshapebroadcast_to)r   dimsr   r@   s       r   	broadcastrC      sW    	A!


D!9??1#56Q% 
		5t	44r   c                 6    t        t        | ||      ||      S r   )minmax)ar   br   s       r   clamprI      s    	SAD!14	00r   Fc                    d}|r|j                         }|	xs  | j                  |j                  k7  xs |dkD  }|	*t        j                  | j                  |j                        }	|s|r/t	        j
                  | ||||||||j                         ||	|
      S t	        j                  | |||||||j                         ||

      S )a  Wraps the XLA ConvGeneralDilated operator.

  ConvGeneralDilated is the most general form of XLA convolution and is
  documented at
  https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution

  Args:
    lhs: the input tensor
    rhs: the kernel tensor
    window_strides: the inter-window strides
    padding: the padding to apply at the start and end of each input dimensions
    lhs_dilation: dilation to apply between input elements
    rhs_dilation: dilation to apply between kernel elements
    dimension_numbers: a `ConvolutionDimensionNumbers` proto.
    feature_group_count: number of feature groups for grouped convolution.
    precision_config: a `xla.PrecisionConfig` proto.
    preferred_element_type: the result `dtype`.
    name: an optional name for the operator.
    use_v2: an optional request to use the XlaConvV2 op even if not necessary.
    batch_group_count: number of batch groups or grouped filters.

  Returns:
    A tensor representing the output of the convolution.
      )
window_stridespaddinglhs_dilationrhs_dilationfeature_group_countbatch_group_countdimension_numbersprecision_configpreferred_element_typer   )rM   rN   rO   rP   rQ   rS   rT   r   )SerializeToStringr+   r   result_typer   xla_conv_v2xla_conv)lhsrhsrM   rN   rO   rP   rS   rQ   rT   rU   r   use_v2rR   precision_config_protoneeds_v2s                  r   convr_      s    N -??A 
))syy
 	Q	 
 #%11#))SYYG""%!!/++==?/5  
				#-);;=-
 r   c                 4    t        j                  | |d|      S )NrL   )axesr   )r   	tensordot)rZ   r[   r   s      r   dotrc   E  s    			C14	88r   c                 f   d}|r|j                         }|xs | j                  |j                  k7  }|*t        j                  | j                  |j                        }|s|r)t	        j
                  | ||j                         |||      S t	        j                  | ||j                         ||      S )NrK   )rS   rT   rU   r   )rS   rT   r   )rV   r+   r   rW   r   
xla_dot_v2xla_dot)	rZ   r[   rS   rT   rU   r   r\   r]   r^   s	            r   dot_generalrg   M  s     -??A#?		SYY(>(#%11#))SYYG!!+==?/5  
				);;=-
 r   c                 2    t        j                  | |||      S r   )r   xla_self_adjoint_eig)rG   lowermax_iterepsilons       r   self_adjoint_eigrm   n  s    		)	)!UHg	FFr   c                 Z    d}|r|j                         }t        j                  | |||      S )NrK   )rV   r   xla_svd)rG   rk   rl   rT   r]   s        r   svdrp   r  s2    -??A			Q'3I	JJr   c                 t    t        j                  |       } t        j                  || || j                  |      S )N)meanstddevr+   r   )r   r"   r   random_normalr+   )musigmarB   r   s       r   rt   rt     s4    
R "		!	!
E
 r   c                 t    t        j                  |       } t        j                  || || j                  |      S )N)r+   r   )r   r"   r   random_uniformr+   )minvalmaxvalrB   r   s       r   rx   rx     s4      (&		"	"
FF&,,T
 r   c                 ^    t        j                  |       }t        j                  ||||      S )aD  Stateless PRNG bit generator.

  Wraps the XLA RngBitGenerator operator, documented at
    https://www.tensorflow.org/performance/xla/operation_semantics#rngbitgenerator.

  Args:
    algorithm: The PRNG algorithm to use, one of tf.random.Algorithm.{PHILOX,
      THREEFRY, AUTO_SELECT}.
    initial_state: Initial state for the PRNG algorithm. For THREEFRY, it should
      be a u64[2] and for PHILOX a u64[3].
    shape: The output shape of the generated data.
    dtype: The type of the tensor.

  Returns:
    a tuple with a new state and generated data of the given shape.
  r+   )r   convert_alg_to_intr   xla_rng_bit_generator)	algorithminitial_stater@   r+   alg_ints        r   rng_bit_generatorr     s0    " ..y9'		*	*}e5
 r   XlaVariadicReducec	                     |xs dgt        |      z  }|xs dgt        |      z  }|xs dgt        |      z  }|xs dgt        |      z  }t        j                  | ||||||||	      S )aN  Wraps the XLA ReduceWindow operator.

  ReduceWindow is documented at
  https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow .

  Args:
    operand: the input tensor
    init: a scalar tensor representing the initial value for the reduction
    reducer: a reduction function that combines a pair of scalars.
    window_dimensions: shape of the window, as a list of integers
    window_strides: inter-window strides, as a list of integers. Optional; if
      omitted, defaults to strides of 1.
    padding: padding to apply to 'operand'. List of (low, high) pairs of
      integers that specify the padding to apply before and after each
      dimension. Optional; if omitted, defaults to no padding.
    name: the operator name, or None.

  Returns:
    A tensor that represents the output of the reduce_window operator.
  rL   )r   r   )	input
init_valuewindow_dimensionsrM   base_dilationswindow_dilationsrN   computationr   )lenr   xla_reduce_window)	operandinitreducerr   rM   r   r   rN   r   s	            r   reduce_windowr     s    > "AaS3/@+A%A.!AaS3/@+A%A.%E!s3D/E)E8x#&7"88'		&	&)##'

 
r   c                 f    |t        j                  | |      } t        j                  | ||      } | S r   )r	   	transposereshape)r   	new_sizes
dimensionsr   s       r   r   r     s3    Az*A940!	
(r   c                 2    t        j                  | |||      S r   )r	   where)	conditionr   r%   r   s       r   selectr     s    	Aq$	//r   c           
          t        |||      D cg c]  \  }}}t        |||       }}}}| t        |         S c c}}}w r   )zip_slicetuple)r   
start_dims
limit_dimsstridesstartlimitstridespecs           r   slicer     sS     %(
J$H
 

 5% UE6"
$ 
 
5;	
s   <XlaShardingc                     | j                  d      }t        j                  ||| j                  d            }|j                  j	                  dt        j                  |             |gS )zGradient for XlaSharding op.shardingunspecified_dims)r   r   _XlaSharding)s)get_attrr   xla_shardingop	_set_attrr   	AttrValue)r   gradsharding_attrgrad_shardings       r   _sharding_gradr     se     ++j)-**
{{#56- n..? r   XlaSpmdFullToShardShapec           	          t        j                  || j                  d      | j                  d   j                  j                         | j                  d      | j                  d            }|gS )Nmanual_shardingr   dimr   )r   
full_shaper   r   )r   xla_spmd_shard_to_full_shaper   inputsr@   as_list)r   r   s2fs      r   _spmd_full_to_shard_shape_gradr   *  s^    00
kk"341##++-
++e
{{#56	# ,r   XlaSpmdShardToFullShapec                     t        j                  || j                  d      | j                  d      | j                  d            }|gS )Nr   r   r   )r   r   r   )r   xla_spmd_full_to_shard_shaper   )r   r   f2ss      r   _spmd_shard_to_full_shape_gradr   6  sD    00
kk"34
++e
{{#56		# ,r   c                     t        j                  || |dn||dn|t        d |D              t        d |D              |      S )a  Emits an HLO `CustomCall` operation with multiple outputs.

  See `CustomCall` specification at
    https://tensorflow.org/xla/operation_semantics#customcall,
  and `mhlo.custom_call` specification at
    https://tensorflow.org/mlir/hlo_ops#mhlocustom_call_mlirmhlocustomcallop.

  Args:
    call_target_name: Name of the user function. The function signature must
      conform to version 3 of the API, see
      `API_VERSION_STATUS_RETURNING_UNIFIED`. All operands and results assumed
      to be in the default layout.
    operands: A sequence of tensors with possibly different types.
    result_specs: A sequence of tensor specs for all results.
    backend_config: A string that encodes a metadata for the backend. Empty
      string by default.
    has_side_effect: Indicates whether the custom call has side effects. `False`
      by default.
    name: Optional name of the operation.

  Returns:
    A tuple of output tensors.
  rK   Fc              3   4   K   | ]  }|j                     y wr   r|   .0r   s     r   	<genexpr>z!custom_call_v2.<locals>.<genexpr>m       >$**>   c              3   4   K   | ]  }|j                     y wr   )r@   r   s     r   r   z!custom_call_v2.<locals>.<genexpr>n  r   r   )operandscall_target_namebackend_confighas_side_effectresult_dtypesresult_shapesr   )r   xla_custom_call_v2r   )r   r   result_specsr   r   r   s         r   custom_call_v2r   I  sP    > 
	'	'')1R~.6eO>>>>>>
 r      r   )version	platformsfunction_listhas_token_input_outputdisabled_checksc                |    t        j                  | ||d||||||
      }	t        |	t        j                        rd}	|	S )zSee documentation for the XlaCallModule op.

  https://github.com/search?q=repo%3Atensorflow%2Ftensorflow+path%3Axla_ops.cc+xlacallmodule&type=code
  r   )	r   moduledim_args_specToutSoutr   r   r   r   )r   xla_call_module
isinstancer   	Operation)
argsr   r   r   r   r   r   r   r   ress
             r   call_moduler   u  sL      	##
!3%	#  S]]#
C	*r   c                       y)zMaximum version of XlaCallModule op supported.

  See versioning details documentation for the XlaCallModule op at:
  https://github.com/search?q=repo%3Atensorflow%2Ftensorflow+path%3Axla_call_module+%22int+kVersionMaximumSupported%22&type=code
  	   r   r   r   r   %call_module_maximum_supported_versionr     s     
r   c                       y)Nplatformr   r   r   r   "call_module_disable_check_platformr     s    	r   c                 T    t        j                  | |||j                         ||      S )N)slice_sizesrS   indices_are_sortedr   )r   
xla_gatherrV   )r   start_indicesrS   r   r   r   s         r   gatherr     s2     
		);;=+
 r   c           	      V    t        j                  | ||||j                         ||      S )N)update_computationrS   r   r   )r   xla_scatterrV   )r   scatter_indicesupdatesr   rS   r   r   s          r   scatterr     s5     
	 	 +);;=+
 r   c                  ,    t        j                  |       S r   )r   xla_optimization_barrier)r   s    r   optimization_barrierr     s    		-	-d	33r   c                 0    t        j                  | ||      S r   )r   xla_reduce_precision)r   exponent_bitsmantissa_bitss      r   reduce_precisionr     s    		)	)'=-	PPr   r   )rL   NNNFrL   )NNNF)NNNNNr(   )NNN)FN)__doc__tensorflow.compiler.tf2xla.opsr   tensorflow.compiler.xlar   tensorflow.core.frameworkr   tensorflow.python.frameworkr   r   r   tensorflow.python.opsr	   r
   r   r   r   r   r   r   tensorflow.python.ops.numpy_opsr   rF   _maxrE   _minr   r   r?   r   absconjcosceildigammaerferfcerfinvndtriexpexpm1floorimag	is_finitelgammaloglog1plogical_notnegrealroundsinsigntantanh
bessel_i0e
bessel_i1er)   int8uint8int16uint16int32uint32r#   uint64r,   r4   r2   r7   addsubmuldivmodremmaximumminimumatan2complexlogical_and
logical_orlogical_xorequaleq	not_equalnegreater_equalgegreatergt
less_equallelessltpow
left_shift
shift_leftshift_right_logicalshift_right_arithmeticigammaigamma_grad_arandom_gamma_gradigammac	polygammazetar;   r   reverserevbitcastbitcast_convert_typerC   rI   r>   concatenater_   r-   convert_element_typerc   DotDimensionNumbersPrecisionConfigrg   rm   rp   xla_dynamic_slicedynamic_slicexla_dynamic_update_slicedynamic_update_slice
xla_einsumeinsumxla_padpadrt   rx   r   xla_recvrecv
xla_reducereducexla_variadic_reduce_v2variadic_reduceno_gradientr   xla_replica_id
replica_idxla_set_bound	set_boundxla_set_dynamic_dimension_sizeset_dynamic_dimension_size!xla_remove_dynamic_dimension_sizeremove_dynamic_dimension_sizer   r   xla_select_and_scatterselect_and_scatterxla_sendsendr   r   RegisterGradientr   r   spmd_full_to_shard_shaper   spmd_shard_to_full_shaper   r   xla_sortsortxla_key_value_sortkey_value_sortxla_variadic_sortvariadic_sort	xla_while
while_loopxla_dequantize
dequantizexla_custom_callcustom_callr   r   r   r   r   r   r   r   r   r   r   <module>r     s  
 7 0 4 3 . + + - . 0 * , 1 2 4 
	 
H$$
%	8??	#(..!(..!(..!h(()		8??	#(..!,,- 	(..! '223
'223
($ KK
LL&--
LL&--
LL&--	  LL&++
MM6<<
MM6<<
MM6<<	  hll+hll+hll+hll+l../h../h..//
!("2"2
3%h&:&:;$X%8%89
%h&:&:;X^^,X//0X334X--.X001X]]+hll+$[%;%;<
-.IJ 01OP 	 	1'(B(BC+N,L,LM 
!("2"2
3#H$6$67	x}}- y**+	""# (( 51  	K\  }} 9 #66 .. 	BGK --";; 			 . 			44 # $ 	-` ''
 %%	 )GG 
 !, M M 0 !77  ## m$ % 'CC &CC  /0 1 /0 1 //--""
''
)) 	'^   "J 	0 	(4Qr   