
    uki26                    t   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lmZ d dlmZ d d	l	mZ d d
lmZmZ d dlZeZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd ZddZedd       Zej4                  d        Zedd       Zej4                  d        Zy)    )annotations)SequenceN)Any)
custom_jvp)dtypes)lax)convolution)util)Array	ArrayLikec	                V   t        j                  |       }	t        |      }t        j                  |	j
                  d|z   |      }|\  }
}}t        j                  |      }|	j
                  |
d      }t        j                  |	j                  ||f      }t        j                  ||||fd      }t        j                  |||z  dg|      }t        j                  |d|d   |d   f      }t        j                  |	|||||||dn|t         j                  j                   f||
      }|S )	a
  Extract patches subject to the receptive field of `conv_general_dilated`.

  Runs the input through a convolution with given parameters. The kernel of the
  convolution is constructed such that the output channel dimension `"C"`
  contains flattened image patches, so instead a single `"C"` dimension
  represents, for example, three dimensions `"chw"` collapsed. The order of
  these dimensions is `"c" + ''.join(c for c in rhs_spec if c not in 'OI')`,
  where `rhs_spec == dimension_numbers[1]`, and the size of this `"C"`
  dimension is therefore the size of each patch, i.e.
  `np.prod(filter_shape) * lhs.shape[lhs_spec.index('C')]`, where
  `lhs_spec == dimension_numbers[0]`.

  Docstring below adapted from `jax.lax.conv_general_dilated`.

  See Also:
    https://www.openxla.org/xla/operation_semantics#conv_convolution

  Args:
    lhs: a rank `n+2` dimensional input array.
    filter_shape: a sequence of `n` integers, representing the receptive window
      spatial shape in the order as specified in
      `rhs_spec = dimension_numbers[1]`.
    window_strides: a sequence of `n` integers, representing the inter-window
      strides.
    padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of
      `n` `(low, high)` integer pairs that give the padding to apply before and
      after each spatial dimension.
    lhs_dilation: `None`, or a sequence of `n` integers, giving the
      dilation factor to apply in each spatial dimension of `lhs`. LHS dilation
      is also known as transposed convolution.
    rhs_dilation: `None`, or a sequence of `n` integers, giving the
      dilation factor to apply in each spatial dimension of `rhs`. RHS dilation
      is also known as atrous convolution.
    dimension_numbers: either `None`, or a 3-tuple
      `(lhs_spec, rhs_spec, out_spec)`, where each element is a string
      of length `n+2`. `None` defaults to `("NCHWD..., OIHWD..., NCHWD...")`.
    precision: Optional. Either ``None``, which means the default precision for
      the backend, or a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``).
    preferred_element_type: Optional. Either ``None``, which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    A rank `n+2` array containing the flattened image patches in the output
    channel (`"C"`) dimension. For example if
    `dimension_numbers = ("NcHW", "OIwh", "CNHW")`, the output has dimension
    numbers `"CNHW" = "{cwh}NHW"`, with the size of dimension `"C"` equal to
    the size of each patch
    (`np.prod(filter_shape) * lhs.shape[lhs_spec.index('C')]`).

     r   r   )shape)r      )r   r   r   N)
lhsrhswindow_stridespaddinglhs_dilationrhs_dilationdimension_numbers	precisionfeature_group_countpreferred_element_type)r   asarraytupler	   conv_dimension_numbersr   mathprod_eyedtypebroadcast_in_dimreshaper
   moveaxisconv_general_dilated	PrecisionDEFAULT)r   filter_shaper   r   r   r   r   r   r   	lhs_arraylhs_specrhs_specout_specspatial_size
n_channelsr   outs                    M/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/lax/other.pyconv_general_dilated_patchesr2      s1   ~ kk#)|$,!88oov,.?A "3(Hh<(,x{+* 	|(DE#S:|\"JFS#C*|3QFFG#c6HQK!#=>#((

#)!)	030E0E0G$3	# 
*    c	           
        t        j                  |       }	t        j                  |      }
|
d}n2t        |
t              rt        |
      dk(  r|
d   }nt        d|       t        |	|||||||      }t        j                  |	j                  dt	        |      z   |      \  }}}|d   g|d   g}}|dd |dd }t        t        t        |            fd	      D cg c]  }||   	 }}t              ||f|ff}t        j                  ||||
      }t        j                  |d|d   |d   f      }|S c c}w )aT  General n-dimensional unshared convolution operator with optional dilation.

  Also known as locally connected layer, the operation is equivalent to
  convolution with a separate (unshared) `rhs` kernel used at each output
  spatial location. Docstring below adapted from `jax.lax.conv_general_dilated`.

  See Also:
    https://www.openxla.org/xla/operation_semantics#conv_convolution

  Args:
    lhs: a rank `n+2` dimensional input array.
    rhs: a rank `n+2` dimensional array of kernel weights. Unlike in regular
      CNNs, its spatial coordinates (`H`, `W`, ...) correspond to output spatial
      locations, while input spatial locations are fused with the input channel
      locations in the single `I` dimension, in the order of
      `"C" + ''.join(c for c in rhs_spec if c not in 'OI')`, where
      `rhs_spec = dimension_numbers[1]`. For example, if `rhs_spec == "WHIO",
      the unfolded kernel shape is
      `"[output W][output H]{I[receptive window W][receptive window H]}O"`.
    window_strides: a sequence of `n` integers, representing the inter-window
      strides.
    padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of
      `n` `(low, high)` integer pairs that give the padding to apply before and
      after each spatial dimension.
    filter_shape: a sequence of `n` integers, representing the receptive window
      spatial shape in the order as specified in
      `rhs_spec = dimension_numbers[1]`.
    lhs_dilation: `None`, or a sequence of `n` integers, giving the
      dilation factor to apply in each spatial dimension of `lhs`. LHS dilation
      is also known as transposed convolution.
    rhs_dilation: `None`, or a sequence of `n` integers, giving the
      dilation factor to apply in each input spatial dimension of `rhs`.
      RHS dilation is also known as atrous convolution.
    dimension_numbers: either `None`, a `ConvDimensionNumbers` object, or
      a 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string
      of length `n+2`.
    precision: Optional. Either ``None``, which means the default precision for
      the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.

  Returns:
    An array containing the unshared convolution result.

  In the string case of `dimension_numbers`, each character identifies by
  position:

  - the batch dimensions in `lhs`, `rhs`, and the output with the character
    'N',
  - the feature dimensions in `lhs` and the output with the character 'C',
  - the input and output feature dimensions in rhs with the characters 'I'
    and 'O' respectively, and
  - spatial dimension correspondences between `lhs`, `rhs`, and the output using
    any distinct characters. The examples below use 'W' and 'H'.

  For example, to indicate dimension numbers consistent with the `conv` function
  with two spatial dimensions, one could use `('NCHW', 'OIHW', 'NCHW')`. As
  another example, to indicate dimension numbers consistent with the TensorFlow
  Conv2D operation, one could use `('NHWC', 'HWIO', 'NHWC')`. When using the
  latter form of convolution dimension specification, window strides are
  associated with spatial dimension character labels according to the order in
  which the labels appear in the `rhs_spec` string, so that `window_strides[0]`
  is matched with the dimension corresponding to the first character
  appearing in rhs_spec that is not `'I'` or `'O'`.

  If `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`
  (for a 2D convolution).
  Nr   r   z6Unsupported precision for conv_general_dilated_local: )r   r)   r   r   r   r   r   r   r   r   c                    |    S N )k
lhs_b_dimss    r1   <lambda>z,conv_general_dilated_local.<locals>.<lambda>   s    JqM r3   )key)r   r   ))r   r   canonicalize_precision
isinstancer   len
ValueErrorr2   r	   r   r   sortedrangedot_generalr
   r%   )r   r   r   r   r)   r   r   r   r   r*   c_precisionlhs_precisionpatchesr+   r,   r-   
lhs_c_dims
rhs_c_dims
rhs_b_dimsidnr0   r9   s                         @r1   conv_general_dilated_localrM   ~   sx   ^ kk#)**95+M+u%#k*:a*?NM

@LN N )
#)	' "-!C!Coovl 335F"H(Hh %QK=8A;-j*|*|*'-eC
O.D2I(K L!
1 L* Lj!*	Z :z":;"iP#c8hqk8A;%?@#	*Ls   !D<c                   t        j                  | |      }t        j                  | d|z        }t        j                  | d      }t        j                  t        j                  | |      |      }t        j                  t        j
                  ||      t        j                  ||      |      }t        j                  ||      S )zWraps `x` between `[-a, a]`.r   r   )r   _constremaddselectltsub)x_aatwo_azerorP   s         r1   _wrap_betweenrZ      s    	jjB!
**QB
%	Aq	$1u%#

366#t$cggc5&93?#	ar3   c                F   t        j                  | j                  t        j                        rt        j                  |       n| }t        j                  |t        d            }t        j                  t        j                  ||      t        j                  |       |       S )Ninf)r   
issubdtyper"   npcomplexfloatingr   realrO   floatrR   eq_zeros)rU   re_xr\   s      r1   _replace_infre      sd    ))!''23E3EF!A$

4u&#	CFF4%szz!}a	88r3   c                  t        j                  |       }t        j                  |      }|j                  |j                  k(  sJ t        j                  ||      }t	        j
                  |j                  d      rt        j                  ||      }t        j                  t        j                  |      t        j                  ||      t        j                  |t        j                  t        j                  t        j                  t        j                  |                                    S t	        j
                  |j                  d      rt        j                  t        j                  | |      t        j                  |t        j                  |d                  }t        j                  |t        j                  t        j                  |                  }t        j                   t        j"                  |      t%        t        j&                  |      t(        j*                              S t-        d|j                         )z1Compute log(exp(x1) + exp(x2)) avoiding overflow.real floatingcomplex floatingr   z9logaddexp requires floating-point or complex inputs; got )r   r   r"   maxr   isdtyperT   rR   _isnanrQ   log1pexpnegabsmulrO   complexr`   rZ   imagr^   pirA   )x1x2x1_arrx2_arramaxdeltar0   s          r1   	logaddexprz     sp    ;;r?&;;r?&		%%	%		 $^^FLL/2GGFF#E::cjj'ggff-ggdCIIcggcggcggen6M.N$OPR R ~~fll$67GGCGGBOSWWT3::dA3F%GHE
''$		#''%.1
2C;;sxx}mCHHSM255&IJJ
PQWQ]Q]P^_
``r3   c                   | \  }}|\  }}t        ||      }t        j                  t        j                  |t        j                  t        j
                  t        |      t        |                        t        j                  |t        j                  t        j
                  t        |      t        |                              }||fS r6   )rz   r   rQ   rp   rm   rT   re   primalstangentsrt   ru   t1t2
primal_outtangent_outs           r1   _logaddexp_jvpr     s    &"b&"bR *CGGCGGL4DlS]F^,_$`aCGGCGGL4DlS]F^,_$`ac+	[	  r3   c               j   t        j                  |       }t        j                  |      }|j                  |j                  k(  sJ t        j                  ||      }t        j                  |dt        j                  d      z        }t        j                  |j                  d      rt        j                  ||      }t        j                  t        j                  |      t        j                  ||      t        j                  |t        j                  |t        j                  t        j                  t        j                   t        j"                  |                                          S t        j                  |j                  d      rt        j                  t        j                  ||      t        j                  |t        j                  |d                  }t        j                  |t        j                  |t        j                  t        j                  |                        }t        j$                  t        j&                  |      t)        t        j*                  |      t
        j,                  t        j                  d      z              S t/        d|j                         )z4Compute log2(exp2(x1) + exp2(x2)) avoiding overflow.r   r   rg   rh   z:logaddexp2 requires floating-point or complex inputs; got )r   r   r"   ri   rO   r^   logr   rj   rT   rR   rk   rQ   rp   rl   exp2rn   ro   rq   r`   rZ   rr   rs   rA   )rt   ru   rv   rw   rx   invln2ry   r0   s           r1   
logaddexp2r   $  s    ;;r?&;;r?&		%%	%		 $::dAbffQiK(&^^FLL/2GGFF#E::cjj'ggff-ggdCGGFCIIchhswwswwW\~G^>_4`$abd d ~~fll$67GGCGGFF+SWWT3::dA;N-OPE
''$		#((5/(BC
DC;;sxx}mCHHSM255266RS9CT&UVV
QRXR^R^Q_`
aar3   c                   | \  }}|\  }}t        ||      }t        j                  t        j                  |t        j                  t        j
                  t        |      t        |                        t        j                  |t        j                  t        j
                  t        |      t        |                              }||fS r6   )r   r   rQ   rp   r   rT   re   r|   s           r1   _logaddexp2_jvpr   :  s    &"b&"b"b!*CHHSWW\"5E|T^G_-`$abCHHSWW\"5E|T^G_-`$abd+	[	  r3   )NNNNN)r   r   r)   Sequence[int]r   r   r   str | Sequence[tuple[int, int]]r   Sequence[int] | Noner   r   r   5convolution.ConvGeneralDilatedDimensionNumbers | Noner   zlax.Precision | Noner   zDType | Nonereturnr   )NNNN)r   r   r   r   r   r   r   r   r)   r   r   r   r   r   r   r   r   zlax.PrecisionLiker   r   )rU   r   r   r   )rt   r   ru   r   r   r   )
__future__r   collections.abcr   r   typingr   jax._src.custom_derivativesr   jax._srcr   jax._src.laxr   r	   r
   jax._src.typingr   r   numpyr^   DTyper2   rM   rZ   re   rz   defjvpr   r   r   r7   r3   r1   <module>r      s   # $   2   $  ,  *.)-OS&*+/\	\\ "\ -	\
 '\ '\ M\ $\ )\ \J *.)-OS#'t	t	t "t -	t
  t 't 't Mt !t tn9 a a( ! ! b b* ! !r3   