
    ͑ij                       S SK Jr  S SKJr  S SKJrJr  S SKrS SKJ	r	  \(       a  S SKJ
r
  S r " S S	5      r " S
 S\5      r " S S5      r " S S\5      r " S S\5      rS r\ S       SS jj5       r\ S       SS jj5       r\ S       S S jj5       r\ S       S!S jj5       r S"S jr\ S       S#S jj5       r\ S       S$S jj5       r S"S jrS rS"S jrg)%    )annotations)Sequence)TYPE_CHECKINGoverloadN)	framework)Tensorc                    [        U [        R                  5      (       a  U $ [        U [        5      (       a  [	        U 5      $ U $ N)
isinstancer   Variabler   tuple)xss    X/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/autograd/autograd.py
as_tensorsr      s6    "i(())		B	!	!Ry	    c                      \ rS rSrSr S       SS jjr\SS j5       rS rSS jr	S r
S rS	 rS
 rS rS rS rS rS rS rS rS rS rS rS rSrg)Jacobian#   a  Computes the Jacobian matrix of given xs and ys.

Once the Jacobian ``J`` is constructed, you can use a multidimensional index
to retrieve the submatrix of ``J``, as same as slicing a Tensor. The
submatrix is lazily evaluated along row axis, and will be cached once
evaluated.

you can retrieve the submatrix by
following methods:

    * J[:], retrieving the full matrix.
    * J[:, :, j], retrieving the partial derivatives w.r.t. the j'th input
      variable.
    * J[:, i, :], retrieving the partial derivatives w.r.t. the i'th output
      variable.
    * J[:, i, j], retrieving the partial derivatives w.r.t. the i'th output
      variable and the j'th input variable.

Notes:

    Ellipsis index is not supported currently.

Args:

    ys (Tensor|Tuple[Tensor, ...]): The output derived from xs .
    xs (Tensor|Tuple[Tensor, ...]): The input tensor(s) .
    is_batched (bool): If true, the first axis is batch axis. Defaults to
        False.

Returns:

    Jacobian (Object): A python object retains the Jacobian matrix.

c                l   U(       d  S[        UR                  5      s=::  a  S::  d#  O  [        S[        UR                  5       35      eS[        UR                  5      s=::  a  S::  d#  O  [        S[        UR                  5       35      e[        X5      U l        g S[        UR                  5      s=::  a  S::  d#  O  [        S[        UR                  5       35      eS[        UR                  5      s=::  a  S::  d#  O  [        S[        UR                  5       35      e[        X5      U l        g )Nr      z7xs.ndim should be 0 or 1 when is_batched=False but got z7ys.ndim should be 0 or 1 when is_batched=False but got    z6ys.ndim should be 1 or 2 when is_batched=True but got z6xs.ndim should be 1 or 2 when is_batched=True but got )lenshape
ValueError_JacobianNoBatch	_jacobian_JacobianBatchFirst)selfysr   
is_batcheds       r   __init__Jacobian.__init__G   s    BHH**   #BHH0  BHH**   #BHH0  .b5DNBHH**   #BHH0  BHH**   #BHH0  18DNr   c                .    U R                   R                  $ )z'The shape of flattened Jacobian matrix.)r   r   r   s    r   r   Jacobian.shapef   s     ~~###r   c                     U R                   U   $ r
   r   )r   indexess     r   __getitem__Jacobian.__getitem__k   s    ~~g&&r   c                    US:X  a  [        U R                  U5      $ US:X  a  [        U R                  U5      $ [        U R                  R                  5       U5      $ )Nr   _evaluate_all)getattrr   r,   )r   _Jacobian__names     r   __getattr__Jacobian.__getattr__n   sN    W4>>622_$4>>622t~~335v>>r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-   $ r
   r,   r   r   r   otherlhsrhss       r   __add__Jacobian.__add__u   4      "'1%'B'Be!!#yr   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-
  $ r
   r2   r3   s       r   __sub__Jacobian.__sub__z   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   __mul__Jacobian.__mul__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   __div__Jacobian.__div__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   __truediv__Jacobian.__truediv__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   __pow__Jacobian.__pow__   s3      "'1%'B'Be!!#xr   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   __mod__Jacobian.__mod__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   __floordiv__Jacobian.__floordiv__   4      "'1%'B'Be!!#zr   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#-  $ r
   r2   r3   s       r   
__matmul__Jacobian.__matmul__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#:H  $ r
   r2   r3   s       r   __eq__Jacobian.__eq__   rO   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#:g  $ r
   r2   r3   s       r   __ne__Jacobian.__ne__   rO   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#:  $ r
   r2   r3   s       r   __lt__Jacobian.__lt__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#:*  $ r
   r2   r3   s       r   __le__Jacobian.__le__   rO   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#:  $ r
   r2   r3   s       r   __gt__Jacobian.__gt__   r9   r   c                x    U R                  5       n[        U[        5      (       a  UR                  5       OUnX#:  $ r
   r2   r3   s       r   __ge__Jacobian.__ge__   rO   r   r'   N)F)r   r   r   r   r    boolreturnNone)rf   z	list[int])r.   str)__name__
__module____qualname____firstlineno____doc__r!   propertyr   r)   r/   r7   r;   r>   rA   rD   rG   rJ   rM   rQ   rT   rW   rZ   r]   r`   rc   __static_attributes__ r   r   r   r   #   s    !N !	99 9 	9
 
9> $ $'?













r   r   c                      \ rS rSrSrg)Hessian   rp   N)ri   rj   rk   rl   ro   rp   r   r   rr   rr      s    r   rr   c                  \    \ rS rSrSrS r\S 5       rS rS r	SS jr
S rS	 rS
 rS rSrg)	_Jacobian   a  The base class for computing Jacobian matrix.

``_Jacobian`` implements the core logic of multidimensional index and lazy
evaluation for Jacobian matrix, subclass only need to overwrite following
methods:

    * ``_lazy_axis()``,  return the axis along which will be lazy
        evaluating.
    * ``_flatten(xs)``, flattens the inputs ``xs``.
    * ``_evaluate(index)``, evaluates one slice along ``_lazy_axis`` .

Notes:

    Because currently PaddlePaddle only support reverse differentiation by
    ``paddle.grad``, so lazy evaluation is only supported along the row of
    Jacobian matrix, which means that slicing along row will get better
    performance.

c                h   UR                   U l        UR                   U l        X l        Xl        [        U R                  R                   5      S:X  a2  U R                  (       d!  U R                  R                  S/5      U l        [        U R                  R                   5      S:X  a3  U R                  (       a"  U R                  R                  SS/5      U l        U R                  [        U R                  5      5      U l
        U R                  [        U R                  5      5      U l        0 U l        g )Nr   r   )r   original_xs_shapeoriginal_ys_shape_xs_ysr   r    reshape_flattenr   _flatten_xs_flatten_ys_cache)r   r   r   s      r   r!   _Jacobian.__init__   s    !#!#txx~~!#DOOxx''DH
 txx~~!#xx''Q0DH==DHH)=>==DHH)=>r   c                    [         e)z"The axis of lazily evaluated.NotImplementedErrorr$   s    r   
_lazy_axis_Jacobian._lazy_axis   s
     "!r   c                    XR                      n[        U[        5      (       a  U4$ [        [	        UR
                  UR                  UR                  5      5      $ r
   )r   r   intr   rangestartstopstep)r   r(   idxs      r   _lazy_indexes_Jacobian._lazy_indexes   sM    oo& #s## F	
 uSYY#((;<	
r   c                    [         er
   r   r   r   s     r   r~   _Jacobian._flatten   s    !!r   c                    XR                      n[        U[        5      (       a  SO[        SUS5      n/ US U R                    QUPXR                   S-   S  Q7$ )Nr   r   )r   r   r   slice)r   r(   lazy_axis_sizer   shifted_lazy_axis_idxs        r   _shifted_indexes_Jacobian._shifted_indexes   sl    oo&C%%A5NA+F 	
&t'
!
 __q(*+
 	
r   c                0   U R                   SL a_  [        U R                  5      S:X  a  [        S5      e[        U R                  5      S:X  a!  [        U R                  5      S:X  a  SU4OUS4nO[        U R                  5      S:X  a  USS4nOm[        U R                  5      S:X  aT  [        U[        5      (       a  U[        S S S 5      4nO/[        U R                  5      S:X  a  US   SUS   4O
US   US   S4n[        XR                  5      n[        XR                     [        5      (       aA  US U R                   XR                  S-   S  -   nU R                  XR                     5      U   $ U R                  U5      n[        U R                  5      n[        U5      X@R                  '   [        R                  " U Vs/ s H  oPR                  U5      PM     snU R                  S9R!                  U5      nX`R#                  U[        U5      5         n[        UR                  5      [        U R                  5      :  aL  [%        [        UR                  5      [        U R                  5      -
  5       H  nUR'                  S5      nM     U$ s  snf )NFr   z0-D tensor can not be indexed.r   r   )axisrx   )r    r   r   
IndexErrorrz   r   r   _multi_indexinner_shaper   r   _cached_evaluater   listpaddleconcatr}   r   r   squeeze)	r   r(   other_indexeslazy_indexesr   ipart_jacresult_s	            r   r)   _Jacobian.__getitem__  sN   ??e#4::!# !ABBTZZA% 4112a7 L!1  4::!#"Aq/TZZA%gu--&dD$(?@G t556!; !Q
3%aj'!*a8  w(8(89goo.44)$//*W__q5H5J-KK  (()AB  ))'2 T%%&!$\!2oo==/;<|!""1%|<
 '%. 	 //\9JKL v||s4::.3v||,s4::>?+ @  =s   Jc                    Uc   U R                  S5      R                  / 5      $ U R                  R                  U5      nUc  U R	                  U5      nX R                  U'   U$ Nr   )r   r}   r   get	_evaluate)r   kvs      r   r   _Jacobian._cached_evaluate=  sX    9((+33B77KKOOA9q!AKKNr   c                    [         e)z&Evaluate one slice at along lazy axis.r   )r   indexs     r   r   _Jacobian._evaluateF  s    !!r   c                `    [        U R                  5      S:X  a  U R                  S 5      $ U S S  $ r   )r   r   r   r$   s    r   r,   _Jacobian._evaluate_allJ  s,    tzz?a((..7Nr   )r   r   r   r{   r|   ry   rz   N)r   )ri   rj   rk   rl   rm   r!   rn   r   r   r~   r   r)   r   r   r,   ro   rp   r   r   ru   ru      sD    ($ " "
"	
4l"r   ru   c                  H   ^  \ rS rSrSrU 4S jr\S 5       rS rS r	Sr
U =r$ )r   iQ  zCompute Jacobian matrix without batch dimension.
Suppose the mapping is :math:`f: R^M        o R^N`, the output shape is
``(N, M)`` .
c                   > SU l         [        TU ]	  X5        / U R                  R                  SS QU R
                  R                  SS QU l        / U R                  SS QU R                  SS QU l        g )NFr   r   )	r    superr!   r   r   r   r   rz   ry   r   r   r   	__class__s      r   r!   _JacobianNoBatch.__init__W  s     
$$Qq)
$$Qq)

$$Qq)
$$Qq)

r   c                    gr   rp   r$   s    r   r   _JacobianNoBatch._lazy_axisd      r   c                    [        U[        5      (       d  UR                  S5      $ [        R                  " [        S U 5       5      5      $ )Nrx   c              3  B   #    U  H  oR                  S 5      v   M     g7f)r   N)r}   .0xs     r   	<genexpr>,_JacobianNoBatch._flatten.<locals>.<genexpr>k  s     "@R99U#3#3Rs   )r   r   r}   r   r   r   r   s     r   r~   _JacobianNoBatch._flattenh  s8    "h''::e$$}}U"@R"@@AAr   c                f    U R                  [        U R                  U   U R                  5      5      $ r
   r~   _grad_for_jacobianr   r{   r   	row_indexs     r   r   _JacobianNoBatch._evaluatem  s0    }}  +
 	
r   r   r    r   ri   rj   rk   rl   rm   r!   rn   r   r~   r   ro   __classcell__r   s   @r   r   r   Q  s1    

  B

 
r   r   c                  H   ^  \ rS rSrSrU 4S jr\S 5       rS rS r	Sr
U =r$ )r   iv  zCompute Jacobian matrix with batch at first axis.
Suppose the mapping is :math:`f: R^{B,M}    o R^{B,N}`, the output shape is
``(B, N, M)`` .
c                R  > SU l         [        TU ]	  X5        / U R                  R                  SS QU R
                  R                  SS QU R                  R                  SS QU l        / U R                  R                  SS QU R                  SS QU R                  SS QU l        g )NTr   r   r   )	r    r   r!   r   r   r   r   rz   ry   r   s      r   r!   _JacobianBatchFirst.__init__|  s     
$$Qq)
$$Qq)
 $$Qq)


$$Qq)
$$Qq)
 $$Qq)

r   c                    g)Nr   rp   r$   s    r   r   _JacobianBatchFirst._lazy_axis  r   r   c                    [        U[        5      (       d   UR                  UR                  S   S45      $ [        R
                  " [        S [        U5       5       5      S5      $ )Nr   rx   c              3  `   #    U  H$  oR                  UR                  S    S45      v   M&     g7f)r   rx   N)r}   r   r   s     r   r   /_JacobianBatchFirst._flatten.<locals>.<genexpr>  s'     F~!))QWWQZ,--~s   ,.r   )r   r   r}   r   r   r   r   r   r   s     r   r~   _JacobianBatchFirst._flatten  sP    "h''::rxx{B/00}}Fz"~FF
 	
r   c                n    U R                  [        U R                  S S 2U4   U R                  5      5      $ r
   r   r   s     r   r   _JacobianBatchFirst._evaluate  s0    }}t//9=txxH
 	
r   r   r   r   s   @r   r   r   v  s0    

  

 
r   r   c           	     L   [        U [        5      (       a  U OU 4n [        S U  5       5      (       a  [        S5      eU [	        SSS5      4[        U5      [        U 5      -
  -  -   n / n[        U 5       GH#  u  p4[        U[        5      (       a  [	        UR                  =(       d    SUR                  =(       d    X   UR                  =(       d    S5      nUR                  [	        UR                  S:  a  UR                  X   -   OUR                  UR                  S:  a  UR                  X   -   OUR                  UR                  5      5        M  [        U[        5      (       a!  UR                  US:  a  XAU   -   OU5        GM  [        SU S35      e   [        U5      $ )a.  A tool for parsing N-dimensional index into a standard format.

Currently supporting following input format:
    * ([positive|negative|slice], ...), the right-most elements can be
        omitted.

The standard format after converted is slice tuple which contains N elements:
    * ([positive|slice], ..., [positive|slice])

Notes:
    Ellipsis indexes such as ``(..., i), (i, ...)`` is not supported.

Args:
    indexes (tuple): The input indexes.
    shape (tuple): The input shape.

Returns:
    tuple: The standard format index as the above description.
c              3  T   #    U  H  n[        U[        [        5      5      v   M      g 7fr
   )r   typeEllipsis)r   r   s     r   r   _multi_index.<locals>.<genexpr>  s     
:'Q:ah(('s   &(z*Ellipsis index currently is not supported.r   Nr   zNot supported index type .)r   r   anyr   r   r   	enumerater   r   r   appendr   	TypeErrorr   )r(   r   positive_indexesr   r   s        r   r   r     s[   ( $GX66gWJG

:'
:::EFFq$-/3u:G3LMMGg&eU## q%**"8%**/E ##.3kkAoEKK%(*5;;-2ZZ!^EJJ) JJ s####	E!H$4uM7wa@AA# '$ !""r   c                    g r
   rp   r   r   
batch_axiss      r   jacobianr     s    
 r   c                    g r
   rp   r   s      r   r   r     s    
 (+r   c                    g r
   rp   r   s      r   r   r         
 r   c                    g r
   rp   r   s      r   r   r     r   r   c                  ^ ^^ Ub  US:w  a  [        SU S35      eUSLm[        T [        5      (       a-  [        T[        5      (       a  [        UU4S jT  5       5      nU$ [        T [        5      (       a-  [        T[        5      (       d  [        UU4S jT  5       5      nU$ [        T [        5      (       d-  [        T[        5      (       a  [        UU 4S jT 5       5      nU$ [	        T TT5      nU$ )aT  
Computes the Jacobian of the dependent variable ``ys`` versus the independent
variable ``xs``.

Where ``ys`` represents the output of ``xs`` after a certain operation, ``ys`` and
``xs`` can be Tensor or tuple of Tensors, ``batch_axis`` indicates the position of
the batch dimension of the parameter data.

When the input is a tuple Tensors, the returned result is a ``Jacobian`` object with
the same number of nesting levels as ``xs``, and each Jacobian has the same shape as
The ``xs`` tuples are identical in one-to-one correspondence.

- When ``batch_axis=None``, only 0-dimensional Tensor or 1-dimensional Tensor is
  supported, assuming the shape of ``xs`` is ``[N, ]``, the shape of ``ys`` is
  ``[M, ]``, then the output Jacobian matrix shape is ``[M, N]``.

- When ``batch_axis=0``, only 1-dimensional Tensor or 2-dimensional Tensor is
  supported, assuming the shape of ``xs`` is ``[B, N]``, The shape of ``ys`` is
  ``[B, M]``, then the output Jacobian matrix shape is ``[B, M, N]``.

After the ``Jacobian`` object is created, the actual calculation process does not
occur, but the lazy evaluation method is used for calculation. It can be
multi-dimensional indexed to obtain the entire Jacobian matrix or sub-matrix, and
the actual calculation will be performed at this time the value is calculated and
the result is returned. At the same time, in the actual evaluation process, the
calculated sub-matrix will be cached to avoid duplicate calculations in the
subsequent indexing process.

For example, assuming ``Jacobian`` instance ``J`` has shape ``[B, M, N]``, assuming
``M > 4`` , then ``J[:, 1:4:1, :]`` means to get the values from row ``1`` to row
``3`` of ``J``. In actual calculation, only the rows ``1`` to ``3`` are evaluated,
and the calculation results of ``1`` to ``3`` will be cached at the granularity of
the row, and will be used next time. When obtaining one or more rows of results
above, the already calculated parts will not be recalculated.

Args:

    ys (Union[paddle.Tensor, Tuple[paddle.Tensor, ...]]): Output or tuple of outputs derived from xs.
    xs (Union[paddle.Tensor, Tuple[paddle.Tensor, ...]]): Input or tuple of inputs.
    batch_axis (Optional[int], optional): Index of batch axis. Defaults to None.

Returns:

    Union[Tuple[Tuple[Jacobian, ...], ...], Tuple[Jacobian, ...], Jacobian]: Jacobian(s) of ys derived from xs.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> x1 = paddle.randn([3])
        >>> x2 = paddle.randn([3])
        >>> x1.stop_gradient = False
        >>> x2.stop_gradient = False

        >>> y = x1 + x2

        >>> J = paddle.autograd.jacobian(y, (x1, x2))
        >>> J_y_x1 = J[0][:]  # evaluate result of dy/dx1
        >>> J_y_x2 = J[1][:]  # evaluate result of dy/dx2

        >>> print(J_y_x1.shape)
        paddle.Size([3, 3])
        >>> print(J_y_x2.shape)
        paddle.Size([3, 3])
Nr   z(batch_axis should be None or 0, but got r   c              3  R   >^#    U  H  m[        UU4S  jT 5       5      v   M     g7f)c              3  >   >#    U  H  n[        TUT5      v   M     g 7fr
   r   )r   r{   r|   r    s     r   r   %jacobian.<locals>.<genexpr>.<genexpr>>  s     ?BS(3Z00B   N)r   r   r|   r    r   s    @r   r   jacobian.<locals>.<genexpr>=  s"      
KMCE?B???2s   #'c              3  >   >#    U  H  n[        UTT5      v   M     g 7fr
   r   r   s     r   r   r   A  s     F2C(3J772r   c              3  >   >#    U  H  n[        TUT5      v   M     g 7fr
   r   )r   r{   r    r   s     r   r   r   C  s     F2C(2sJ772r   )r   r   r   r   r   )r   r   r   r   r    s   ``  @r   r   r     s    R */6zl!D
 	

 4'J"hJr8$<$< 
KM
 
	  
B	!	!*R*B*BF2FF	  H%%*R*B*BF2FF	  RZ0	r   c                    g r
   rp   r   s      r   hessianr   J  s    
 r   c                    g r
   rp   r   s      r   r   r   R  s    
 '*r   c                  ^^ TcC  U R                  5       S:  a  [        SU R                  5        S35      eU R                  S5      n O[        T[        5      (       aW  U S   R                  5       S:  a  [        SU R                  5        S35      eTS:w  a  [        S5      eU R                  S	5      n O[        S
[        T5       S35      e[        U TT5      n[        T[        5      (       d  [        UTT5      n[        Ul	        U$ [        UU4S jU 5       5      n[        [        U5      5       H1  n[        [        US   5      5       H  n[        XE   U   l	        M     M3     U$ )a
  
Computes the Jacobian of the dependent variable ``ys`` versus the independent
variable ``xs``.

Among them, ``ys`` means the output of ``xs`` after a certain operation, ``ys`` can
only be a single Tensor, ``xs`` can be a Tensor or a Tensor tuple, and
``batch_axis`` means The position of the batch dimension of the parameter data.

When the input ``xs`` is a Tensor tuple, the returned result is a ``Hessian`` tuple,
assuming that the internal shape of the ``xs`` tuple is composed of ``([M1, ], [M2, ])``, the shape of the returned
result consists of ``(([M1, M1], [M1, M2]), ([M2, M1], [M2, M2]))``

- When ``batch_axis=None``, only 0-dimensional Tensor or 1-dimensional Tensor is
  supported, assuming that the shape of ``xs`` is ``[N, ]``, and the shape of ``ys`` is ``[ ]`` (0-dimensional Tensor), the final output is a single Hessian matrix whose shape is ``[N, N]``.

- When ``batch_axis=0``, only 1-dimensional Tensor or 2-dimensional Tensor is
  supported, assuming that the shape of ``xs`` is ``[B, N]``, and the shape of ``ys`` is ``[B, ]``, the final output Jacobian matrix shape is ``[B, N, N]``.

After the ``Hessian`` object is created, the complete calculation process does not
occur, but a partial lazy evaluation method is used for calculation. It can be
multi-dimensionally indexed to obtain the entire Hessian matrix or sub-matrix. At
this time, the actual Evaluates the computation and returns the result. At the same
time, in the actual evaluation process, the calculated sub-matrix will be cached to
avoid repeated calculations in the subsequent indexing process.

Args:

    ys (paddle.Tensor): Output derived from xs which contain one element.
    xs (Union[paddle.Tensor, Tuple[paddle.Tensor, ...]]): Input or tuple of inputs.
    batch_axis (Optional[int], optional): Index of batch axis. Defaults to None.

Returns:

    Union[Tuple[Tuple[Hessian, ...], ...], Tuple[Hessian, ...], Hessian]: Hessian(s) of ys derived from xs.

Examples:

    .. code-block:: pycon

        >>> import paddle

        >>> x1 = paddle.randn([3])
        >>> x2 = paddle.randn([4])
        >>> x1.stop_gradient = False
        >>> x2.stop_gradient = False

        >>> y = x1.sum() + x2.sum()

        >>> H = paddle.autograd.hessian(y, (x1, x2))
        >>> H_y_x1_x1 = H[0][0][:]  # evaluate result of ddy/dx1x1
        >>> H_y_x1_x2 = H[0][1][:]  # evaluate result of ddy/dx1x2
        >>> H_y_x2_x1 = H[1][0][:]  # evaluate result of ddy/dx2x1
        >>> H_y_x2_x2 = H[1][1][:]  # evaluate result of ddy/dx2x2

        >>> print(H_y_x1_x1.shape)
        paddle.Size([3, 3])
        >>> print(H_y_x1_x2.shape)
        paddle.Size([3, 4])
        >>> print(H_y_x2_x1.shape)
        paddle.Size([4, 3])
        >>> print(H_y_x2_x2.shape)
        paddle.Size([4, 4])
r   zOnly support ys.numel()(z)==1 when batch_axis is None.rp   r   zOnly support ys[0].numel()(z)==1 when batch_axis is intzOnly support batch_axis=0 yet.r   z*batch_axis should be None or int, but got r   c              3  >   >#    U  H  n[        UTT5      v   M     g 7fr
   )r   )r   _jr   r   s     r   r   hessian.<locals>.<genexpr>  s     IyR44yr   )numelr   r}   r   r   r   r   r   rr   r   r   r   r   )r   r   r   r   r   r   js    ``    r   r   r   Z  sX   J 88:>*288:,6ST  ZZ^	J	$	$a5;;=1-bhhj\9TU  ?=>>ZZ8j9I8J!L
 	
 R,Ib(##9b*5 $ N IyII s7|$A3wqz?+*1
1' , % Nr   c                   ^ U c)  [         R                  " T5      n TR                  U l        U $ [        U [        5      (       a  [        U4S j[        U 5       5       5      $ U $ )Nc              3  F   >#    U  H  u  p[        UTU   5      v   M     g 7fr
   )_replace_none_with_zero_tensor)r   r   r   refss      r   r   1_replace_none_with_zero_tensor.<locals>.<genexpr>  s%      
CP41*1d1g66=s   !)r   
zeros_likestop_gradientr   r   r   r   )r   r  s    `r   r  r    s]    	zt$--		B	!	! 
CLR=
 
 	
 	r   c                   [         R                  " 5       (       at  [         R                  " XUSSS9n[        U[         R                  R
                  R                  5      (       a)  [        U[        5      (       a  [        U5      S:  a  US   nOh[         R                  R                  XU5      n[        U[
        R                  5      (       a)  [        U[        5      (       a  [        U5      S:  a  US   n[        X15      $ )a  A gradient function that can be used in dynamic graph and static graph.

The ``grad`` combines ``paddle.grad`` used in dynamic graph and
``paddle.static.gradients`` used in static graph, and do following changes:

* The ``allow_unused`` flag is removed and set defaults to true internally,
    none in outputs will be replaced by zero tensor.
* The ``create_graph`` flag is removed and set defaults to true internally,
    only makes sense in dynamic graph.
* When xs is a single Tensor, ``paddle.grad`` returns a list which only
    contains one Tensor. It may confuse users, thus in this case we improve
    to return a single Tensor in _grad_for_jacobian interface.

Args:
    ys (Tensor|Sequence[Tensor]): The output tensor or tensor sequence of
        the graph to compute gradients.
    xs (Tensor|Sequence[Tensor]): The input tensor or tensor sequence of the graph to
        compute gradients. The returned values of this API are the
        gradients of inputs .
    v (Tensor|Sequence[Tensor]|None,optional): The initial gradient values
        of outputs . If grad_outputs is None, the initial gradient values of
        outputs would be Tensors filled with 1; if grad_outputs is not None,
        it must have the same length as outputs , and in this case, the
        initial gradient value of the i-th outputs would be: (1) a Tensor
        filled with 1 when the i-th element of grad_outputs is None;
        (2) the i-th element of grad_outputs when the i-th element of
        grad_outputs is a Tensor. Default None.

Returns:
    Tensor|tuple[Tensor]: Tensor or a tuple of Tensors, whose length is the
        same as the Tensor number inside inputs, and the i-th returned
        Tensor is the sum of gradients of outputs with respect to the i-th
        inputs.
T)create_graphallow_unusedr   )r   in_dynamic_modegradr   baser   r   r   r   static	gradientsr  )r   r   r   xs_grads       r   r   r     s    F  ++badNr6;;0099::7H--Gq ajG--))"!4r9--..7H--Gq ajG)'66r   ).)r   r   r   r   r   
int | Nonerf   r   )r   Sequence[Tensor]r   r  r   r  rf   z tuple[tuple[Jacobian, ...], ...])r   r   r   r  r   r  rf   tuple[Jacobian, ...])r   r  r   r   r   r  rf   r  r
   )r   r   r   r   r   r  rf   rr   )r   r   r   r  r   r  rf   ztuple[tuple[Hessian, ...], ...])
__future__r   collections.abcr   typingr   r   r   paddle.baser   r   r   r   rr   ru   r   r   r   r   r   r  r   rp   r   r   <module>r     s   # $ *  ![ [|	h 	I IX"
y "
J#
) #
L-#` 
 !  	 
 
 !+++ + &	+ 
+ 
 !  	 
 
 !  	 
 [| 
 !  	 
 
 !*** * %	* 
* gT
67r   