
    ϑi!e                       S SK Jr  S SKrS SKJrJrJrJr  S SKrS SKJ	r	  S SK
JrJr  \(       a!  S SKJr  S SKJr  S SKJr  \" S	\\\S
4   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 r " S S5      r " S S5      r " S S5      r " S S\5      r " S S\5      rS rS rS$S jrS  r S! r!S$S" jr"S# r#g)'    )annotationsN)TYPE_CHECKINGCallableTypeVaroverload)	framework)primapiutils)Sequence)Tensor)TensorOrTensors_OutputT.c                    g N funcxsvs      c/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/incubate/autograd/functional.pyvjpr   !       
 "    c                    g r   r   r   s      r   r   r   )       
 +.r   c                6   [        XU5        [        R                  " 5       (       d  [        R                  " 5       (       d  [        U5      [        U5      p![        U[        R                  5      (       a  U " U6 OU " U5      n[        X#5        U[        X1U5      4$ )aV  Computes the Vector-Jacobian product, a functional form of
reverse mode automatic differentiation.

Warning:
    This API is in beta, the signatures could be changed in future version.

Args:
    func(Callable): A function that takes ``xs`` as inputs parameter and
        returns a sequence of Tensors or a Tensor.
    xs(Tensor|Sequence[Tensor]): Used as positional arguments to evaluate
        ``func``. ``xs`` is accepted as one Tensor or a sequence of Tensors.
    v(Tensor|Sequence[Tensor]|None, optional): The cotangent vector involved
        in the VJP computation. ``v`` matches the size and shape of
        ``func`` 's output. Defaults to None, which is equivalent to all
        ones the same size of ``func`` 's output.

Returns:
    output(tuple):

        - func_out(Tensor|tuple[Tensor]): The output of ``func(xs)`` .
        - vjp(Tensor|tuple[Tensor]): The vjp result.

Examples:

    .. code-block:: python

        >>> import paddle

        >>> def func(x):
        ...     return paddle.matmul(x, x)
        ...
        >>> x = paddle.ones(shape=[2, 2], dtype='float32')
        >>> _, vjp_result = paddle.incubate.autograd.vjp(func, x)
        >>> print(vjp_result)
        Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
               [[4., 4.],
                [4., 4.]])

        >>> v = paddle.to_tensor([[1.0, 0.0], [0.0, 0.0]])
        >>> _, vjp_result = paddle.incubate.autograd.vjp(func, x, v)
        >>> print(vjp_result)
        Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
               [[2., 1.],
                [1., 0.]])
)_check_inputsr   in_dygraph_moder
   prim_enabled	_separate
isinstancetypingr   _check_v_shape_gradr   r   r   yss       r   r   r   1   sv    \ $A   ""%*<*<*>*>"y|A V__55r48B1uRQr   c                    g r   r   r   s      r   jvpr(   k   r   r   c                    g r   r   r   s      r   r(   r(   s   r   r   c                   [        XU5        [        R                  " 5       (       d  [        R                  " 5       (       d  [        U5      [        U5      p![        U[        R                  5      (       a  U " U6 OU " U5      n[        X!5        [        R                  " 5       (       d3  [        R                  " 5       (       a  U[        R                  " X1U5      4$ U[        X1U5      4$ )a  
Computes the Jacobian-Vector product for a function at the given
inputs and a vector in the tangent space induced by the inputs.

Warning:
    This API is in beta, the signatures could be changed in future version.

Args:
    func(Callable): The ``func`` takes as input a Tensor or a Sequence
        of Tensors and returns a Tensor or a Sequence of Tensors.
    xs(Tensor|Sequence[Tensor]): Used as positional arguments to
        evaluate ``func``.  The ``xs`` is accepted as one Tensor or a
        Sequence of Tensors.
    v(Tensor|Sequence[Tensor]|None, Optional): The tangent vector involved
        in the JVP computation. The ``v`` matches the size and shape of
        ``xs`` . Default value is None and in this case is equivalent to
        all ones the same size of ``xs`` .

Returns:
    output(tuple):

        - func_out(Tensor|tuple[Tensor]): The output of ``func(xs)`` .
        - jvp(Tensor|tuple[Tensor]): The jvp result.

Examples:

    .. code-block:: python

        >>> import paddle

        >>> def func(x):
        ...     return paddle.matmul(x, x)
        ...
        >>> x = paddle.ones(shape=[2, 2], dtype='float32')
        >>> _, jvp_result = paddle.incubate.autograd.jvp(func, x)
        >>> print(jvp_result)
        Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False,
               [[4., 4.],
                [4., 4.]])

        >>> v = paddle.to_tensor([[1.0, 0.0], [0.0, 0.0]])
        >>> _, jvp_result = paddle.incubate.autograd.jvp(func, x, v)
        >>> print(jvp_result)
        Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False,
               [[2., 1.],
                [1., 0.]])

)r   r   r   r
   r   r    r!   r"   r   r#   r	   forward_grad_double_backward_trickr%   s       r   r(   r(   {   s    b $A   ""%*<*<*>*>"y|A V__55r48B1$$&&5+=+=+?+?7''222)"!444r   c                H    [        U 5      n[        XU5      n[        XCU5      $ )zzDouble backward trick for computing ``jvp`` by ``vjp``
see details: https://j-towns.github.io/2017/06/12/A-new-trick.html
)_zeros_like_with_gradr$   )r&   r   r   ys_gradxs_grads        r   r,   r,      s'     $B'GBG$G1%%r   c                    [        U [        R                  5      (       d  [        R                  " U 5      nSUl        U$ / nU  H1  n[        R                  " U5      nSUl        UR                  U5        M3     U$ )zYCreate a zero or zeros sequence Tensor like ``xs`` with a flag
``stop_gradient=False`` .
F)r!   r"   r   paddle
zeros_likestop_gradientappend)r   r&   xys       r   r.   r.      sn     b&//**r"  I A!!!$A#AOIIaL  Ir   c                  \    \ rS rSrSr S       S	S jjr    S
S jr\SS j5       rSr	g)Jacobian   ao	  
Computes the Jacobian matrix of a given function.

If the function has multiple inputs and multiple outputs, during internal
implementation, all input tensors are concatenated after being flatten,
the batch dimension is retained, and the output is subject to the same
processing rules.

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.

For examples, supposing ``is_batched=True``, 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.

Warning:
    This API is in beta, the signatures could be changed in future version.

Args:

    func (Callable): A python function that takes a Tensor or a sequence of
        Tensors as inputs(the first dimension is batch size) and
        returns a Tensor  a sequence of Tensors.
    xs (Tensor|Sequence[Tensor]): The input to the function ``func`` .
    is_batched (bool): If true, the first axis is batch axis. Defaults to
        False.

Returns:

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

Examples:

    .. code-block:: python

        >>> import paddle

        >>> def func(x, y):
        ...     return paddle.matmul(x, y)
        ...
        >>> x = paddle.to_tensor([[1., 2.], [3., 4.]])
        >>> J = paddle.incubate.autograd.Jacobian(func, [x, x])
        >>> print(J[:, :])
        Tensor(shape=[4, 8], dtype=float32, place=Place(cpu), stop_gradient=False,
               [[1., 3., 0., 0., 1., 0., 2., 0.],
                [2., 4., 0., 0., 0., 1., 0., 2.],
                [0., 0., 1., 3., 3., 0., 4., 0.],
                [0., 0., 2., 4., 0., 3., 0., 4.]])

        >>> print(J[0, :])
        Tensor(shape=[8], dtype=float32, place=Place(cpu), stop_gradient=False,
               [1., 3., 0., 0., 1., 0., 2., 0.])
        >>> print(J[:, 0])
        Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=False,
               [1., 2., 0., 0.])

c                T    U(       d  [        X5      U l        g [        X5      U l        g r   )_JacobianNoBatch	_jacobian_JacobianBatchFirst)selfr   r   
is_batcheds       r   __init__Jacobian.__init__  s     -d7DN0:DNr   c                     U R                   U   $ r   r=   r?   indexess     r   __getitem__Jacobian.__getitem__(  s     ~~g&&r   c                .    U R                   R                  $ )z'The shape of flattened Jacobian matrix.)r=   shaper?   s    r   rJ   Jacobian.shape-  s     ~~###r   rD   NFr   zCallable[..., TensorOrTensors]r   r   r@   boolreturnNone)rF   z%int | slice | tuple[int | slice, ...]rP   r   rP   z	list[int])
__name__
__module____qualname____firstlineno____doc__rA   rG   propertyrJ   __static_attributes__r   r   r   r9   r9      sb    EV !		;,	; 	; 		;
 
	;'<'	'
 $ $r   r9   c                  `    \ rS rSr% SrS\S'    S
       SS jjrSS jr\SS j5       r	Sr
g	)Hessiani3  av  
Computes the Hessian matrix  with a given ``func`` with respect to ``xs`` .

If the function has multiple inputs, during internal implementation,
all input tensors are concatenated after being flatten, the batch dimension
is retained.

The Hessian submatrix is lazily evaluated, and can be retrieved with a
multidimensional indexes. See details ``Jacobian`` .

Warning:
    This API is in beta, the signatures could be changed in future version.

Args:
    func (Callable): A python function that takes a Tensor or a Tensor
        sequence as inputs and returns a Tensor with shape
        ``[batch_size, 1]`` with batch or ``[1]`` without batch.
    xs (Tensor|Sequence(Tensor)): The input Tensor or Tensor sequence of
        the function ``func``.
    is_batched (bool): If true, the first axis is batch axis. Defaults to
        False.

Returns:

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


Examples:

    .. code-block:: python

        >>> import paddle

        >>> def reducer(x):
        ...     return paddle.sum(x * x)
        ...
        >>> x = paddle.rand([2, 2])
        >>> h = paddle.incubate.autograd.Hessian(reducer, x)
        >>> print(h[:])
        Tensor(shape=[4, 4], dtype=float32, place=CPUPlace(), stop_gradient=False,
            [[2., 0., 0., 0.],
             [0., 2., 0., 0.],
             [0., 0., 2., 0.],
             [0., 0., 0., 2.]])

r9   symbolicc                4   ^^ UU4S jn[        XBTS9U l        g )Nc                    > [        TU TS9nT(       a  UR                  S   S:w  d  T(       d  UR                  S   S:w  a  [        S5      eT(       a  US S 2SS S 24   $ USS S 24   $ )Nr@      r   zfThe function given to Hessian should return as single element Tensor or batched single element Tensor.)r9   rJ   RuntimeError)r   jacr   r@   s     r   	_jac_func#Hessian.__init__.<locals>._jac_funck  sf    4
;Csyy|q0399Q<1#4"|  $.3q!Qw<<3q!t9<r   r_   )r9   r\   )r?   r   r   r@   rc   s    ` ` r   rA   Hessian.__init__e  s    	= !:Fr   c                     U R                   U   $ r   r\   rE   s     r   rG   Hessian.__getitem__w  s    }}W%%r   c                .    U R                   R                  $ )z&The shape of flattened Hessian matrix.)r\   rJ   rK   s    r   rJ   Hessian.shapez  s     }}"""r   rg   NrM   rN   )rF   zint | slicerP   r   rR   )rS   rT   rU   rV   rW   __annotations__rA   rG   rX   rJ   rY   r   r   r   r[   r[   3  s^    -^  !	G,G G 	G
 
G$& # #r   r[   c                  f    \ rS rSrSrS r\S 5       r\S 5       rS r	S r
SS jrS	 rS
 rS rSrg)	_Jacobiani  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                   [         R                  " 5       (       d!  [        R                  " 5       (       a  X l        O[        U5      U l        U" [        R                  " U R                  5      6 U l        U R                  [        R                  " U R                  5      5      U l	        U R                  [        R                  " U R                  5      5      U l
        0 U l        g r   )r   r   r
   r   _xsr    
as_tensors_ys_flatten_flatten_xs_flatten_ys_cache)r?   r   r   s      r   rA   _Jacobian.__init__  s     ((**u/A/A/C/CH }DH))$((34==)9)9$(()CD==)9)9$(()CDr   c                    [         er   NotImplementedErrorrK   s    r   rJ   _Jacobian.shape      !!r   c                    [         e)z"The axis of lazily evaluated.rx   rK   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!   inttuplerangestartstopstep)r?   rF   idxs      r   _lazy_indexes_Jacobian._lazy_indexes  sM    oo& #s## F	
 uSYY#((;<	
r   c                    [         er   rx   r?   r   s     r   rr   _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?   rF   lazy_axis_sizer   shifted_lazy_axis_idxs        r   _shifted_indexes_Jacobian._shifted_indexes  sl    oo&C%%A5NA+F 	
&t'
!
 __q(*+
 	
r   c                H   [        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         $ s  snf )Nr`   )axis)_multi_indexrJ   r!   r}   r   _cached_evaluater   listlenr2   concatreshaper   )r?   rF   other_indexeslazy_indexesrJ   ipart_jacs          r   rG   _Jacobian.__getitem__  s   w

3goo.44)$//*W__q5H5J-KK  (()AB  ))'2 TZZ !$\!2oo==/;<|!""1%|<
 '%. 	 --gs<7HIJJ =s   	Dc                    U R                   R                  U5      nUc  U R                  U5      nX R                   U'   U$ r   )ru   get	_evaluate)r?   kr   s      r   r   _Jacobian._cached_evaluate  s7    KKOOA9q!AKKNr   c                    [         e)z&Evaluate one slice at along lazy axis.rx   )r?   indexs     r   r   _Jacobian._evaluate  r{   r   )ru   rs   rt   ro   rq   N)r   )rS   rT   rU   rV   rW   rA   rX   rJ   r}   r   rr   r   rG   r   r   rY   r   r   r   rm   rm     sS    (
 " " " "
"	
K*"r   rm   c                  X   ^  \ rS rSrSrU 4S jr\S 5       r\S 5       rS r	S r
SrU =r$ )	r<   i  zCompute Jacobian matrix without batch dimension.
Suppose the mapping is :math:`f: R^M        o R^N`, the output shape is
``(N, M)`` .
c                $   > [         TU ]  X5        g r   superrA   r?   r   r   	__class__s      r   rA   _JacobianNoBatch.__init__      "r   c                f    U R                   R                  S   U R                  R                  S   4$ Nr   )rt   rJ   rs   rK   s    r   rJ   _JacobianNoBatch.shape  s/      &&q)4+;+;+A+A!+DEEr   c                    gr   r   rK   s    r   r}   _JacobianNoBatch._lazy_axis      r   c                N    [         R                  " [        S U 5       5      5      $ )Nc              3  B   #    U  H  oR                  S 5      v   M     g7f))N)r   .0r6   s     r   	<genexpr>,_JacobianNoBatch._flatten.<locals>.<genexpr>  s     "@R99U#3#3Rs   )r2   r   r   r   s     r   rr   _JacobianNoBatch._flatten  s    }}U"@R"@@AAr   c                f    U R                  [        U R                  U   U R                  5      5      $ r   rr   r$   rt   ro   r?   	row_indexs     r   r   _JacobianNoBatch._evaluate  s0    }}  +
 	
r   r   rS   rT   rU   rV   rW   rA   rX   rJ   r}   rr   r   rY   __classcell__r   s   @r   r<   r<     sG    
# F F  B
 
r   r<   c                  X   ^  \ rS rSrSrU 4S jr\S 5       r\S 5       rS r	S r
SrU =r$ )	r>   i  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                $   > [         TU ]  X5        g r   r   r   s      r   rA   _JacobianBatchFirst.__init__  r   r   c                    U R                   R                  S   U R                  R                  S   U R                   R                  S   4$ r   )rs   rJ   rt   rK   s    r   rJ   _JacobianBatchFirst.shape  sJ     ""1%""1%""1%
 	
r   c                    g)Nr`   r   rK   s    r   r}   _JacobianBatchFirst._lazy_axis  r   r   c                x    [         R                  " [        S [        R                  " U5       5       5      S5      $ )Nc              3  `   #    U  H$  oR                  UR                  S    S45      v   M&     g7f)r   r   N)r   rJ   r   s     r   r   /_JacobianBatchFirst._flatten.<locals>.<genexpr>  s)     L7K!))QWWQZ,--7Ks   ,.r`   )r2   r   r   r
   rp   r   s     r   rr   _JacobianBatchFirst._flatten  s.    }}Lu7G7G7KLLa
 	
r   c                n    U R                  [        U R                  S S 2U4   U R                  5      5      $ r   r   r   s     r   r   _JacobianBatchFirst._evaluate  s+    }}U4#3#3AyL#A488LMMr   r   r   r   s   @r   r>   r>     sF    
# 
 
  

N Nr   r>   c           	     `   [        U [        R                  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>1  s     
:'Q:ah(('s   &(z*Ellipsis index currently is not supported.r   Nr`   zNot supported index type .)r!   r"   r   any
IndexErrorr   r   	enumerater   r   r   r5   r   	TypeErrorr   )rF   rJ   positive_indexesr   r   s        r   r   r     s_   ( $GV__==gG:G

:'
:::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                   ^ U c)  [         R                  " T5      n TR                  U l        U $ [        U [        R
                  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   r6   refss      r   r   1_replace_none_with_zero_tensor.<locals>.<genexpr>R  s%      
CP41*1d1g66=s   !)r2   r3   r4   r!   r"   r   r   r   )r   r   s    `r   r   r   L  sa    	zt$--		B	(	( 
CLR=
 
 	
 	r   c                   [         R                  " 5       (       a  [        R                  " XUSSS9n[	        U[        R
                  R                   R                  [        R                  R                  45      (       a3  [	        U[        R                  5      (       a  [        U5      S:  a  US   nO*[        R                  R                  R                  XU5      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 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   r   r2   gradr!   baseVariablepirValuer"   r   r   incubateautogradr   )r&   r   r   r0   s       r   r$   r$   Y  s    F   "" ++badNrFKK11::FJJ<L<LMNN7FOO44Gq ajG//**//:)'66r   c                z    [        U [        R                  5      (       a  [        S U  5       5      $ [	        U 5      $ )aO  
``_separate`` separates ``xs`` from the computation graph through ``clone``
or ``detach`` .

Internally, ``paddle.grad(xs, ys)`` is stateful API implemented based on
computational graph, which will reduce gradients along all path from ys to xs.

However, functional autograd API such as ``vjp``, ``jvp`` is stateless, and
only compute gradients with a given ``func`` .

For example, given a ``func`` :math:`y0=f(x0)`, supposing forward path is:
``x0 -> y0``, ``x0 -> x1 -> y0`` .
``paddle.grad(y0, x0)`` will reduce gradients along ``y0->x0`` and
``y0->x1->x0``, and ``vjp`` only need reduce along ``y0->x0``.

So, it's needed to clone or detach xs for breaking the dependencies with
other variables.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.incubate.autograd.functional import _separate

        >>> def func(x, y):
        ...     return x * y
        ...
        >>> x = paddle.ones((1,))
        >>> x.stop_gradient = False

        >>> y = func(x, x)
        >>> print(paddle.grad(y, x))
        [Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True,
               [2.])]

        >>> x1, x2 = _separate((x, x))
        >>> y = func(x1, x2)
        >>> print(paddle.grad(y, x1))
        [Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True,
               [1.])]

c              3  8   #    U  H  n[        U5      v   M     g 7fr   )_single_separater   s     r   r   _separate.<locals>.<genexpr>  s     5"Q%a(("s   )r!   r"   r   r   r   )r   s    r   r    r      s2    X "foo&&5"555##r   c                    U c  U $ U R                   (       d  [        R                  " U 5      $ U R                  5       n SU l         U $ )NF)r4   r2   assigndetach)r6   s    r   r   r     s9    y??}}QHHJr   c                   [        U 5      (       d  [        S[        U 5       S35      e[        U[        R
                  [        R                  [        R                  R                  45      (       d  [        S[        U5       S35      e[        U[        R                  5      (       a"  [        S U 5       5      (       d  [        S5      e[        U[        R
                  [        R                  [        S 5      [        R                  R                  45      (       d  [        S[        U5       S35      e[        U[        R                  5      (       a#  [        S U 5       5      (       d  [        S5      eg g )Nz$Expected 'fun' is Callable, but got r   z4Expected 'xs' is a Tensor|Sequence[Tensor], but got c              3     #    U  H9  n[        U[        R                  [        R                  R
                  45      v   M;     g 7fr   r!   r   r   r2   r   r   r   s     r   r    _check_inputs.<locals>.<genexpr>  s2      3GI!
1y))6::+;+;<==r   AAz&All elements of 'xs' should be Tensor.z6Expected 'v' is Tensor|Sequence[Tensor]|None, but got c              3     #    U  H9  n[        U[        R                  [        R                  R
                  45      v   M;     g 7fr   r   )r   es     r   r   r     s2      2GH!
1y))6::+;+;<==qr   )callabler   r   r!   r   r   r"   r   r2   r   r   allr   s      r   r   r     s>   D>>>tDzl!LMM
Y&**2B2BC  B48*AN
 	
 "foo&&s 3GI3 0 0 @AA	IdVZZ=M=MN  DT!WIQO
 	
 !V__%%c 2GH2 / / @AA/%r   c           
        U c  g [         R                  " U 5      [         R                  " U5      p[        U5      [        U 5      :w  a$  [        S[        U5       S[        U 5       S35      e[	        [        X5      5       HK  u  nu  p4UR                  UR                  :w  d  M$  [        SU SUR                   SUR                   S35      e   g )Nz6The argument v is a tuple of invalid length:should be z	 but got r   zThe v[z] has invalid shape: should be )r
   rp   r   ra   r   ziprJ   )r   r   r   	element_velement_refs        r   r#   r#     s    yq!5#3#3D#9t
4yCFT9SVHA7
 	

 ,5S\+B''	??k///  !''(	)//1B!E  ,Cr   r   )r   Callable[..., _OutputT]r   r   r   TensorOrTensors | NonerP   ztuple[_OutputT, Tensor])r   r  r   zSequence[Tensor]r   r  rP   z#tuple[_OutputT, tuple[Tensor, ...]])$
__future__r   r"   r   r   r   r   r2   paddle.baser   paddle.incubate.autogradr	   r
   collections.abcr   r   paddle._typingr   r   r   r   r(   r,   r.   r9   r[   rm   r<   r>   r   r   r$   r    r   r   r#   r   r   r   <module>r     s   #  = =  ! 3(.z65+=>H 
 !%"
!"" " 	" 
" 
 !%.
!.. . )	. 
.7 t 
 !%"
!"" " 	" 
" 
 !%.
!.. . )	. 
.<5~& [$ [$|J# J#Z^" ^"B
y 
:N) N<-#`
07f/$d	B8r   