o
    "j_                     @   s   d dl Z d dlZd dlmZ d dlmZmZ d$ddZd$ddZdd	 Z	d
d Z
G dd dZG dd dZG dd dZG dd deZG dd deZdd Zdd Zd$ddZdd Zdd Zd$d d!Zd"d# ZdS )%    N)	framework)primapiutilsc                 C   sd   t | || t st st|t|}}t|tjr!| | n| |}t	|| |t
|||fS )a  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 invovled
            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typingSequence_check_v_shape_gradfuncxsvys r   d/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/incubate/autograd/functional.pyvjp   s   .
r   c                 C   s   t | || t st st|t|}}t|tjr!| | n| |}t	|| t s;t r;|t
|||fS |t|||fS )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 invovled
            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   Zforward_grad_double_backward_trickr   r   r   r   jvpP   s   1
r   c                 C   s    t | }t| ||}t|||S )zDouble 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   Zys_gradxs_gradr   r   r   r      s   r   c                 C   sL   t | tjst| }d|_|S g }| D ]}t|}d|_|| q|S )zaCreate a zero or zeros sequence Tensor like ``xs`` with a flag
    ``stop_graident=False`` .
    F)r	   r
   r   paddle
zeros_likestop_gradientappend)r   r   xyr   r   r   r      s   

r   c                   @   .   e Zd ZdZd
ddZdd Zedd Zd	S )Jacobiana?
  
    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:

        Eclipsis 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.])

    Fc                 C   s$   |s
t ||| _d S t||| _d S N)_JacobianNoBatch	_jacobian_JacobianBatchFirst)selfr   r   
is_batchedr   r   r   __init__   s   zJacobian.__init__c                 C   
   | j | S r"   )r$   r&   indexesr   r   r   __getitem__      
zJacobian.__getitem__c                 C      | j jS )z'The shape of flattened Jacobian matrix.)r$   shaper&   r   r   r   r/         zJacobian.shapeNF__name__
__module____qualname____doc__r(   r,   propertyr/   r   r   r   r   r!      s    
Gr!   c                   @   r    )Hessiana  
    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.]])

    Fc                    s"    fdd}t ||d| _d S )Nc                     sd   t  | d}r|jd dkss|jd dkrtdr*|d d dd d f S |dd d f S )Nr'      r   zeThe function given to Hessian shoud return as single element Tensor or batched single element Tensor.)r!   r/   RuntimeError)r   Zjacr   r'   r   r   	_jac_func2  s   *z#Hessian.__init__.<locals>._jac_funcr:   )r!   symbolic)r&   r   r   r'   r>   r   r=   r   r(   1  s   
zHessian.__init__c                 C   r)   r"   )r?   r*   r   r   r   r,   >  r-   zHessian.__getitem__c                 C   r.   )z&The shape of flattened Hessian matrix.)r?   r/   r0   r   r   r   r/   A  r1   zHessian.shapeNr2   r3   r   r   r   r   r9     s    
/r9   c                   @   sb   e Zd ZdZdd Zedd Zedd Zdd	 Zd
d Z	dddZ
dd Zdd Zdd ZdS )	_Jacobiana  The base class for computing Jacobian matrix.

    ``_Jacobian`` implementes 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                 C   sf   t  st r|| _nt|| _|t| j | _| t| j| _	| t| j| _
i | _d S r"   )r   r   r   r   _xsr   
as_tensorsZ_ys_flatten_flatten_xs_flatten_ys_cacher&   r   r   r   r   r   r(   \  s   

z_Jacobian.__init__c                 C      t r"   NotImplementedErrorr0   r   r   r   r/   h     z_Jacobian.shapec                 C   rH   )z "The axis of lazily evaluated.rI   r0   r   r   r   
_lazy_axisl  s   z_Jacobian._lazy_axisc                 C   s0   || j  }t|tr|fS tt|j|j|jS r"   )rL   r	   inttuplerangestartstopstep)r&   r+   idxr   r   r   _lazy_indexesq  s   
z_Jacobian._lazy_indexesc                 C   rH   r"   rI   r&   r   r   r   r   rC   y  s   z_Jacobian._flattenr   c                 C   sJ   || j  }t|trdntd|d}|d | j  |f || j d d   S Nr   r;   )rL   r	   rM   slice)r&   r+   Zlazy_axis_sizerS   Zshifted_lazy_axis_idxr   r   r   _shifted_indexes|  s   
z_Jacobian._shifted_indexesc                    s   t | j}t| j tr(|d  j | jd d   } | j | S  |}t j}t|| j< t	j
 fdd|D  jd|}| |t| S )Nr;   c                    s   g | ]}  |qS r   )_cached_evaluate.0ir0   r   r   
<listcomp>  s    z)_Jacobian.__getitem__.<locals>.<listcomp>)Zaxis)_multi_indexr/   r	   rL   rM   rY   rT   listlenr   concatreshaperX   )r&   r+   Zother_indexesZlazy_indexesr/   Zpart_jacr   r0   r   r,     s"   

z_Jacobian.__getitem__c                 C   s,   | j |}|d u r| |}|| j |< |S r"   )rF   get	_evaluate)r&   kr   r   r   r   rY     s
   

z_Jacobian._cached_evaluatec                 C   rH   )z&Evaluate one slice at along lazy axis.rI   )r&   indexr   r   r   rd     rK   z_Jacobian._evaluateN)r   )r4   r5   r6   r7   r(   r8   r/   rL   rT   rC   rX   r,   rY   rd   r   r   r   r   r@   G  s    


r@   c                       H   e Zd ZdZ fddZedd Zedd Zdd	 Zd
d Z	  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                       t  || d S r"   superr(   rG   	__class__r   r   r(        z_JacobianNoBatch.__init__c                 C   s   | j jd | jjd fS Nr   )rE   r/   rD   r0   r   r   r   r/     s   z_JacobianNoBatch.shapec                 C      dS rn   r   r0   r   r   r   rL     rK   z_JacobianNoBatch._lazy_axisc                 C   s   t tdd |D S )Nc                 s   s    | ]}| d V  qdS ))N)rb   r[   r   r   r   r   	<genexpr>  s    z,_JacobianNoBatch._flatten.<locals>.<genexpr>)r   ra   rN   rU   r   r   r   rC     s   z_JacobianNoBatch._flattenc                 C   s   |  t| j| | jS r"   rC   r   rE   rA   r&   Z	row_indexr   r   r   rd     s   z_JacobianNoBatch._evaluater4   r5   r6   r7   r(   r8   r/   rL   rC   rd   __classcell__r   r   rk   r   r#     s    

r#   c                       rg   )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                    rh   r"   ri   rG   rk   r   r   r(     rm   z_JacobianBatchFirst.__init__c                 C   s"   | j jd | jjd | j jd fS rV   )rD   r/   rE   r0   r   r   r   r/     s   


z_JacobianBatchFirst.shapec                 C   ro   )Nr;   r   r0   r   r   r   rL     rK   z_JacobianBatchFirst._lazy_axisc                 C   s    t tdd t|D dS )Nc                 s   s$    | ]}| |jd  dfV  qdS )r   rp   N)rb   r/   rq   r   r   r   rr     s   " z/_JacobianBatchFirst._flatten.<locals>.<genexpr>r;   )r   ra   rN   r   rB   rU   r   r   r   rC     s   z_JacobianBatchFirst._flattenc                 C   s    |  t| jd d |f | jS r"   rs   rt   r   r   r   rd     s    z_JacobianBatchFirst._evaluateru   r   r   rk   r   r%     s    

r%   c                 C   s  t | tjr| n| f} tdd | D rtd| tdddft|t|    } g }t| D ][\}}t |trnt|jp=d|j	pC|| |j
pGd}|t|jdk rX|j||  n|j|j	dk rf|j	||  n|j	|j
 q/t |tr||dk r|||  n| q/td| dt|S )	aa  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
            omited.

    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                 s   s    | ]
}t |ttV  qd S r"   )r	   typeEllipsisrZ   r   r   r   rr     s    z_multi_index.<locals>.<genexpr>z*Ellipsis index currently is not supported.r   Nr;   zNot supported index type .)r	   r
   r   any
IndexErrorrW   r`   	enumeraterP   rQ   rR   r   rM   	TypeErrorrN   )r+   r/   Zpositive_indexesr\   rf   r   r   r   r^     s*   "

	 r^   c                    sH   | d u rt  }  j| _| S t| tjr"t fddt| D S | S )Nc                 3   s"    | ]\}}t | | V  qd S r"   )_replace_none_with_zero_tensor)r[   r\   r   refsr   r   rr     s    
z1_replace_none_with_zero_tensor.<locals>.<genexpr>)r   r   r   r	   r
   r   rN   r|   )r   r   r   r   r   r~     s   
r~   c                 C   sj   t  r'tj| ||ddd}t|tjj jr&t|tjr&t	|dkr&|d }n	tj
j| ||}t||S )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)Zcreate_graphZallow_unusedr   )r   r   r   Zgradr	   baseVariabler
   r   r`   ZincubateZautogradr~   )r   r   r   r   r   r   r   r      s   #

r   c                 C   s&   t | tjrtdd | D S t| S )a  
    ``_separate`` separates ``xs`` from the computation graph through ``clone``
    or ``deteach`` .

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

    However, funcional 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                 s   s    | ]}t |V  qd S r"   )_single_separaterq   r   r   r   rr     s    z_separate.<locals>.<genexpr>)r	   r
   r   rN   r   )r   r   r   r   r   S  s   ,r   c                 C   s.   | d u r| S | j st| S |  } d| _ | S )NF)r   r   Zassigndetach)r   r   r   r   r     s   
r   c                 C   s   t | stdt|  dt|tjtjfs!tdt| dt|tjr4tdd |D s4tdt|tjtjtd fsJtdt| dt|tjr]tdd |D s_tdd S d S )	Nz$Expected 'fun' is Callable, but got ry   z3Expected 'xs' is a Tensor|Sequence[Tensor],but got c                 s       | ]	}t |tjV  qd S r"   r	   r   r   rq   r   r   r   rr         
z _check_inputs.<locals>.<genexpr>z&All elements of 'xs' shoule be Tensor.z6Expected 'v' is Tensor|Sequence[Tensor]|None, but got c                 s   r   r"   r   )r[   er   r   r   rr     r   )	callabler}   rw   r	   r   r   r
   r   all)r   r   r   r   r   r   r     s*   r   c              	   C   s   | d u rd S t | t |} }t|t| kr(tdt| dt|  dtt| |D ]\}\}}|j|jkrKtd| d|j d|j dq/d S )Nz6The argument v is a tuple of invalid length:should be z	 but got ry   zThe v[z] has invalid shape: should be )r   rB   r`   r<   r|   zipr/   )r   r   rf   Z	element_vZelement_refr   r   r   r     s,   r   r"   )r
   r   Zpaddle.baser   Zpaddle.incubate.autogradr   r   r   r   r   r   r!   r9   r@   r#   r%   r^   r~   r   r   r   r   r   r   r   r   r   <module>   s(   

:?WFa0
32
