
    uki              	      :   d Z ddlmZ ddlmZmZ ddlmZ ddlZddl	Z	ddl
Z
ddlZddlmZmZ ddlZddlmZ ddl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%Z&ddl'm(Z) ddl*m+Z+ 	 ddl,m-Z- ddl0m1Z2 ejf                  Z3e"jh                  Z4eZ5ejl                  Z6ejn                  Z8ejr                  Z:eZ;e<Z=d;dZ> G d d      Z? e?       Z@daA G d dej                        ZC eC       ZDej                  d        ZF	 	 d<d ZG eej                  d!"      dd#d$e@e@dd#d%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d=d&       ZI G d' d(      ZJd>d)ZK eej                  d*"      dd+	 d?d,       ZL	 	 d@d-ZM	 	 	 	 dAd.ZN	 	 	 	 	 	 	 	 	 	 dBd/ZO	 	 	 	 dCd0ZPdDd1ZQd2 ZRdEd3ZSej                  ZUd4 ZVd5 ZW	 	 dF	 	 	 dGd6ZXeeYe<d7f   df   ZZ	 	 dHd8Z[	 	 	 	 	 	 dId9Z\d: Z] e]        y# e.$ r
 ddl/m-Z- Y sw xY w)Jz0Provides JAX and TensorFlow interoperation APIs.    )annotations)CallableSequence)partialN)AnyUnion)logging)	tree_util)export)api)api_util)config)core)dtypes)op_shardings)source_info_util)util)_export)
shape_poly)
xla_client)xla)xla_data_pb2)xla_sharding)contextc                    t        | t        j                  t        j                  f      ry	 t        j                  d      5  t        j
                  |        d d d        y# 1 sw Y   yxY w#  Y yxY w)NTCPUF)
isinstancetfTensorVariabledeviceconstant)vs    Y/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/experimental/jax2tf/jax2tf.py	_is_tfvalr%   K   sW    BIIr{{+,	5	 kk!ns)   A- A!A- !A*&A- *A- -A1c                      e Zd Zy)_DefaultNativeSerializationN)__name__
__module____qualname__     r$   r'   r'   V   s    r,   r'   Fc                      e Zd Zd Zy)_ThreadLocalStatec                .    d| _         d| _        d | _        y )NFr+   )inside_call_tf	shape_envcall_tf_concrete_function_listselfs    r$   __init__z_ThreadLocalState.__init__l   s       D 35DN
 =AD'r,   N)r(   r)   r*   r5   r+   r,   r$   r.   r.   k   s    Ar,   r.   c               #     K   t         j                  } dt         _        	 d  | t         _        y # | t         _        w xY ww)NT)_thread_local_stater0   )prevs    r$   r0   r0   {   s6      
	+	+$'+$.	)-&&s   ?/ ?<?c                 "    t         j                  S Nr7   r2   r+   r,   r$   5get_thread_local_state_call_tf_concrete_function_listr<      s     
	;	;;r,   jax2tf_convert)tagr+   T)polymorphic_shapespolymorphic_constraintswith_gradient
enable_xlanative_serializationnative_serialization_platforms$native_serialization_disabled_checksc               l    |t         urt        j                  dt        d       ~|t         urt        j                  dt        d       ~rAt	        t
        t        f      rt        d D              st        d       t              t        j                          d fd}|S )	a`  Allows calling a JAX function from a TensorFlow program.

  See
  [README](https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md)
  for more details about usage and common problems.

  Args:
    fun_jax: target JAX function to be called. Its arguments and return value
      should be JAX arrays, or nested standard Python containers
      (tuple/list/dict) thereof (pytrees).
    polymorphic_shapes: Specifies input shapes to be treated polymorphically
      during lowering.

      .. warning:: The shape-polymorphic lowering is an experimental feature.
        It is meant to be sound, but it is known to reject some JAX programs
        that are shape polymorphic. The details of this feature can change.

      It should be `None` (all arguments are monomorphic), a single PolyShape
      or string (applies to all arguments), or a tuple/list of the same length
      as the function arguments. For each argument the shape specification
      should be `None` (monomorphic argument), or a Python object with the
      same pytree structure as the argument.
      See [how optional parameters are matched to
      arguments](https://docs.jax.dev/en/latest/pytrees.html#applying-optional-parameters-to-pytrees).

      A shape specification for an array argument should be an object
      `PolyShape(dim0, dim1, ..., dimn)`
      where each `dim` is a dimension specification: a positive integer denoting
      a monomorphic dimension of the given size, or a string denoting a
      dimension variable assumed to range over non-zero dimension sizes, or
      the special placeholder string "_" denoting a monomorphic dimension
      whose size is given by the actual argument. As a shortcut, an Ellipsis
      suffix in the list of dimension specifications stands for a list of "_"
      placeholders.

      For convenience, a shape specification can also be given as a string
      representation, e.g.: "batch, ...", "batch, height, width, _", possibly
      with surrounding parentheses: "(batch, ...)".

      The lowering fails if it cannot ensure that the it would produce the same
      sequence of TF ops for any non-zero values of the dimension variables.

      polymorphic_shapes are only supported for positional arguments; shape
      polymorphism is not supported for keyword arguments.

      See [the README](https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md#shape-polymorphic-conversion)
      for more details.

    polymorphic_constraints: a sequence of constraints on symbolic dimension
      expressions, of the form `e1 >= e2` or `e1 <= e2`.
      See more details at https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md#user-specified-symbolic-constraints.
    with_gradient: if set (default), add a tf.custom_gradient to the lowered
      function, by converting the ``jax.vjp(fun)``. This means that reverse-mode
      TensorFlow AD is supported for the output TensorFlow function, and the
      value of the gradient will be JAX-accurate.
    native_serialization_platforms: Specifies the platform(s)
      for which to lower the code. Must be a tuple of
      strings, including a subset of: 'cpu', 'cuda', 'rocm', 'tpu'.
      The default (`None``), specifies the JAX default
      backend on the machine where the lowering is done.
    native_serialization_disabled_checks: Disables the specified safety checks.
      See docstring of `DisabledSafetyCheck`.

  Returns:
    A version of `fun_jax` that expects TfVals as arguments (or
    tuple/lists/dicts thereof), and returns TfVals as outputs, and uses
    only TensorFlow ops and thus can be called from a TensorFlow program.
  zbThe `native_serialization` parameter is deprecated and will be removed in a future version of JAX.   )
stacklevelzXThe `enable_xla` parameter is deprecated and will be removed in a future version of JAX.c              3  $   K   | ]  }|d v  
 yw))cpucudarocmtpuNr+   .0ps     r$   	<genexpr>zconvert.<locals>.<genexpr>   s      9 33 9s   znnative_serialization_platforms must be a sequence containing a subset of {'cpu', 'cuda', 'rocm', 'tpu'}. Got: c            
     ^   t        j                         s/t        j                  st	        ddt         j
                   z         t        sBt        j                  t        j                  j                  t        j                               dadd}t        j                  ||       }t!        j"                  |      t        j                  ||      }t!        j"                  |d       | |f}t        j$                  |      \  }}t'        t)        t*        t-        t/        |            |            }t1              	 j3                          d r$t        j4                  dfd       } || }	nEj7                  |      \  }
}d}|
D cg c]#  }t        j8                  j;                  ||	      % }	}j=                          |	D cg c]  }t        j>                  |d
       }	}t        j@                  |	      }|S c c}w # j=                          w xY wc c}w )Nz5convert must be used outside all JAX transformations.zTrace state: Tc                    t        j                  |       }t        d |D              }t        |       \  }}t	        j
                  ||      S )Nc              3     K   | ]@  }t        |t        j                  j                  j                        r|j
                  n| B y wr:   )r   r   compatv1	DimensionvaluerO   ds     r$   rQ   zRconvert.<locals>.converted_fun_tf.<locals>.jax_arg_spec_from_tf.<locals>.<genexpr>  s?      2  )BIILL,B,BC 77IJK 2s   AA)npshapetuple_tfval_to_tensor_jax_dtypejaxShapeDtypeStruct)atf_arg_shape_a_jax_dtypes       r$   jax_arg_spec_from_tfz?convert.<locals>.converted_fun_tf.<locals>.jax_arg_spec_from_tf  sK    XXa[l 2$02 2l 2!4na !!,<<r,   )constraints)
args_specskwargs_specsrD   rE   c                 j    j                  |       \  }}t        |      t        | ||      fS )N)implrA   rg   rh   args_tf
outs_avalsouts_tf)
run_fun_tfr]   _make_custom_gradient_fn_tf)	args_flat_tfrm   rl   rg   fun_jaxrj   rh   	outs_treerA   s	      r$   *converted_fun_flat_with_custom_gradient_tfzUconvert.<locals>.converted_fun_tf.<locals>.converted_fun_flat_with_custom_gradient_tf(  sJ     ,0??<+H
(':y.-$1!+,*!+%'( (r,   zkThe jax2tf-converted function does not support gradients. Use `with_gradient` parameter to enable gradients)inputmessage
jax2tf_out)ra   TfValreturnzjax.ShapeDtypeStruct)rp   rw   rx   rw   )!r   trace_state_cleanr7   r0   
ValueError	trace_ctx_has_registered_tf_source_pathr   register_exclusionospathdirnamer   __file__r
   tree_mapr   symbolic_args_specstree_flattenr]   mappreprocess_arg_tfrangelenNativeSerializationImplbefore_conversioncustom_gradientrn   raw_opsPreventGradientafter_conversionidentitytree_unflatten)rk   	kwargs_tfre   args_jax_specskwargs_jax_specscombined_args_tfrp   args_kwargs_treers   outs_flat_tfrm   rc   ru   oxout_tfrg   rj   rh   rr   rq   rE   rD   r@   r?   rA   s                   @@@@r$   converted_fun_tfz!convert.<locals>.converted_fun_tf   s    !!#,?,N,N
A$..)
*+, ,
 *))"''//"++*FG'+$
= ''(<gFN++*+-J
 !))*>	J--$ L+%.%;%;<L%M"L"uS%67FHL #L'E-Q	SD

'+i					( 	( 
	( B<P $ =IG
 
 JJ&&Q&@
 

 :FGQBKK<0GLG%%i>FM

 Gs%   AH (HH H*H H')rk   rw   r   rw   rx   rw   )DEFAULT_NATIVE_SERIALIZATIONwarningswarnDeprecationWarningr   listr]   allrz   r   check_callable)	rq   r?   r@   rA   rB   rC   rD   rE   r   s	   ````  `` r$   convertr      s    ^ !==MM	6q* 33MM	6q* #5e}E 979 90134 4 &++I%J"WQ Qf 
r,   c                  @    e Zd Z	 	 	 	 ddZd Zd Z	 	 	 	 ddZd	dZy)
r   c                   t        ||      | _        t        |d      r|}nt        j                  |      }|| _        || _        || _        || _        || _	        y )N)rD   rE   trace)
dictconvert_kwargshasattrr_   jitrq   rg   rh   rE   rD   )r4   rq   rg   rh   rD   rE   fun_jits          r$   r5   z NativeSerializationImpl.__init__K  s_     >\DhjDw  g
  gDL DO$D0TD-*HD'r,   c                (   t         j                  g t         _        fd}|| _        d g} t        j                  | j
                  | j                  | j                  |      | j                  i | j                  | _
        |d   J |d   | _        y )Nc                      t         _        y r:   r;   )_prev_func_lists   r$   _restore_contextzCNativeSerializationImpl.before_conversion.<locals>._restore_contextd  s    ;J8r,   )	platformsdisabled_checks/_device_assignment_for_internal_jax2tf_use_onlyr   )r7   r2   r   r   _export_internalrq   rD   rE   rg   rh   exporteddevice_assignment)r4   r   _exported_device_assignmentr   s      @r$   r   z)NativeSerializationImpl.before_conversion`  s    )HHO9;6K -D#'&G,,55AA8S	
 -
 ++-DM 'q)5658;Dr,   c                $    | j                          y r:   )r   r3   s    r$   r   z(NativeSerializationImpl.after_conversionr  s    r,   c                    t        || j                        }|t        | j                  j                        | j                  j                  fS r:   )_run_exported_as_tfr   r]   	out_avalsout_tree)r4   rp   resultss      r$   rn   z"NativeSerializationImpl.run_fun_tfu  s:     ",>GE$--112DMM4J4JJJr,   c           
     ,   t        j                  | j                  | j                  j                  | j                  j
                  | j                  j                  | j                  j                  | j                  j                  | j                  d      S )NT)in_treein_avalsin_shardings_hlor   out_shardings_hlor   	apply_jit)
r   _get_vjp_funrq   r   r   r   r   r   r   r   r3   s    r$   get_vjp_funz#NativeSerializationImpl.get_vjp_fun{  sh    (,(=(=)-)?)?151O1O*.--*A*A26--2Q2Q262H2H*.0 0r,   N)rD   Sequence[str] | NonerE   Sequence[DisabledSafetyCheck])rp   Sequence[TfVal]rx   zGtuple[Sequence[TfVal], Sequence[core.ShapedArray], tree_util.PyTreeDef])rx   z-tuple[Callable, Sequence[core.AbstractValue]])r(   r)   r*   r5   r   r   rn   r   r+   r,   r$   r   r   J  sD    I/CI 6SI*<$K.K]K	0r,   r   c                6    t        |       \  }}|j                  S )aX  Computes the TensorFlow dtype using JAX's typing rules.

  If the value is a tf.Tensor, it starts with its dtype. If the value is a
  constant it uses JAX to infer its dtype. The resulting dtype follows the
  JAX type inference rules, and depends on the value of the
  JAX_ENABLE_X64 flag.

  See README.md for how 64-bit values are treated.
  )r^   dtype)valtvalrc   s      r$   dtype_of_valr     s     's+'$	r,   jax2tf_eval_polymorphic_shapes)r?   c                    d fd}|S )a  Evaluates the output shape in presence of shape polymorphism.

  This is done without lowering or executing the function, same as for
  `jax.eval_shape`.

  Args:
    fun_jax: target JAX function to be called. Its arguments and return value
      should be JAX arrays, or nested standard Python containers
      (tuple/list/dict) thereof (pytrees).
    polymorphic_shapes: Specifies input shapes to be treated polymorphically
      during shape evaluation. See discussion for `jax2tf.convert`.

      .. warning:: The shape-polymorphic lowering is an experimental feature.

  Returns: a function that takes `jax.ShapeDtypeStruct`s (or any values
    with `.shape` and `.dtype` attributes) corresponding to the inputs for
    `fun_jax`, and returns a tuple with:

      * the jax.ShapeDtypeStruct corresponding to the result, as for
       `jax.eval_shape`. The shape may contain symbolic dimension expressions.
      * the value that can be passed to `polymorphic_shapes` for a subsequent
        call to `jax2tf.eval_polymorphic_shape`, or `jax2tf.convert`.

  For example:

  >>> import jax
  >>> from jax.experimental import jax2tf
  >>> from jax import numpy as jnp
  >>>
  >>> f = lambda A, x: jnp.sin(jnp.dot(A, x))
  >>> A = jax.ShapeDtypeStruct((2000, 3000), jnp.float32)
  >>> x = jax.ShapeDtypeStruct((3000, 1000), jnp.float32)
  >>> out_spec, out_poly_shape = jax2tf.eval_polymorphic_shape(f, polymorphic_shapes=["a, b", "b, c"])(A, x)
  >>> print(out_spec.shape)
  ("a", "c")
  >>> print(out_poly_shape)
  (a, c)
  >>> res_spec, res_poly_shape = jax2tf.eval_polymorphic_shape(lambda x: x.T, polymorphic_shapes=[out_poly_shape])(out_spec)
  >>> print(res_poly_shape)
  (c, a)
  c                     t        j                  |       }t        j                  g| }t	        j
                  d |      }||fS )Nc                ,    t        | j                        S r:   strr\   )rs    r$   <lambda>zKeval_polymorphic_shape.<locals>.do_eval_polymorphic_shape.<locals>.<lambda>  s    QWW r,   )r   r   r_   
eval_shaper
   r   )rg   args_poly_specsres_poly_specres_polymorphic_shaperq   r?   s       r$   do_eval_polymorphic_shapez9eval_polymorphic_shape.<locals>.do_eval_polymorphic_shape  sL    00&(ONN7=_=M%../E}U///r,   )rx   r   r+   )rq   r?   r   s   `` r$   eval_polymorphic_shaper     s    Z0 
#"r,   c                (     d fd}|fdfS )a  Wraps the function to take a (flat) list of positional args.

  jax2tf works better and is simpler when the JAX function takes and returns
  just a tuple of values (no pytrees, no kwargs). This is in part because
  jax.vjp does not support kwargs and we can only set
  tf.custom_gradient on functions with flat arguments and results

  Returns:
     * the wrapped JAX function taking and returning a flat list of arguments
     * a thunk that can be called after the wrapped function has been called
       to return the output pytree.
  Nc                     t        j                  |       \  }} |i |}t        j                  |      \  }}|k(  sJ ||S r:   )r
   r   r   )	args_flat_jax	tree_argstree_kwargstree_resres_flat_jaxr   rq   r   out_tree_refs	         r$   fun_flat_jaxz%flatten_fun_jax.<locals>.fun_flat_jax  s\    &55g}MI{	1[1H&33H=L(<8#;;;Lr,   c                      S r:   r+   )r   s   r$   r   z!flatten_fun_jax.<locals>.<lambda>  s    | r,   r+   )rq   r   r   r   s   `` @r$   flatten_fun_jaxr     s     , 
+	++r,   c                    t        |      sd| dt        |       d}t        |      t        |      \  }}t	        j
                  |d|        }|S )zwPre-processes the TF args.

  Returns: a tuple with the pre-processed TF arg, the TF shape, and the
      JAX dtype.
  z	Argument z	 of type zN of jax2tf.convert(f) should be NumPy array, scalar, tf.Variable, or tf.Tensorjax2tf_arg_)r%   type	TypeErrorr^   r   r   )arg_idxarg_tfmsgrc   s       r$   r   r     s_     
6	vhiV~ 6? ?C
C. )0)&!;;vWI67&	-r,   c               *    dddfd}|S )a  Prepares the TF function to be used with tf.custom_gradient.

  Args:
    impl: the serialization implementation details
    with_gradient: whether to include a tf.custom_gradient
    args_specs, kwargs_specs: the jax.ShapeDtypeArrays for the args and kwargs
    args_tf: the flattened TF arguments of the primal function
    outs_avals: the flattened output JAX abstract values of the primal function
    outs_tf: the flattened TF outputs of the primal function
  N)	variablesc           	     R   | rt        d|       t        j                  d      5  dd}t        t	        ||            }t        	      |z   }
j                         \  }}t        d |D              } t        |f|d
j                  | }d d d        |S # 1 sw Y   S xY w)NzmUnexpected variables used in forward pass. This should not happen for first-order differentiation. variables=
jax2tf_vjpc                    | | S t        j                  |j                        t        j                  k(  s
J d|        t        j                  |t              S )Nz
out_ct_tf=r   )r   primal_dtype_to_tangent_dtyper   r   float0r   
zeros_like_tf_np_dtype_for_float0)	out_ct_tfout_ct_avalr   s      r$   
fix_out_ctzC_make_custom_gradient_fn_tf.<locals>.grad_fn_tf.<locals>.fix_out_ct  sV    
  
11+2C2CDUfZdZcYeWffU }}V+BCCr,   c              3  F   K   | ]  }t        |j                          y wr:   r   )rO   ra   s     r$   rQ   zB_make_custom_gradient_fn_tf.<locals>.grad_fn_tf.<locals>.<genexpr>*  s       % 	AGG%   !)rA   r?   )r   core.ShapedArrayr   rw   )rz   r   
name_scoper]   r   r   r   r   )r   out_cts_flat_tfr   out_cts_fixed_flat_tfvjp_args_flat_tffun_vjp_jaxvjp_in_avalsvjp_polymorphic_shapesin_cts_flatrk   rj   rl   rm   rA   s            r$   
grad_fn_tfz/_make_custom_gradient_fn_tf.<locals>.grad_fn_tf  s    L  
|	$ 2
D $C
OZQX$YZw*??"&"2"2"4k<$ %%  G#1 

	 !1	2k+2: ;2: s   A+BB&)r   rw   r+   )	rq   rj   rA   rg   rh   rk   rl   rm   r  s	    ``  ``` r$   ro   ro     s    &  & &P 
r,   c           	        |j                   }d }t        t        || |            } t        d |j                  D              }t        d |j                  D              }t	        |       D cg c]  \  }}||j
                  v s| }}}|j                  }		 t        j                  }
|
r |
       }nd}|	|kD  rt        d| d|	 d      t        |	||t        j                  <t        j                  D cg c]"  }|j                  j                  j                   $ c}ng d	
      }t        d |j"                  D              |d<   |	dk\  r t        d |j$                  D              |d<   n*|	dk\  r%t&        j)                         |j$                  v rd|d<   |	dk\  rt*        j,                  j.                  |d<   t1        j2                  d      r t1        j4                  ddt7        |             |j8                  |d<   g }|j
                  D ]   }|j;                  |j<                  |          " t        t        t?        t@        tC        jD                               ||            } t        jF                  | fi |}t        j                  Vt        j                  D ]C  }tB        jH                  jJ                  jM                         jO                  |jP                         E tS        t        t?        t@        tC        jD                               ||jT                              }t        t        |||j                              }|S c c}}w # t        $ r d}
Y w xY wc c}w )z]Runs the `exported` as an XlaCallModule TF op.

  Returns: the flattened tuple of results.
  c                    t        d t        |j                  | j                        D              s	J || f       t        |j                        }||j                  k7  rt        j                  | |      S | S )Nc              3  V   K   | ]!  \  }}t        j                  |      r||k(   # y wr:   r   is_constant_dim)rO   d_avald_vals      r$   rQ   z>_run_exported_as_tf.<locals>._convert_value.<locals>.<genexpr>F  s.      0 65&&v.  0s   '))r   zipr\   _to_tf_dtyper   r   cast)r   avalconversion_dtypes      r$   _convert_valuez+_run_exported_as_tf.<locals>._convert_valueD  sp     0$'

CII$>0 0 =26= 0 $DJJ/4::%WWS*++jr,   c              3  T   K   | ]   }t        d  |j                  D               " yw)c              3  N   K   | ]  }t        j                  |      r|nd   y wr:   r  rY   s     r$   rQ   z0_run_exported_as_tf.<locals>.<genexpr>.<genexpr>R  s*      % %%a(Ad2 %s   #%N)r]   r\   rO   out_avals     r$   rQ   z&_run_exported_as_tf.<locals>.<genexpr>Q  s0      *   %^^% %*s   &(c              3  F   K   | ]  }t        |j                          y wr:   )r  r   r  s     r$   rQ   z&_run_exported_as_tf.<locals>.<genexpr>V  s     TXL0Tr   N   zUXlaCallModule from your TensorFlow installation supports up to serialization version z) but the serialized module needs version z5. You should upgrade TensorFlow, e.g., to tf_nightly.F)versionToutSoutfunction_listhas_token_input_outputc              3  <   K   | ]  }|j                           y wr:   )upperrN   s     r$   rQ   z&_run_exported_as_tf.<locals>.<genexpr>{  s     (Oq(Os   r   c              3  2   K   | ]  }t        |        y wr:   )r   )rO   dcs     r$   rQ   z&_run_exported_as_tf.<locals>.<genexpr>}  s      13 	B13   r      r+   
   use_shardy_partitionerzXlaCallModule %smodule)skip_replicated_sharding)+r   r]   r   r   	enumeratemodule_kept_var_idxcalling_convention_versiontfxla%call_module_maximum_supported_versionAttributeErrorNotImplementedErrorr   r7   r2   function_def	signaturenamer   disabled_safety_checksDisabledSafetyCheckplatformr   r$  rX   r	   
vlog_is_onvlogr   mlir_module_serializedappendr   r   _shard_valuer   executing_eagerlycall_modulerU   rV   get_default_graph_add_function_recursive_inference_functionr   r   )rp   r   
args_avalsr  out_shapes_tf	out_typesiatfkept_args_flat_tfr  get_max_supported_versionmax_supported_versionconcrete_fncall_module_attrskept_in_shardingsress                   r$   r   r   :  sY      *	 s><DE, * ((* *-
 TASASTT))2<)@fvq#AIeIeDesff//'% % K K 57$$
45 6%Y '<<   ==I 1OO 
"
"
,
,
1
1 PR # $)(OH<N<N(O#OK \+0 131113 ,3'( !|		%	%	'8+J+J	J)++&]%%++ ./ LL&,=(>? ( ? ?H '' ;aX66q9:;)+)=)=)?	A,./, 	,<*;<# 77C*II iill$$&>>

)
)
 	S242F2F2HJh002 	3# 	c.#x'9'9:;#	*k g 
 % $%(s$   ,MMM 4'MMMc                    t        j                  |       }t        |j                        t        | j                        k\  r/|j                  dt        | j                         | j                  k(  s	J || f       |S )a  Converts JAX avals from logical to physical, if relevant.

  JAX might have avals whose logical vs physical shape/dtype may
  differ, and only the physical view is expected to possibly
  relate to TF. TF impl rules should operate on the physical form.

  A JAX logical aval might even correspond, in principle, to several
  physical avals, but we don't support those here. Instead we assert
  there is only one and return it.
  N)r   physical_avalr   r\   )r  rK  s     r$   _jax_physical_avalrL    sq     $$T*-
m!!
"c$**o
5


.s4::
/4::
=VANPT@UV >	r,   c                T    t        t        j                  d|             j                  S )Nr+   )rL  r   ShapedArrayr   r   s    r$   _jax_physical_dtyperO    s     	D,,R7	8	>	>>r,   c                X    t        |       } t        t        d | j                              S )zIGenerate a TF shape, possibly containing None for polymorphic dimensions.c                4    t        j                  |       rd S | S r:   )r   is_symbolic_dim)rZ   s    r$   r   z#_aval_to_tf_shape.<locals>.<lambda>  s    V%;%;A%>T A r,   )rL  r]   r   r\   )r  s    r$   _aval_to_tf_shaperS    s,     
D	!$	sE:: 
   r,   c                    	 t        |       } | t        j                  k(  rt        } t
        j                  j                  |       S # t        $ r Y Cw xY wr:   )rO  r   r   r   r   r   as_dtype)	jax_dtypes    r$   r  r    sO    	#I.I
 &--'I			I	&& 
 	 		s   A 	AAc                    t        j                  | j                        }|t         j                  vrt	        d| d      |S )Nzdtype zR is not a valid JAX array type. Only arrays of numeric types are supported by JAX.)r   canonicalize_dtypeas_numpy_dtype_jax_dtype_setr   )tf_dtypedts     r$   _to_jax_dtyper]    sN       !8!89"v$$$
fRD !O O P P	)r,   c                   t        | t        j                  t        j                  f      rO|xs t	        | j
                        }t        |      }|| j
                  k7  rt        j                  | |      |fS | |fS |xs t        j                  |       j
                  }t        |       |f}|xr, t        j                  |       dkD  xr t        j                  du}|r$t        j                  j                  |d      \  }}nd}|t        |      }|t         j"                  k(  r3t        j$                  t        j&                  |       |j(                        } t+        | d      rSt!        j,                  | j
                  t         j.                        r%| j
                  j0                  j3                  |       } t        j4                  | |      }|r| |ft        j                  |<   ||fS )a<  Converts a scalar, ndarray, or tf.Tensor to a tf.Tensor with proper type.

  If `jax_dtype` is missing, uses JAX typing rules.
  See README.md for details regarding 64-bit values.

  Args:
    val: a scalar, ndarray, tf.Tensor, or tf.Variable
    jax_dtype: an optional dtype to use. If missing, uses JAX type inference
      rules for constants.
    memoize_constants: whether to memoize TF constants. We can't do this
      everywhere, we may be outside of a conversion scope.

  Returns:
    a tuple with a tf.Tensor with the type as needed by JAX, and the JAX type.
     N)NNr   r   )r   r   r   r    r]  r   r  r  r   abstractifyidr[   sizer7   constant_cachegetr   r   zerosr\   rY  r   
issubdtypeextended_rulesphysical_constconvert_to_tensor)r   rV  memoize_constantsr  	const_key
do_memoizerc   tf_vals           r$   r^   r^     s   $ bii-.5]3995I#I.399$WWS*+Y66)^8T--c288I C)$I $kq(8k=P=_=_gk=kJ%4488LQiaf~%i0	fmm	#hhrxx}&6&E&EF	g	6#4#4SYY#Pii--c2##C/?@f	9<f**959r,   .c                    |t        j                  | d      S t        j                  |      }t	        j
                  |      j                  |      }t        j                  | |d      S )a  Like TPUMPStrategy.experimental_split_to_logical_devices.

  For jax2tf purposes we want to avoid needing to thread the `strategy` object
  through the generated computation. It seems that the original function needs
  the strategy object only for error checking, which we assume is done upstream
  by JAX.

  Args:
    tensor: Input tensor to annotate.
    partition_dimensions: A list of integers, with one integer per tensor
      dimension, specifying in how many parts the dimension should be split. The
      product of integers must equal the number of devices per replica.
    use_sharding_op: whether to use a sharding op, or not.

  Returns:
    an annotated tensor.
  Tuse_sharding_op)r   	replicatemathprodr[   arangereshapetile)tensorpartition_dimensionsnum_partition_splitstile_assignments       r$   split_to_logical_devicesr|  $  s_    * !!!&$??#78II23;;/			6?D	IIr,   c          	        || S |j                         }|rt        j                  |      r| S |j                  s|j                  rxt        t        j                  t        j                  |j                              j                  |j                        j                  |j                        j                        }n|j                  }t        j                   t#        |j$                        |j                  ||j&                  |j(                        }t*        j,                  j.                  rlt        j                   t#        |j$                        |j                  |j                  |j                  |j                  |j&                  |j(                        }nd}t1        j2                         rt5        d      t7        d t8        j:                  j=                  d      dd D              }|dk  r't?        j@                  |	      jC                  | d
      S t?        j@                  |	      jC                  | d
|      S )zApply sharding to a TfVal.N)r   tile_assignment_dimensionstile_assignment_devicesreplicate_on_last_tile_dimlast_tile_dims)r   r~  r  iota_reshape_dimsiota_transpose_permr  r  zA jit function with sharded arguments or results must be used under a `tf.function` context. See https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md#support-for-partitioning for a discussionc              3  2   K   | ]  }t        |        y wr:   )int)rO   r#   s     r$   rQ   z_shard_value.<locals>.<genexpr>v  s     CSVCr!  .rG   )rG      )protoTrp  )rq  sharding_v2_proto)"to_protor   is_hlo_sharding_replicatedr  r  r   r[   ru  rs  rt  r~  rv  	transposer  flatr   
OpShardingr  r   r  r  r   r$  rX   
tf_contextr9  rz   r]   r   __version__splitr   Shardingapply_to_tensor)r   sdr&  sharding_prototadxla_sharding_v1_protoxla_sharding_v2_proto
tf_versions           r$   r8  r8  A  s    ZJ;;=.--b1J
 
0
0

*
*

		$))NEEFG	11	2	>55	6		C 
0
0C 4@3J3J~""#!/!J!J!!/!J!J#224 ""((5A5L5L$$%#1#L#L . F F(::*>>#1#L#L%446 !!!#
	BC C CR^^%9%9#%>r%BCC* '  '<=MMT N   
		%:	;	K	K	43H 
L 
 r,   c                    t        j                         } t        j                         t        j                         f| _        t        j                         t        j                         g| _        dt        j                         i| _        t        | j                        }t        | j                        }t        | j                        |t        usJ |t        usJ t        usJ t        j                  j                  |d d        t        j                  j                  |d d        t        j                  j                  d fd       y)	z/Registers TF custom container types as pytrees.ra   c                    t        |       d fS r:   r]   xss    r$   r   z._register_checkpoint_pytrees.<locals>.<lambda>  s    &+Bi%6 r,   c                    t        |      S r:   r  rc   r  s     r$   r   z._register_checkpoint_pytrees.<locals>.<lambda>  s
    eBi r,   c                    t        |       d fS r:   r  r  s    r$   r   z._register_checkpoint_pytrees.<locals>.<lambda>  s    uRy$>O r,   c                    t        |      S r:   )r   r  s     r$   r   z._register_checkpoint_pytrees.<locals>.<lambda>  s
    48 r,   c                f    t        | j                               t        | j                               fS r:   )r]   valueskeys)ss    r$   r   z._register_checkpoint_pytrees.<locals>.<lambda>  s     qxxz"E!&&(O4 r,   c                (     t        | |            S r:   )r  )kr  dict_wrappers     r$   r   z._register_checkpoint_pytrees.<locals>.<lambda>  s    LQ, r,   N)r   Modulera   bcr   r]   r   r   r_   r
   register_pytree_node)mtuple_wrapperlist_wrapperr  s      @r$   _register_checkpoint_pytreesr    s    iik! 
biik"!#	biik"!#	biik!#qss)-acc,acc, 
e	##	#	T	!!	!	T	!!	!--$$] 578OQ --$$\3O%;= --$$4,.r,   )r#   rw   rx   bool)rx   zlist[Any] | None)rq   r   r?   z9str | PolyShape | None | Sequence[str | PolyShape | None]r@   zSequence[str]rA   r  rB   r  rC   z"bool | _DefaultNativeSerializationrD   r   rE   r   rx   r   )r   rw   rx   DType)rq   r   rx   r   )rq   r   rx   ztuple[Callable, Callable])r   r  r   rw   rx   rw   )
rj   r   rA   r  rk   r   rl   zSequence[core.ShapedArray]rm   r   )rp   r   r   zexport.Exportedrx   r   )r  r   rx   r   )r  r   rx   ztuple[int | None, ...])NF)r   rw   rV  zDType | Nonerx   ztuple[TfVal, DType])rx  rw   ry  PartitionsOrReplicated)r   rw   r  zxla_client.HloSharding | Noner&  r  rx   rw   )^__doc__
__future__r   collections.abcr   r   	functoolsr   
contextlibrs  r~   	threadingtypingr   r   r   abslr	   numpyr[   r_   r
   r   jax._srcr   r   r   r   r   r   r   r   jax._src.exportr   r   jax._src.libr   
tensorflowr   !tensorflow.compiler.tf2xla.pythonr   r*  tensorflow.compiler.xlar   +tensorflow.python.compiler.xla.experimentalr   ModuleNotFoundError1tensorflow.compiler.xla.experimental.xla_shardingtensorflow.python.eagerr   r  	NameStack	PolyShaper  r2  safe_mapr   safe_zipr  rw   r  PrecisionTyper%   r'   r   r|   localr.   r7   contextmanagerr0   r<   api_hookr   r   r   r   r   r   ro   r   rL  rO  rS  bool_r   r  r]  r^   r]   r  r|  r8  r  r+   r,   r$   <module>r     s   7 " .    	      
        ! %  # & #  ; 0MF : &&	  	00  mm
mm 		 :< " "' A	 A () . .<< 			 01 ]a57"&;GcCGRTz Yz &3z  	z
 z #Ez -Az 3Pz z 2zz:0 :0z 			 @A #'4#+34# B4#r,2,6#(-(:&=: 04:
 *9: -G: *9:zs"1s,sl ?
  (( ' :>167*67;N7t uS#X45 J3IJ:>2>+/>49>B.:  S  MLLMs    H HH