
    yjj                       d dl mZ d dlmZ d dlmZmZ d dlZd dlm	Z	 erd dlm
Z
 d Z G d d	          Z G d
 de          Z G d d          Z G d de          Z G d de          Zd Ze	 d(d)d            Ze	 d(d*d            Ze	 d(d+d            Ze	 d(d,d             Z	 d-d!Ze	 d(d.d"            Ze	 d(d/d$            Z	 d-d%Zd& Zd-d'ZdS )0    )annotations)Sequence)TYPE_CHECKINGoverloadN)	framework)Tensorc                    t          | t          j                  r| S t          | t                    rt	          |           S | S N)
isinstancer   Variabler   tuple)xss    h/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/autograd/autograd.py
as_tensorsr      s?    "i()) 		B	!	! Ryy	    c                      e Zd ZdZ	 d!d"d
Zed#d            Zd Zd$dZd Z	d Z
d Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd S )%Jacobianac  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.

    Fysr   r   
is_batchedboolreturnNonec                   |sdt          |j                  cxk    rdk    s&n t          dt          |j                             dt          |j                  cxk    rdk    s&n t          dt          |j                             t          ||          | _        d S dt          |j                  cxk    rdk    s&n t          dt          |j                             dt          |j                  cxk    rdk    s&n t          dt          |j                             t          ||          | _        d S )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)selfr   r   r   s       r   __init__zJacobian.__init__G   s     	9BH******** 0 #BH0 0   BH******** 0 #BH0 0   .b"55DNNNBH******** 0 #BH0 0   BH******** 0 #BH0 0   1R88DNNNr   	list[int]c                    | j         j        S )z'The shape of flattened Jacobian matrix.)r    r   r"   s    r   r   zJacobian.shapef   s     ~##r   c                    | j         |         S r
   )r    )r"   indexess     r   __getitem__zJacobian.__getitem__k   s    ~g&&r   _Jacobian__namestrc                    |dk    rt          | j        |          S |dk    rt          | j        |          S t          | j                                        |          S )Nr   _evaluate_all)getattrr    r-   )r"   r*   s     r   __getattr__zJacobian.__getattr__n   sZ    W4>6222_$$4>6222t~3355v>>>r   c                    |                                  }t          |t                    r|                                 n|}||z   S r
   r-   r   r   r"   otherlhsrhss       r   __add__zJacobian.__add__u   B      ""'1%'B'BMe!!###Syr   c                    |                                  }t          |t                    r|                                 n|}||z
  S r
   r1   r2   s       r   __sub__zJacobian.__sub__z   r7   r   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   __mul__zJacobian.__mul__   r7   r   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   __div__zJacobian.__div__   r7   r   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   __truediv__zJacobian.__truediv__   r7   r   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   __pow__zJacobian.__pow__   sA      ""'1%'B'BMe!!###Cxr   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   __mod__zJacobian.__mod__   r7   r   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   __floordiv__zJacobian.__floordiv__   sB      ""'1%'B'BMe!!###czr   c                    |                                  }t          |t                    r|                                 n|}||z  S r
   r1   r2   s       r   
__matmul__zJacobian.__matmul__   r7   r   c                    |                                  }t          |t                    r|                                 n|}||k    S r
   r1   r2   s       r   __eq__zJacobian.__eq__   B      ""'1%'B'BMe!!###czr   c                    |                                  }t          |t                    r|                                 n|}||k    S r
   r1   r2   s       r   __ne__zJacobian.__ne__   rJ   r   c                    |                                  }t          |t                    r|                                 n|}||k     S r
   r1   r2   s       r   __lt__zJacobian.__lt__   B      ""'1%'B'BMe!!###Syr   c                    |                                  }t          |t                    r|                                 n|}||k    S r
   r1   r2   s       r   __le__zJacobian.__le__   rJ   r   c                    |                                  }t          |t                    r|                                 n|}||k    S r
   r1   r2   s       r   __gt__zJacobian.__gt__   rO   r   c                    |                                  }t          |t                    r|                                 n|}||k    S r
   r1   r2   s       r   __ge__zJacobian.__ge__   rJ   r   N)F)r   r   r   r   r   r   r   r   )r   r$   )r*   r+   )__name__
__module____qualname____doc__r#   propertyr   r)   r/   r6   r9   r;   r=   r?   rA   rC   rE   rG   rI   rL   rN   rQ   rS   rU    r   r   r   r   #   sa       ! !N !	9 9 9 9 9> $ $ $ X$' ' '? ? ? ?  
  
  
  
  
  
  
  
  
  
  
  
  
  
    r   r   c                      e Zd ZdS )HessianN)rV   rW   rX   r[   r   r   r]   r]      s        Dr   r]   c                  Z    e Zd ZdZd Zed             Zd Zd ZddZ	d Z
d	 Zd
 Zd ZdS )	_Jacobiana  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                "   |j         | _        |j         | _        || _        || _        t          | j        j                   dk    r'| j        s | j                            dg          | _        t          | j        j                   dk    r(| j        r!| j                            ddg          | _        |                     t          | j                            | _
        |                     t          | j                            | _        i | _        d S )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#   z_Jacobian.__init__   s    !#!#tx~!##DO#x'' DH
 tx~!###x''Q00DH==DH)=)=>>==DH)=)=>>r   c                    t           )z "The axis of lazily evaluated.NotImplementedErrorr&   s    r   
_lazy_axisz_Jacobian._lazy_axis   s
     "!r   c                    || j                  }t          |t                    r|fn,t          t	          |j        |j        |j                            S r
   )rn   r   intr   rangestartstopstep)r"   r(   idxs      r   _lazy_indexesz_Jacobian._lazy_indexes   sJ    do& #s##=SFFuSY#(;;<<	
r   c                    t           r
   rl   r"   r   s     r   rg   z_Jacobian._flatten   s    !!r   r   c                    || j                  }t          |t                    rdnt          d|d          }g |d | j                  ||| j         dz   d          R S )Nr   r   )rn   r   rp   slice)r"   r(   lazy_axis_sizeru   shifted_lazy_axis_idxs        r   _shifted_indexesz_Jacobian._shifted_indexes   s}    do&C%%FAA5NA+F+F 	
&t&'
!
 T_q(**+
 
 	
r   c                <     j         du r`t           j                  dk    rt          d          t           j                  dk    r t           j                  dk    rd|fn|df}nt           j                  dk    r|ddf}n{t           j                  dk    rct          |t                    r|t          d d d           f}n:t           j                  dk    r|d         d|d         fn|d         |d         df}t          | j                  }t          | j	                 t                    rH|d  j	                 | j	        dz   d          z   }                     | j	                           |         S                      |          }t           j                  }t          |          | j	        <   t          j         fd|D              j	                                      |          }|                     |t          |                             }t          |j                  t           j                  k    rNt%          t          |j                  t           j                  z
            D ]}|                    d          }|S )	NFr   z0-D tensor can not be indexed.r   r   c                :    g | ]}                     |          S r[   )_cached_evaluate).0ir"   s     r   
<listcomp>z)_Jacobian.__getitem__.<locals>.<listcomp>1  s'    <<<!T""1%%<<<r   )axisra   )r   r   r   
IndexErrorrc   r   rz   _multi_indexinner_shapern   rp   r   rv   listpaddleconcatrf   r}   rq   squeeze)r"   r(   other_indexeslazy_indexesr   part_jacresult_s   `       r   r)   z_Jacobian.__getitem__  s   ?e##4:!## !ABBBTZA%% 4122a77 LL!1  4:!##"Aq/TZA%%gu-- &dD$(?(?@GG t566!;; !Q
33%aj'!*a8  w(899gdo.44 	)$/)*WT_q5H5J5J-KK  (()ABB  ))'22 T%&&!$\!2!2do=<<<<|<<<
 
 
 '%.. 	 $//\9J9JKKL v|s4:..3v|,,s4:>?? , ,++r   c                    |(|                      d                              g           S | j                            |          }||                     |          }|| j        |<   |S Nr   )r   rf   rj   get	_evaluate)r"   kvs      r   r   z_Jacobian._cached_evaluate=  sb    9((++33B777KOOA9q!!ADKNr   c                    t           )z&Evaluate one slice at along lazy axis.rl   )r"   indexs     r   r   z_Jacobian._evaluateF  s    !!r   c                p    t          | j                  dk    r|                     d           S | d d          S r   )r   r   r   r&   s    r   r-   z_Jacobian._evaluate_allJ  s6    tz??a((...7Nr   N)r   )rV   rW   rX   rY   r#   rZ   rn   rv   rg   r}   r)   r   r   r-   r[   r   r   r_   r_      s         (  $ " " X"
 
 
" " "	
 	
 	
 	
4 4 4l  " " "    r   r_   c                  D     e Zd ZdZ fdZed             Zd Zd Z xZ	S )r   zCompute Jacobian matrix without batch dimension.
    Suppose the mapping is :math:`f: R^M 	o R^N`, the output shape is
    ``(N, M)`` .
    c                   d| _         t                                          ||           g | j        j        dd         | j        j        dd         | _        g | j        dd         | j        dd         | _        d S )NFr   r   )	r   superr#   ri   r   rh   r   rc   rb   r"   r   r   	__class__s      r   r#   z_JacobianNoBatch.__init__W  s    R   
$QqS)
$QqS)

$QqS)
$QqS)



r   c                    dS r   r[   r&   s    r   rn   z_JacobianNoBatch._lazy_axisd      qr   c                    t          |t                    s|                    d          S t          j        t          d |D                                 S )Nra   c              3  @   K   | ]}|                     d           V  dS )r   N)rf   r   xs     r   	<genexpr>z,_JacobianNoBatch._flatten.<locals>.<genexpr>k  s.      "@"@199U#3#3"@"@"@"@"@"@r   )r   r   rf   r   r   r   rx   s     r   rg   z_JacobianNoBatch._flattenh  sM    "h'' 	%::e$$$}U"@"@R"@"@"@@@AAAr   c                h    |                      t          | j        |         | j                            S r
   rg   _grad_for_jacobianri   rd   r"   	row_indexs     r   r   z_JacobianNoBatch._evaluatem  s5    }} + 
 
 	
r   
rV   rW   rX   rY   r#   rZ   rn   rg   r   __classcell__r   s   @r   r   r   Q  s~         

 
 
 
 
   XB B B

 
 
 
 
 
 
r   r   c                  D     e Zd ZdZ fdZed             Zd Zd Z xZ	S )r!   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   d| _         t                                          ||           g | j        j        dd         | j        j        dd         | j        j        dd         | _        g | j        j        dd         | j        dd         | j        dd         | _        d S )NTr   r   r   )	r   r   r#   rh   r   ri   r   rc   rb   r   s      r   r#   z_JacobianBatchFirst.__init__|  s    R   
$QqS)
$QqS)
 $QqS)


$QqS)
$QqS)
 $QqS)



r   c                    dS )Nr   r[   r&   s    r   rn   z_JacobianBatchFirst._lazy_axis  r   r   c                    t          |t                    s"|                    |j        d         df          S t	          j        t          d t          |          D                       d          S )Nr   ra   c              3  Z   K   | ]&}|                     |j        d          df          V  'dS )r   ra   N)rf   r   r   s     r   r   z/_JacobianBatchFirst._flatten.<locals>.<genexpr>  s9      FF!!))QWQZ,--FFFFFFr   r   )r   r   rf   r   r   r   r   r   rx   s     r   rg   z_JacobianBatchFirst._flatten  sg    "h'' 	1::rx{B/000}FFz"~~FFFFF
 
 	
r   c                p    |                      t          | j        d d |f         | j                            S r
   r   r   s     r   r   z_JacobianBatchFirst._evaluate  s7    }}t/9=txHH
 
 	
r   r   r   s   @r   r!   r!   v  s{         

 
 
 
 
   X
 
 

 
 
 
 
 
 
r   r!   c           	     .   t          | t                    r| n| f} t          d | D                       rt          d          | t	          ddd          ft          |          t          |           z
  z  z   } g }t          |           D ]\  }}t          |t                    rt	          |j        pd|j        p||         |j	        pd          }|
                    t	          |j        dk     r|j        ||         z   n|j        |j        dk     r|j        ||         z   n|j        |j	                             t          |t                    r'|
                    |dk     r|||         z   n|           t          d| d          t          |          S )ab  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  Z   K   | ]&}t          |t          t                              V  'd S r
   )r   typeEllipsis)r   r   s     r   r   z_multi_index.<locals>.<genexpr>  s2      
:
:Q:ah((
:
:
:
:
:
:r   z*Ellipsis index currently is not supported.r   Nr   zNot supported index type .)r   r   anyr   rz   r   	enumeraterr   rs   rt   appendrp   	TypeErrorr   )r(   r   positive_indexesr   r   s        r   r   r     s   ( $GX66FggWJG

:
:'
:
:
::: GEFFFq$--/3u::G3LMMGg&& B B5eU## 	B q%*"8a%*/ E ##.3kAooEK%(**5;-2Z!^^EJq)) J     s## 	B##		EE!H$4$4uMMMM@@@@AAA!"""r   .r   r   r   
batch_axis
int | Noner   c                    d S r
   r[   r   r   r   s      r   jacobianr     s	    
 sr   Sequence[Tensor] tuple[tuple[Jacobian, ...], ...]c                    d S r
   r[   r   s      r   r   r     s	    
 (+sr   tuple[Jacobian, ...]c                    d S r
   r[   r   s      r   r   r     	    
 3r   c                    d S r
   r[   r   s      r   r   r     r   r   c                    ||dk    rt          d| d          |dut           t                    r2t          t                    rt          fd D                       }nt           t                    r2t          t                    st          fd D                       }nXt           t                    s2t          t                    rt           fdD                       }nt	                     }|S )a  
    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   K   | ] t          fd D                       V  !dS )c              3  :   K   | ]}t          |          V  d S r
   r   )r   rd   re   r   s     r   r   z%jacobian.<locals>.<genexpr>.<genexpr>>  s/      ??S(3Z00??????r   N)r   r   re   r   r   s    @r   r   zjacobian.<locals>.<genexpr>=  sU       
 
DGE?????B?????
 
 
 
 
 
r   c              3  :   K   | ]}t          |          V  d S r
   r   r   s     r   r   zjacobian.<locals>.<genexpr>A  s/      FFC(3J77FFFFFFr   c              3  :   K   | ]}t          |          V  d S r
   r   )r   rd   r   r   s     r   r   zjacobian.<locals>.<genexpr>C  s/      FFC(2sJ77FFFFFFr   )r   r   r   r   r   )r   r   r   r    r   s   ``  @r   r   r     sN   R *//DzDDD
 
 	

 4'J"h 	1Jr8$<$< 	1 
 
 
 
 
KM
 
 
 
 
		 
B	!	! 1*R*B*B 1FFFFF2FFFFF		H%% 1*R*B*B 1FFFFF2FFFFF		RZ00	r   c                    d S r
   r[   r   s      r   hessianr   J  s	    
 cr   tuple[tuple[Hessian, ...], ...]c                    d S r
   r[   r   s      r   r   r   R  s	    
 '*cr   c                r   S|                                  dk    r%t          d|                                   d          |                     d          } nt          t                    rn| d                                          dk    r%t          d|                                   d          dk    rt          d	          |                     d
          } n t          dt                     d          t          |           }t          t                    st          |          }t          |_	        nxt          fd|D                       }t          t          |                    D ]?}t          t          |d                             D ]}t          ||         |         _	        @|S )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])
    Nr   zOnly support ys.numel()(z)==1 when batch_axis is None.r[   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  :   K   | ]}t          |          V  d S r
   )r   )r   _jr   r   s     r   r   zhessian.<locals>.<genexpr>  s/      IIR44IIIIIIr   )numelr   rf   r   rp   r   r   r   r]   r   r   rq   r   )r   r   r   r    r   r   js    ``    r   r   r   Z  s   J 88::>>T288::TTT   ZZ^^	J	$	$ 
a5;;==1UbhhjjUUU   ??=>>>ZZLj9I9ILLL
 
 	
 R,,Ib(## 29b*55 $IIIIIyIIIII s7||$$ 	2 	2A3wqz??++ 2 2*1
1''2 Nr   c                    | "t          j                  } j        | _        | S t          | t                    r(t          fdt          |           D                       S | S )Nc              3  J   K   | ]\  }}t          ||                   V  d S r
   )_replace_none_with_zero_tensor)r   r   r   refss      r   r   z1_replace_none_with_zero_tensor.<locals>.<genexpr>  sG       
 
;?1a*1d1g66
 
 
 
 
 
r   )r   
zeros_likestop_gradientr   r   r   r   )r   r   s    `r   r   r     s    	zt$$-		B	!	!  
 
 
 
CLR==
 
 
 
 
 	
 	r   c                   t          j                    rnt          j        | ||dd          }t          |t           j        j        j                  r0t          |t                    rt          |          dk    r|d         }nkt           j	        
                    | ||          }t          |t
          j                  r0t          |t                    rt          |          dk    r|d         }t          ||          S )ak  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  ! +b"adNNNr6;09::	!7H--	! Gq  ajG-))"b!44r9-..	!7H--	! Gq  ajG)'2666r   ).)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r
   )r   r   r   r   r   r   r   r]   )r   r   r   r   r   r   r   r   )
__future__r   collections.abcr   typingr   r   r   paddle.baser   r   r   r   r]   r_   r   r!   r   r   r   r   r   r[   r   r   <module>r      s   # " " " " " $ $ $ $ $ $ * * * * * * * *  ! ! ! ! ! !   [ [ [ [ [ [ [ [|	 	 	 	 	h 	 	 	I I I I I I I IX"
 "
 "
 "
 "
y "
 "
 "
J#
 #
 #
 #
 #
) #
 #
 #
L-# -# -#` 
 !    
 
 !+ + + + 
+ 
 !    
 
 !    
 [ [ [ [| 
 !    
 
 !* * * * 
* g g g gT
 
 
67 67 67 67 67 67r   