
    Vpf                    $   U d Z ddlmZ ddlZddlmZmZ ddlZddlm	Z	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ZddlZi Zded<   eZ eZ!eZ"dwdxdZ#d Z$d Z%d Z&d Z'd Z(dyd Z)dzd#Z*d{d$Z+d% Z,d& Z-d' Z.d|d*Z/d+ Z0d, Z1d- Z2d}d;Z3e3eej4        <   d~d<Z5e5eej6        <   d= Z7dd>Z8e8eej9        <   ddFZ: e	e:dG          eej;        <    e	e:dH          eej<        <   dI Z=dJ Z>dK Z?ddLZ@ddOZA e	e@dPQ          eejB        <    e	e@dRQ          eejC        <    e	e@dSQ          eejD        <   eAeejE        <    e'dT          eejF        <    e'dU          eejG        <    e'dV          eejH        <   dd[ZIejJ         G d\ d]                      ZKdd`ZLddbZM eLeM          ddc            ZNdddZO eLeO          dde            ZPddfZQddgZR eLeQ          ddh            ZSddkZT eLeR          ddl            ZUddmZVeVeejW        <   ddnZXeXeejY        <   ddoZZeZeej[        <   	 	 dddrZ\ddsZ] e]dt           eej^        <    e]ej_        ej        j`                  eeja        <    e]ejb        ej        jc                  eejd        <    e]eje        ej        jf                  eejg        <    e]ejh        ej        ji                  eejj        <    e'du          eejk        <    e'dv          eejl        <   dS )z<Workarounds for jax2tf transforms when XLA is not linked in.    )annotationsN)CallableSequence)partialwraps)Any)core)lax)slicing)dtypes)util)jax2tfz(dict[core.Primitive, Callable[..., Any]]tf_impl_no_xla primitive_namestr
suffix_msgreturn	Exceptionc                B    d|  d}|r	|d| dz  }t          |          S )NzCall to z+ cannot be converted with enable_xla=False. zZ - See source code for the precise conditions under which it can be converted without XLA.)NotImplementedError)r   r   msgs      c/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/experimental/jax2tf/impl_no_xla.py_errorr   2   sH    N>NNN# 7 6
 6 6 6 7C	S	!	!!    c                "    t          d|           S )Nconv_general_dilatedr   r   s    r   <lambda>r!   9   s    &!7== r   c                "    t          d|           S )Nreduce_windowr   r    s    r   r!   r!   :   s    F?C88 r   c                "    t          d|           S )Nz%scatter_(update/add/multiply/min/max)r   r    s    r   r!   r!   ;   s    V$KS % % r   c                      fd}|S )Nc                 "    t                    Nr   )argkwargsnames     r   opz_unimplemented.<locals>.op@   s    
,,r    )r*   r+   s   ` r   _unimplementedr-   >   s#         
)r   c                n     t           fdt          t                               D                       S )Nc              3  B   K   | ]}                     |          V  d S r'   )index).0iperms     r   	<genexpr>z&_invert_permutation.<locals>.<genexpr>J   s-      77tzz!}}777777r   )tuplerangelenr3   s   `r   _invert_permutationr9   I   s4    	7777eCII&6&6777	7	77r   xTfValx_shape
core.Shapetuple[TfVal, core.Shape]c                f    t          j        | |          t          fd|D                       fS )zComputes transposition of x and its shape.

  x_shape matches x.shape in the known dimensions, and it has dimension
  polynomials elsewhere, while x.shape has None.
  r8   c              3  (   K   | ]}|         V  d S r'   r,   )r1   r2   r<   s     r   r4   z(_transpose_with_shape.<locals>.<genexpr>S   s'      1R1R'!*1R1R1R1R1R1Rr   )tf	transposer5   )r:   r<   permutations    ` r   _transpose_with_shaperD   M   s<     
ak	*	*	*E1R1R1R1Rk1R1R1R,R,R	RRr   	lhs_shape	rhs_shapec                   |\  }}}t          | ||          \  } }t          |          dk    r.| ddddddt          j        f         } t	          |          dz   }t          | |d          \  } }t          |||          \  }}t          |          dk    r.|ddddddt          j        f         }t	          |          dz   }t          ||d          \  }}t          j        | |           t          j        ||           | |||fS )zTransposes lhs and rhs to respectively NHWC and HWIO so they can be passed to TF functions.

  The shapes passed in and returned may contain polynomials, and thus may
  be different than lhs.shape and rhs.shape.
     N   r      rH   rJ   )rL   rH   rJ   r   )rD   r7   npnewaxisr5   r   _assert_matching_abstract_shape)lhsrE   rhsrF   dimension_numberslhs_permrhs_perm_s           r   _transpose_for_tf_convrV   V   s'    ,(Ha )iBB.#y]]a aaaAAArz!
"Ci  4'I(iFF.#y )iBB.#y]]a
aaaAAArz!
"Ci  4'I(iFF.#y(i888(i888	ii	''r   c                    dD ]=}t          j        | |||          }t          |          t          |          k    r|c S >dS )N)VALIDSAMEEXPLICIT)r
   padtype_to_padslist)in_shapewindow_shapewindow_stridespaddingpad_strpadss         r   pads_to_padtyperc   x   sQ    "  gx~wOODDzzT']]""nnn #	r   c                r   t          |          }t          |          t          |          dz
  k    r
d}||z   |z   }t          j        | |          } t          | j                  t          |          k    sJ t          d t          ||          D                       }t          j        | |           | |fS )MPads `x` using `padding`, which specifies padding for the spatial dimensions.rL   r   r   c              3  2   K   | ]\  }\  }}||z   |z   V  d S r'   r,   r1   xsp0p1s       r   r4   z$_pad_spatial_dims.<locals>.<genexpr>   2      II<2xB"r'B,IIIIIIr   )r5   r7   rA   padshapezipr   rO   r:   r<   r`   no_pads       r   _pad_spatial_dimsrs      s    'NN'\\S\\A%%%Fw'GfQ!	QWW	%	%	%	%II3w3H3HIIIII'(G444	
Gr   c                    t          |          }t          |          t          |          dz
  k    r
d}||z   |z   }t          | j                  t          |          k    sJ t          d t          ||          D                       }| ||fS )re   rL   rf   c              3  2   K   | ]\  }\  }}||z   |z   V  d S r'   r,   ri   s       r   r4   z*_check_pad_spatial_dims.<locals>.<genexpr>   rm   r   )r5   r7   ro   rp   rq   s       r   _check_pad_spatial_dimsrv      s    'NN'\\S\\A%%%Fw'G	QWW	%	%	%	%II3w3H3HIIIII'	
GW	r   c           	        d}d}t          |           t          |          cxk    rt          |          k    sn t          d|  d| d| d          t          | ||          D ]\  }}\  }}||z   dz
  t          j        ||z
  d          z   }	|dz
  }
|	|
z
  }||
k    s||k    rd	}||z   dz
  }||dz
  k    r|dz
  }
n$t          t          j        |dz                      }
||
z
  }||
k    s||k    rd	}|rd
S |rdS t          d          )z3Finds the padding type for a transpose convolution.Tz*Found different lengths for kernel_sdims (z), lhs_dilation (z), and padding (z).rL   r   rJ   FrX   rY   z=Transpose convolution padding mode must be `SAME` or `VALID`.)r7   
ValueErrorrp   builtinsmaxintrM   ceil)kernel_sdimslhs_dilationr`   is_validis_sameksbeginendpad_len_validpad_apad_bpad_len_sames                r   _conv_transpose_pads_to_padtyper      s    ('	\		c,//	?	?	?	?3w<<	?	?	?	?
 1&21 1&21 1 &-1 1 1 2 2 2  lGDD  aLUCEAIQUA 6 66MEEE!E~~h q519L1q5yy!eee"',*++,,e5 E~~g 7 6 ( 	) 	) )r   rP   rQ   c                    t          j        | |           t          j        ||           t          |          dz
  }|dk    rt          d| d          dS )z Check spatial dimension support.rL   z1We only support 1D or 2D convolutions, but found .N)r   rO   r7   _conv_error)rP   rE   rQ   rF   nr_spatial_dimensionss        r   _validate_spatial_dimensionsr      sy     	(i888(i888i..1, Q
	$ 	$ 	$ 	$% % % r   c                    |r9t          |          dgz   }t          |          dgz   }t          |           dgz   } | ||fS )NrJ   rg   )r\   )r`   r~   rhs_dilation	is_conv1ds       r    _normalize_padding_and_dilationsr      sS     '%%+L%%+L
 7mmvh&G	,	,,r   c                    t          |           dk    rt          |           dgz   } t          |           dk    rdgt          |           z   dgz   } | S )z#Ensure window_strides has length 4.rJ   rL   )r7   r\   )r_   s    r   _normalize_window_stridesr      sa     	A .))QC/NAS4///1#5N	r   c           	        |dk    r|st          d          |r|r| sn5||| g                    d          dk    rt          d| d| d|  d          |dk    rt          d| d          |||k    rt          d	          d S d S )
NrJ   z$Grouped convolutions are unsupportedTzCan only do one of depthwise (z), atrous (z) and transposed convolutions ()z8Unimplemented support for batch_group_count != 1 (found z0Unimplemented support for preferred_element_type)r   count)is_transpose	is_atrousis_depthwisefeature_group_countbatch_group_countpreferred_element_type	lhs_dtypes          r   _validate_conv_featuresr      s    1\
<
=
== 9y 9, 9i.44T::Q>>
	8 	8 	8) 	8 	8(4	8 	8 	89 9 9
 !
 /+/ / / 0 0 0 (	))
H
I
II )())r   rR   lax.ConvDimensionNumbersr   r{   r   	precision*tuple[PrecisionType, PrecisionType] | Noner   DType | None	_in_avalsSequence[core.ShapedArray]	_out_avalcore.ShapedArrayc          	         ~	|d         j         |d         j         }}|j         t          | |||           t          |          dz
  dk    }t          |          }t	          ||||          \  }}}t          | ||||          \  } }}}|d         }|^ }}}t          d |D                       }t          d |D                       }||k    o|dk    }t          ||||||
| j        j	                   d t          ||          D             }|d         }|rt          |||          }n7t          |dd         |||          }|d	k    rt          | ||          \  } }}|}|d
k    rtt          d t          |dd         |          D                       rEt          j        t          j        dt          j                  t%          j                            S |rat)          |          |||z  fz   }t          j                            | t          j        |t%          j        |                    |||          }n|rt          j        |ddg          }t          j        |d          }|rt)          fd|D                       dz    nt)          fd|D                        t)           fddD                        t          j                            | |t%          j                   ||          }n$t          j                            | ||||          }t          j        |d          }|r|dddddddf         }t9          |          }t          j        ||          }|S )z;Implementation of lax.conv_general_dilated_p using XlaConv.r   rJ   rL   c              3  "   K   | ]
}|d k    V  dS rJ   Nr,   r1   ds     r   r4   z(_conv_general_dilated.<locals>.<genexpr>  s&      22Q!V222222r   c              3  "   K   | ]
}|d k    V  dS r   r,   r   s     r   r4   z(_conv_general_dilated.<locals>.<genexpr>  s&      //Q!q&//////r   c                *    g | ]\  }}|d z
  |z  d z   S rI   r,   )r1   r   rs      r   
<listcomp>z)_conv_general_dilated.<locals>.<listcomp>  s5       !Qq1ukAo  r   rH   rZ   rY   c              3  (   K   | ]\  }}||k     V  d S r'   r,   )r1   lr   s      r   r4   z(_conv_general_dilated.<locals>.<genexpr>,  s*      #]#]daAE#]#]#]#]#]#]r   dtype)inputfilterstridesr`   	dilations)r   rJ   rH   rL   c              3  (   K   | ]}|         V  d S r'   r,   r1   r2   	out_shapes     r   r4   z(_conv_general_dilated.<locals>.<genexpr>H  '      ==A9Q<======r   rI   c              3  (   K   | ]}|         V  d S r'   r,   r   s     r   r4   z(_conv_general_dilated.<locals>.<genexpr>J  r   r   c              3  (   K   | ]}|         V  d S r'   r,   )r1   r2   tf_out_shapes     r   r4   z(_conv_general_dilated.<locals>.<genexpr>L  s'      ??Qa??????r   rK   )r   filtersoutput_shaper   r`   )r   r   r   r`   r   )r   rH   rJ   rL   N)ro   r   r7   r   r   rV   anyr   r   as_numpy_dtyperp   r   rc   rv   rA   broadcast_toconstantfloat32r   _eval_shaper5   nndepthwise_conv2dreshapereverserB   conv2d_transposeconv2dr9   )!rP   rQ   r_   r`   r~   r   rR   r   r   r   r   r   r   rE   rF   r   tf_window_stridesin_channelsrhs_spatial_shapesrU   rhs_out_channelr   r   r   rhs_dilated_shapeoutput_permpadding_typenew_rhs_shapeoutputrhs_tinverse_permr   r   s!                                  @@r   _conv_general_dilatedr      s(    "1+Yq\-?Y)o)sIsI>>>)nnq A%)/??(H|\9)6 )6%'< $:#y:=y:K$M $M #y#y "+,5)q/22\22222,//,/////) 33O8Ka8O,,	<-/@0#)2JL L L "%&8,"G"G   "!$+ 	2L'3 3LL #!n'B BL z!! 7Y P Pc9glV#]#]c)AaC.J[6\6\#]#]#] ] ] ?2;q
;;;!-i88: : :  '  ,--1@K1O1Q QMU##z#v1-@@AA! $    FF   JsQF##EL--E  >=========Dll=========l????,?????LU##'55 $  FF U\\!     F <--&  AAAqqq!!!QJF %[11,<--&	-r   c                  ~~t          j        | |d         ||d         |          \  } }}|\  \  }}	\  }
}t          | j                  t          |j                  }}|
|cxk    r.t	          t          t          |
                              k    rn n||z
  dv rd|t          |
          z
  cxk    rdk    rwn nsd|t          |          z
  cxk    rdk    rUn nQ|t          | j                  dz
  fk    r4|	t          |
          fk    rg }|t          |
          z
  dk    rBt          j        | |dz
            } |                    t          | j                  dz
             |t          |          z
  dk    r?t          j        ||          }|                    t          |j                  dz
             t          j	        
                    | |          t          |          dk    r2t          fd|D                       sJ t          j        |           |          S t          t          j                  fd| j        D             }fd|j        D             }|dd         }|dd         }t!          ||	          D ](\  }}t#                    }|||<   |||<   d||<   d||<   )g }t!          |
|          D ]=\  }}t#                    }|||<   |||<   d||<   d||<   |                    |           >d	 }t%          t'          |||z   |z                       }| j        |j        k    sJ d
                    d                    |          d                    |          d                    |                    } |t          j	                            || |                    S )zAImplementation of lax.dot_general_p in terms of tf.linalg.einsum.r   rJ   )r   r   rJ   rL   c              3  :   K   | ]}j         |         d k    V  dS r   ro   )r1   r2   results     r   r4   z_dot_general.<locals>.<genexpr>  s.      <<!aA%<<<<<<r   c                .    g | ]}t                    S r,   nextr1   rU   new_ids     r   r   z _dot_general.<locals>.<listcomp>      2221$v,,222r   c                .    g | ]}t                    S r,   r   r   s     r   r   z _dot_general.<locals>.<listcomp>  r   r   Nc                
    | d uS r'   r,   )r:   s    r   r!   z_dot_general.<locals>.<lambda>  s
    q} r   z	{},{}->{}r   )r   $_dot_general_convert_to_common_dtyper7   ro   r5   r6   rA   expand_dimsappendlinalgmatmulallsqueezeiterstringascii_lettersrp   r   r\   r   r   formatjoineinsum)rP   rQ   rR   r   r   r   r   convert_resultlhs_contractingrhs_contracting	lhs_batch	rhs_batchlhs_ndimrhs_ndimsqueeze_idxslhs_axis_idsrhs_axis_idslhs_out_axis_idsrhs_out_axis_idslhs_axisrhs_axis	shared_id	batch_idsnot_noneout_axis_idsspecr   r   s                             @@r   _dot_generalr  l  s    #H1sIaL)5 5#sN @Q<$?O&<y)39~~s39~~H( 9<<<<eC	NN&;&; < <<<<<<Z''8c)nn$)))))))))8c)nn$)))))))))#ci..1,...#i..***& L#i.. A%%N31--c#ci..1,---#i.. A%%N3))c#ci..1,---Yc3''F
<A<<<<|<<<<<<<<z&,//f>&!!!$%%&2222	222,2222	222,!!!!_!!!!_AA & &hVI&L&L!%X!%X)	955    hVI&L&L!%X!%XY$$(Xy#336FFGGI I,	ci							BGGL11277<3H3HGGL11
3 
3$		((sC88	9	99r   c                   g }|dz   }g }t          t          ||                    D ]\  }\  }\  }	}	}
|
dz   }|                    ||z  |
z
             t          j        |          |z  }d gdt          |          z   z  }t          d d d           ||<   |                    t          j        ||         |                     t          j        |t          |                    }t          j	        || |          }t          j	        |t          j
        | t          j                  |          }t          j        |||          S )NrI   rJ   axisr   )	enumeraterp   r   rA   r6   r7   slicer   concat
scatter_nd	ones_likerM   bool_where)operandpadding_valuepadding_configoperand_shapeindices_by_dimindices_shaper   r   dszrU   r2   dilation_factorindices	expansionindices_cartesian	scatteredmasks                    r   _interior_paddingr    sI    .$&-,&s=.'I'IJJ N Na	#y1a!eOo-1222hsmmo-G!c-0001ItT**IaL"/')*<mLLMMMMiS5G5GHHHm-wEE)	(",wbh*O*O*O#
% 
%$	$	=	1	11r   c          	        t          d |D                       r/t          | ||t          j        |d         j                            } d |D             }t          j        | |d|          } t          d |D                       r;t          j        |j                  }d |D             }t          j        | ||          } | S )Nc              3  *   K   | ]\  }}}|d k    V  dS r   Nr,   )r1   rU   r2   s      r   r4   z_pad.<locals>.<genexpr>  s,      ..GAq!a......r   r   c                >    g | ]\  }}}|d k    r|nd |d k    r|nd fS r   r,   r1   lohirU   s       r   r   z_pad.<locals>.<listcomp>  sK     ; ; ;'b"a #%''BBq"''BBqJ ; ; ;r   CONSTANT)modeconstant_valuesc              3  6   K   | ]\  }}}|d k     p|d k     V  dS r"  r,   r%  s       r   r4   z_pad.<locals>.<genexpr>  s5      ::ib"aa	26::::::r   c                ,    g | ]\  }}}|d k     r| nd S r$  r,   )r1   r&  rU   s      r   r   z_pad.<locals>.<listcomp>  s,    DDDQb1ffss!DDDr   )r   r  r   r   ro   rA   rn   r  )r  r  r  r   r   non_negative_paddingr   beginss           r   _padr/    s     	..~..... H & 29Q<3E F FH HG; ;+9; ; ;F#	% % %' 	::>::::: 6%io66LDD^DDDFhw55G	.r   is_minboolr  axesSequence[int]index_dtypeDTypec                &   |\  }t           j        }t          j        |          j        dk    rt           j        }| rt           j        j        nt           j        j        } ||||          }	t          j	        |	t          j        |                    S )N    )r
  output_type)rA   int32r   iinfobitsint64mathargminargmaxcastr   _to_tf_dtype)
r0  r  r2  r4  r   r   r
  r8  fnr   s
             r   
_argminmaxrC    sz     %$+\+#b(((K3rw~~RW^"2gDk:::&	,[99	:	::r   TFc                   |dvrt          d          |dv rM|t          j        t          j        t          j        t          j        t          j        fv rt          d|           |dk    r,|t          j        t          j        fv rt          d|           |dk    rX|t          j	        t          j
        t          j        t          j        t          j        t          j        fvrt          d|           t          |           t          |          cxk    r't          |          cxk    rt          |          k    rn nt          d	          d
}t          |           dk    rt          d          t          |           dk    rDd}d|fd|fd|ffD ]6\  }}	|	d         |	d         cxk    rdk    rn !t          d| d|	           7t!          |          dgt          |           z  k    rt          d          |S )Nminrz   add5Reduction function should be either min, max, or add.)rF  rz   z/Min/max pool does not support operands of type rF  z+Min pool does not support operands of type rG  z.Add pooling does not support operands of type zgInput shapes, window dimensions, window stride dimensions, and window dilation dimensions should match.T   z"Only 1D or 2D input are supported.rL   Fwindow_dimensionsr_   window_dilationr   r   rJ   z,Only 1D or 2D input are supported, expected z$=(1, spatial_dims, ..., 1), but got z(Unimplemented support for base dilation.)_reduce_errorrA   r1  uint32uint64	complex64
complex128uint8uint16bfloat16float16r   float64int16r9  r7   r\   )
r  computation_namer   rJ  r_   base_dilationrK  has_only_spatial_dimsr*   values
             r   _validate_reduce_window_inputsr[    s    222
O
P
PP''Egry")R\2=6 - -  # # # $ $ $5RXry,A#A#A MeMM
N
NN5kjjjhh1 $ $  # # # $ $ $ 
-C 122    c.6I6I    	/    
 ! " " " !
<
=
==!!,.?@)>:*O<> ( (e 
qU2Y	#	#	#	#!	#	#	#	#	# '#' '$' ' ( ( 	( 
$
 
-QC#m"4"4444 B
C
CC	r   c                    t          ||||          }|dk    o|dk    o|dgt          |          z  k    }|s|dk    rt          | ||          \  } }d}| ||fS )NrY   rG  rJ   rZ   rX   )rc   r7   rs   )r  r  rW  rJ  r_   r`   r   needs_manual_paddings           r   _padding_reduce_windowr^  M  s     0A!/: :,
 f 4!1U!: 4A3]!3!333   \Z77.wwOOG]L	-	--r   c                   |r0t          j        |          }t          j        | d|z   dz             } n|dd         }|dd         }|dd         }| |||fS )NrI   rJ   r   )r   r   rA   r   )r  r  rJ  r_   rK  rY  s         r   _reshape_reduce_windowr`  ^  sx    
  , &}55Mj$"6"=>>GG
 *!B$/#AbD)N%ad+O	#^_	DDr   c	           	        | j         |d         j        }	t          |	||          t          | |	|          \  } }	t	          | |	|          \  } fd}
fd}dk    r |
| d          S dk    r | |
 ||           d                    S dk    r1t          j         |
| d	          t          j                            S d S )
Nr   )rY  c                   t          d 	
fD                       rt          d	d
d          | j        t          j        t          j        fv r.dk    r(| j        }t          j        | t          j                  } nd }t          j        	                    | 	|
          }|rt          j        ||          }rt          j
        |dd	g          }t          j        |j                   |S )
Nc              3  @   K   | ]}t          j        |           V  d S r'   )r	   is_constant_shape)r1   r   s     r   r4   z2_reduce_monoid.<locals>.tf_pool.<locals>.<genexpr>  s@       ; ;Qt%a((( ; ; ; ; ; ;r   u<   TODO: use tf.nn.pool with dynamic shapes¨window_dimensions=z  window_strides=z dilations=rG  r   )r^   pooling_typer`   r   r   r   r   )r   r   r   rA   rV  r9  r@  r   r   poolr   r   rO   ro   )inputsre  original_dtyper   r   rW  r   rY  r   rJ  r_   s       r   tf_poolz_reduce_monoid.<locals>.tf_pool  s@   
 ; ;~y9; ; ; ; ; .-7H - -- - )- -. . .
 	28,,,2Be2K2K|nwvRZ000ffnUZZ&!   F  5wv^444f + z&1b'**f
*69?CCCMr   c                T    t          j        | t          j        d                    S )Nr   )rA   multiplyr   )r:   r   s    r   r!   z _reduce_monoid.<locals>.<lambda>  s    R[BKE$:$:;; r   rz   MAXrF  rG  AVG)	r   ro   r[  r^  r`  rA   rk  r=  prod)r  rJ  r_   r`   rX  rK  rW  r   r   r  ri  negater   r   rY  r   s    ``   ` `   @@@@r   _reduce_monoidrp  t  sr    -% A,$- 9%u.?_& & *@}.0Ag* *&'=, ;Q1;3 ;3 ;37'ni          > <;;;&77E"""5  6''&&//5112225   ;www..	:K0L0LMMM	 ! r   tuple[core.ShapedArray, ...]tuple[TfVal, ...]c        	           t          |          dk    s
J d            t          j        |	t          |	          dz  g          \  }
}t          |
          dk    st          |          dk    rt          d          |
d         |d         }}t          | j                  dk    s_t          | j        d         j                  dk    s<t          | j        d         j                  dk    s| j        d         j        j        dvrt          d          | j        d         j        j        }t          ||||||||d         f|d         	  	        }t          j        t          j        t          j        d|         } |||          }|fS )	Nr   z+Reduction computation cannot have constantsrL   rJ   z.jax2tf does not support variadic reduce_windowrE  rH  )rJ  r_   r`   rX  rK  rW  r   r   )r7   r   
split_listrL  eqnsinvarsoutvars	primitiver*   rp  rA   minimummaximumrG  )jaxprconstsrJ  r_   r`   rX  rK  r   r   argsoperandsinit_valuesr  
init_valuerW  r   	reduce_fns                    r   _reduce_windowr    s   
 
V			H			/$Ta0@AA(K]]a3{++q00
H
I
II [^:'	%*oo	%*Q-
1$$	%*Q-
  A%%jm"*???
O
P
PPZ],1',=)7")(5*9+;%.q\O$-aL2 2 2& ZZV  	)
 9VZ((& r   rF  )rW  rz   rG  reduceselect_and_scatter_addrng_bit_generatormax_indicesSequence[TfVal]start_indicesslice_sizesc                    t          j        t          j        | |          t           j                  }t          j        t          j        |t           j                  d|          S )a  Simulates XLA clipping behavior with TF ops.

  Various TF ops have different clipping behavior than XLA:
  * If `start_indices` is out-of-bounds, then TF fails but XLA clips the indices
  to
    [0, max_len].
  * If `start_indices + slice_size` is out-of-bounds, then TF fails, but XLA
  adjust
    `start_indices` so that a full slice is returned.
  This function clips the start indices correctly.
  r   r   )rA   r@  subtractr9  clip_by_value)r  r  r  	max_starts       r   _clipr    sL      gbk+{;;28LLL)		"'-rx@@@!Y	O	OOr   c                  x    e Zd ZU ded<   ded<   ded<   ded<   ded<   ded	<   d
ed<   d Zd Zed             ZdS )
GatherArgsr;   r  r  zlax.GatherDimensionNumbersdnumsr  r=   op_shapestart_indices_shaper   out_avalc                ^    t          | j                  t          | j                  k    sJ d S r'   )r7   r  r  selfs    r   __post_init__zGatherArgs.__post_init__  s.    t}T%5!6!6666666r   c                F    d| j          d| j         d| j         d| j         S )Nzoperand shape=z, start_indices=z, dimension_numbes=z, slice_sizes=)r  r  r  r  r  s    r   __repr__zGatherArgs.__repr__  sK    .T] . .!/. . $
. .  +. . /r   c                     t           fdt          t           j        j                            D                       S )Nc              3  8   K   | ]}|j         j        v|V  d S r'   )r  offset_dims)r1   r:   r  s     r   r4   z(GatherArgs.batch_dims.<locals>.<genexpr>  s>       4 4qDJ222 22224 4r   )r5   r6   r7   r  ro   r  s   `r   
batch_dimszGatherArgs.batch_dims  sO     4 4 4 4E#dm&9":":;; 4 4 4 4 4 4r   N)__name__
__module____qualname____annotations__r  r  propertyr  r,   r   r   r  r  	  s         ...####!!!!7 7 7/ / /
 4 4 84 4 4r   r  precondition_fnCallable[[GatherArgs], None]c                     d fd}|S )a   Decorator for specifying a precondition function.

  This decorator should be put on a function with argument `arg` of type
  `GatherArgs`. It will first call `precondition_fn` with `arg` (which may throw
  an exception), and then call the function it is decorating with `arg` as well.
  	gather_fnCallable[[GatherArgs], Any]c                B     t                     d fd            }|S )Nr}  r  c                0     |             |           S r'   r,   )r}  r  r  s    r   wrapperz7gather_precondition.<locals>.decorator.<locals>.wrapper*  s#     odYt__r   r}  r  )r   )r  r  r  s   ` r   	decoratorz&gather_precondition.<locals>.decorator(  sA    
9      
 Nr   )r  r  r,   )r  r  s   ` r   gather_preconditionr     s)          
r   r}  c                T    t          | j                  dk    rt          d          dS )zReturns True if this call to gather represents scalar indexing into arrays.

  E.g., op[2], op[:, :5, :], jnp.take(op, 0, axis=0).
  rJ   zstart_indices shape should be 1N)r7   r  rx   r}  s    r   _pre_gather_for_scalar_indexingr  5  s1     		!""a''
6
7
77 ('r   c                   t          j        | j        j        d          }t	          j        | j                  }t	          j        | j                  }t          j        || j	        t          |          g          }t          |||          }||z   }t          d | j        j        D                       }t          j        | j        |||          }t	          j        |t	          j        | j                            }|S )zImplements 'scalar indexing into arrays' cases of lax.gather using tf.slice.

  E.g., op[2], op[:, :5, :], jnp.take(op, 0, axis=0).
  rJ   c              3      K   | ]	}d |z  V  
dS )rL   Nr,   r1   r:   s     r   r4   z._gather_for_scalar_indexing.<locals>.<genexpr>W  s&      BBQAqDBBBBBBr   )shrink_axis_mask)rA   r   r  start_index_mapr   r   r  r  r  r  r7   r  sumcollapsed_slice_dimsstrided_slicer  _ensure_tf_shape_if_dynamic_aval_to_tf_shaper  )r}  r  r  slice_sizes_tfr   r   shrink_maskress           r   _gather_for_scalar_indexingr  @  s     N4:5q99' ..(%d&677. -!3c(mm_
E
E%
%
0
0%# BB$*"ABBBBB+
ucKPPP#*	6#DM22	 	# 
*r   c                ^   | j         }| j        j        }| j        j        }| j        j        }t          |          dk    r[t          |          dk    rHt          |          dk    r5|d         |d         k    r#t          |          t          |          dz
  k    st          d          t          j        | j	        d         d          st          d          |d         }t          | j	                  dz
  }t          t          t          |                    t          t          ||z   t          |          |z   dz
                      z             }||k    rt          d          |d|         dz   ||dz   d         z   }t          j        | j        |          st          d	          dS )
zReturns True if this call to gather represents multi-dimensional indexing.

  E.g., jnp.take(op, [[0], [1]], axis=0).
  Note we currently only support multi-dimensional indexing if the last
  dimension is 1.
  rJ   r   zunsupported dimension numbersr   z#start_indices shape[-1] should be 1zunsupported offset_dimsNrI   zunsupported slice_sizes)r  r  r  r  r  r7   rx   r	   definitely_equalr  r5   r\   r6   definitely_equal_shaper  )	r}  r  r  r  r  r
  
index_dimsexpected_offset_dimsexpected_slice_sizess	            r   !_pre_gather_for_multidim_indexingr  `  s     ](J./8
&+
h--1

_!5!5!:!:
"
#
#q
(
(-A!-DQ.  . $'$4$4H8I$I$I
4
5
55		t7;Q	?	? <
:
;
;;	a	 $4+,,q0*
5;;
5
"X+a/1 1 2 223 3 (((
.
/
//!%4%4/(4!8992EE		$T%57K	L	L 0
.
/
//0 0r   c                    | j         j        d         }t          j        | j        d          }t          j        | j                  }t          ||         f|d          }t          j	        | j
        ||d          S )zImplements 'multi-dimensional indexing into arrays' cases of lax.gather using tf.gather.

  E.g., jnp.take(op, [[0], [1]], axis=0).
  r   r   rI   )r
  r  )r  r  rA   r   r  r   r   r  r  gatherr  )r}  r
  squeezed_indicesr  r  s        r   _gather_for_multidim_indexingr    sn     
	(	+$Z 2B77..($)+;TBB-	4<Ta	H	H	HHr   c                |   t          | j                  dk    r%t          dt          | j                   d          | j        j        t          t          | j        d                             k    rt          d          t          j	        | j
        d         | j        d                   st          d          dS )	zReturns True if this call to gather has non-empty batch dimensions.

  This is for instance triggered when doing jax.vmap(lax.dynamic_slice).
  rJ   zbatch_dims is z but should be 1r   zunsupported start_index_mapr   z9Batch dimensions in operand and start_indices don't agreeN)r7   r  rx   r  r  r5   r6   r  r	   r  r  r  s    r   _pre_gather_with_batch_dimr    s     	Q
Lc$/&:&:LLL
M
MM 
Z5t/G/K)L)L#M#MMM
2
3
33 
	t}Q/1I!1L	M	M 
     r   c                    t          | j        j                  dk    rt          d          t          | j                  dvr%t          dt          | j                   d          dS )zReturns True if this call to gather has non-empty 2D batch dimensions.

  This is for instance triggered when doing
  jax.vmap(jax.vmap(lax.dynamic_slice)).
  r   z0only len(collapsed_slice_dims) == 0 is supported)rJ   rL   rH   zSize of batch_dims is z but should be up to 3N)r7   r  r  rx   r  r  s    r   _pre_gather_with_batch_dimsr    sv     		())Q.. G
H
HH
 	**
MT_!5!5MMM   +*r   c                >    t          j         j                  }t          | j         j                  }t          j         fd|t          j         j	        j
                            }t          j        |t          j         j        j                            }|S )zoImplements call to gather with non-empty batch dimensions.

  E.g., when doing `jax.vmap(lax.dynamic_slice).
  c                F    t          j        j        | j                  S )N)r   size)rA   r  r  r  )idxsr}  s    r   r!   z(_gather_with_batch_dim.<locals>.<lambda>  s    $,d9IJJJ r   )fn_output_signature)r   r   r  r  r  r  rA   map_fnrA  r  r   r   r  ro   )r}  r  r  r   s   `   r   _gather_with_batch_dimr    s     ..($"4d6FGG-9JJJJ+DL,>??  &
 :ff01DEEFF&	-r   ro   tuple[int, ...]c           	         t          j        t          j        t          j        d | D             ddid          dt	          |           f          S )a  
  Returns the indices of the according to `shape`:
    each element in the output is the index of an element of an array
    of the provided shape. The result's shape is (math.prod(shape), len(shape))

  For example, given shape (2,2) it returns (0,0),(0,1),(1,0),(1,1)
  c                :    g | ]}t          j        d |          S )r   startlimit)rA   r6   r  s     r   r   z,_gather_generate_indices.<locals>.<listcomp>  s'    :::qq***:::r   indexingijr   r	  )rA   r   stackmeshgridr7   r   s    r   _gather_generate_indicesr    si     
h
+::E:::EI  	   
3u::
 
 r   c                   t          j        | j                  }t          j        | j        j                  t          j        | j        j        d          }t          t          fd| j        D                                 }t          j        |j                  d         }t          t          fd| j        j        D                                 }t          j        |j                  d         }| j        | j        j        z   }t          fd|D                       }d }	t          j        | j        |          }
 |	||t          | j        j                            }t          j        ||
|t          |          g          }t#          ||| j                  }t          j        t          j        ||d          t          j        ||df                    }t          j        | j        |          }t          j        ||          }t          j        |t
          j                            |          	          S )
z=Implements call to gather with non-empty 2D batch dimensions.rJ   c              3  (   K   | ]}|         V  d S r'   r,   r1   r2   r   s     r   r4   z*_gather_with_batch_dims.<locals>.<genexpr>  s'      55LO555555r   r   c              3  (   K   | ]}|         V  d S r'   r,   r  s     r   r4   z*_gather_with_batch_dims.<locals>.<genexpr>  s'      <<LO<<<<<<r   c              3  (   K   | ]}|         V  d S r'   r,   )r1   r:   r   s     r   r4   z*_gather_with_batch_dims.<locals>.<genexpr>  s'      >>LO>>>>>>r   c                
   t          j        t          j        | d          |ddg          }t          j        t          j        d|          |          }t          j        |||df          }t          j        ||gd          S )zGGenerate the start indices of each slice, which index into the operand.r   rJ   r  r   r	  )rA   tiler   repeatr6   r   r  )r  batch_indices_sizesize_of_index_maptiled_indicestemp_batch_indicess        r   get_scatter_indicesz4_gather_with_batch_dims.<locals>.get_scatter_indices  s     G
w""%7A$> M
 
q 23335F  /1BAF  9(-8rBBBBr   r	  r   r8   )r   r   r  r  ro   rA   r   r  r  r  r5   r  r  	gather_ndr  r7   r  r  r  rG  r  r  r  r   rB   r=  invert_permutation)r}  r  r  batch_indicesr  offset_indicesoffset_indices_sizedim_maskmask_output_shaper  slice_start_indicesscatter_indicesindices_in_operandclipped_start_indicesslice_element_indicesresultstempr   s                    @r   _gather_with_batch_dimsr    s8    ..(#DM$788,N4:5q99' +5555T_55555 - )-*=>>qA ,<<<<TZ%;<<<<< . *>+?@@C _tz55(>>>>X>>>>>C C C$ T%7GG''!3tz'A#B#B / },/A3x==.Q   *<d>NOO
 &i%':CCCgn11566  L'<==' 
G#4	5	5	5$	d!;!;H!E!E	F	F	FFr   c               
   |t           j        j        k    r:t          j        t
          j        d          }
 |
| |||||||	j        ||	
  
        S t          | ||||d         j        |d         j        |	          }g }t          t          t          t          fD ]@}	  ||          c S # t          $ r$}|                    | d|           Y d}~9d}~ww xY wd	| d
d                    |          z   }t!          d|          )z$Tensorflow implementation of gather.F)multiple_results)rR   r  unique_indicesindices_are_sorted
fill_valuer   r   r   r   rJ   )r  r  r  r  r  r  r  z: Nz"Unsupported arguments for gather: z
, errors:

r  )r
   GatherScatterModeFILL_OR_DROPr   _convert_jax_impllax_slicing_gather_fillro   r  r  r  r  r  rx   r   r   r   )r  r  rR   r  r   r  r)  r  r   r   gather_fill_fngather_argserrorsr  e	error_msgs                   r   _gatherr  1  sp   
 
S"///-k.F?DF F FN>2C-*_	Y	P P P P !|!#A,,  + & "#	 	+ 	+i+Y{##### + + +mmy))A))********+ MKLLLyy  !) 	x###s   
B((
C2CCc                   t          j        |          }t          j        |          }t          j        |d         j                  }t          |||          }t          j        | ||          S )Nr   )r  )rA   r  r   r   ro   r  r  )r  r  r   r   r  r  r  s          r   _dynamic_slicer  `  sb     (=))-%k22.$Yq\%788-}nEE-	'=~	>	>	>>r   c               R   t          j        |          }t          j        |d         j                  }t          j        |           }t          j        |d         j                  }t          |||          }t          j        ||          }t          j        t          j	        |          |          }	t          j
        |	||          }
t          j        t           j                            |
          d          }t           j                            |          }t          j        |||f          }t          j        ||          }t          j        |t           j                  }t          j        |||f          }t          j        ||          }t          j        |||           S )Nr   rJ   r   r   )rA   r  r   r   ro   r  r  rG  r   r6   r  r   nestflattenr  r  r1  r  )r  updater   r   r  r  op_sizeupdate_shape_tfend_indices	id_tensorscattered_indicesflat_indicesflat_updateupdate_masks                 r   _dynamic_update_slicer  n  sS    (=))-	! 233(GG'&y|'9::/-AA-}o66+ j'**H55)&y-MM 0A B BBGG,''+={WJ??&:fh''& [888+lK'DD+
;11+ 
+vw	/	//r   inverseforwardc                    t          fdt          t          | j                            D                       }|r|z   n|z   }|s|nt	          |          }t          j        | |          S )z1Shifts the tuple of axes to the front of an arrayc              3  $   K   | ]
}|v|V  d S r'   r,   )r1   r2   r2  s     r   r4   z%shift_axes_forward.<locals>.<genexpr>  s'      KK1Qd]]Q]]]]KKr   )r5   r6   r7   ro   r9   rA   rB   )r  r2  r  r  
other_axes	fwd_orderorders    `     r   shift_axes_forwardr$    s{    
 KKKKc'-&8&8 9 9KKKKK*#*AdZ
T0A)"
F))(;I(F(F%	gu	%	%%r   c                &     d
 fddfd	}|S )Nr   r   r   r   c                   |pt          |j                  dk    }|r`t          j        | |          } ||          }t          |j                  dk    r|d         }|d         }t          j        | ||          }	nZ|j        d         dk    r:r8 |t          j        |d          | j        d                   }
 | |
          }	nt          d          |	S )av  Implementation of scatter specialised to indexing from the front axes.

    This covers unique indices and non-unique indices of single depth.
    Note on unique indices: `tf.tensor_scatter_nd_update` interprets indices
    thusly: every axis except the final one encodes a batch dimension, the final
    axis encoding the actual indices to scatter in to. It enforces, at least
    one, batch dimension so we add an empty dimension to indices and updates if
    lacking.

    Note on non-unique indices: There is no tf op for non-single depth indexing,
    but if indexing is single depth, this can be viewed as a segment op.
    rJ   Nr   r   zgScatter only supports non-unique indices with indexing into only one dimension for (add, mul, min, max))r7   ro   rA   r  tensor_scatter_nd_updater   _scatter_error)r  r  updatesr  r)  r   r   
suboperandupdated_suboperandyoperand_updateunsorted_segment_op	update_ops              r   _sparse_scatterz2convert_scatter_jax_to_tf.<locals>._sparse_scatter  s     $HO,A(B(Ba(GN <99j$9Z99	_"	#	#q	(	()$//5

%g@R
S
Saa


#q
(
(.A
(,,W-/Z-L-L-4]1-=? ? Ig~..  	 Hr   r   r1  r  c                   ~~~|j         }|j        }|j        }| j        }|t          j        t          j        fv rt          d|           ||k    rt          d          |t          j	        j
        k    r$|t          j	        j        k    rt          d          t          t          |          }t          |d          }t          ||d          } |  ||           |||||	|
                    S )	a)  
    Wrapper around the scatter function.
    The underlying tf ops `tf.tensor_scatter_nd_update` and
    `tf.math.unsorted_segment_*` index from the front dimensions.
    `tf.math.unsorted_segment_*` indexes to a depth 1 from the front.
    `tf.tensor_scatter_nd_update` indexes from the front dimensions onwards,
    with no ability to skip a dimension. This function shifts the axes to be
    indexed to the front then calls a front-specific implementation, then
    inverse-shifts the output.

    scatter_dims_to_operand_dims: dimensions which the scatter indexes in to.
      We shift these to the front to match tf syntax. All other dims are batch
    update_window_dims: dimensions which are not batch dimensions. We shift
      these to the back as the remaining dimensions are batch dimensions.
    z*Scatter does not support operands of type z"Complex scatters are not supportedzHOnly scatter modes `FILL_OR_DROP` and `PROMISE_IN_BOUNDS` are supported.)r2  T)r  F)r2  r  )update_window_dimsinserted_window_dimsscatter_dims_to_operand_dimsr   rA   r1  rO  r(  r
   r  r  PROMISE_IN_BOUNDSr   r$  )r  r  r)  update_jaxprupdate_constsrR   r   r  r)  r   r   r2  r3  scatter_to_operand_dimsr   fwdinvupdates_shiftedr0  s                     r   sparse_scatterz1convert_scatter_jax_to_tf.<locals>.sparse_scatter  s7   ( 	m%7*=,A/LME",'''OOOPPP666?@@@%222%777  @ A A A $+B
C
C
CC
#t
$
$
$C )(%9 9 9O 3CLL/?N)Y	( 	() ) )r   r   r   r   r   )r   r1  r  r1  r   r   r   r   r,   )r/  r.  r<  r0  s   `` @r   convert_scatter_jax_to_tfr>    sP    % % % % % % %N7) 7) 7) 7) 7) 7)p 
r   c                    |S r'   r,   )r:   r,  s     r   r!   r!     s     r   sortreduce_precision)r   )r   r   r   r   r   r   )r:   r;   r<   r=   r   r>   )rE   r=   rF   r=   )r   r   )rP   r;   rE   r=   rQ   r;   rF   r=   )rR   r   r   r{   r   r{   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r=  )r0  r1  r  r;   r2  r3  r4  r5  r   r   r   r   )r   r   r   rq  r   rr  )r  r  r  r  r  r  )r  r  r  )ro   r  )r  r=   r   r   r   r   )FT)r2  r  r  r1  r  r1  r'   )m__doc__
__future__r   ry   collections.abcr   r   dataclasses	functoolsr   r   r=  r   typingr   jax._srcr	   jaxr
   jax._src.laxr   r  r   r   jax.experimental.jax2tfr   numpyrM   
tensorflowrA   r   r  r;   r5  PrecisionTyper   r   rL  r(  r-   r9   rD   rV   rc   rs   rv   r   r   r   r   r   r   conv_general_dilated_pr  dot_general_pr  r/  pad_prC  argmin_pargmax_pr[  r^  r`  rp  r  reduce_window_min_preduce_window_max_preduce_window_sum_preduce_window_preduce_pselect_and_scatter_add_prng_bit_generator_pr  	dataclassr  r  r  r  r  r  r  r  r  r  r  r  gather_pr  dynamic_slice_pr  dynamic_update_slice_pr$  r>  	scatter_prG  unsorted_segment_sumscatter_add_prk  unsorted_segment_prodscatter_mul_pry  unsorted_segment_minscatter_min_prz  unsorted_segment_maxscatter_max_psort_preduce_precision_pr,   r   r   <module>rj     s+   C B B " " " " " "  . . . . . . . .     $ $ $ $ $ $ $ $                     / / / / / /             * * * * * *         <> = = = = 	" " " " " >=88% %  8 8 8S S S S( ( ( (D     	 	 	!) !) !)F% % % %
- 
- 
-
 
 
J J J.k k k k\ .Cs) *Y: Y: Y: Y:x %1s  !2 2 2<   0 !sy ; ; ; ;  'wz488s| &wz599s| 4 4 4n. . ."E E E,CN CN CN CNL' ' ' 'V GNU333 s& ' GNU333 s& ' GNU333 s& ' '5s" #-~h77s| /=~0 0s+ , +9.9L*M*Ms& 'P P P P( 4 4 4 4 4 4 4 4,   *8 8 8 8 455   65>&0 &0 &0 &0R 677
I 
I 
I 87
I   ,   & /00   10    & 011JG JG JG 21JGX)$ )$ )$ )$X  's| ? ? ? ? '5s" #0 0 0 0> .Cs) *
 (-'+& & & & &a a a aH !: 9N! !s} $=$=bf27Kg$h$hs  !$=$=bk27Kh$i$is  !$=$=bj27Kg$h$hs  !$=$=bj27Kg$h$hs  !+^F33sz )78J)K)Ks% & & &r   