U
    9%e                     @   s   d dl Z d dlmZ d dlmZ d dlZddlmZ dddd	d
dgZda	dd Z
ddddZdddd	ZedddgZG dd deZdddd
ZG dd deZejjZG dd deZdS )    N)
namedtuple)Any   )_DecoratorContextManagerUnpackedDualTensorenter_dual_levelexit_dual_level	make_dualunpack_dual
dual_levelc                  C   s&   t j } | td krtd| a| S )a  Function that can be used to enter a new forward grad level.
    This level can be used to make and unpack dual Tensors to compute
    forward gradients.

    This function also updates the current level that is used by default
    by the other functions in this API.
    r   zoEntering a new forward AD level but the current level is not valid. Make sure you did not modified it directly.)torch_CZ_enter_dual_level_current_levelRuntimeError)Z	new_level r   X/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/autograd/forward_ad.pyr      s    	
levelc                 C   s6   | dkrt } | t krtdtjj| d | d a dS )a-  Function that can be used to exit a forward grad level.
    This function deletes all the gradients associated with this
    level. Only deleting the latest entered level is allowed.

    This function also updates the current level that is used by default
    by the other functions in this API.
    NzdTrying to exit a forward AD level that was not the last one that was created. This is not supported.r   r   )r   r   r   r   Z_exit_dual_levelr   r   r   r   r   )   s    	c                C   s   t jdddkrddlm} |dkr*t}|dk r:td|  sZ|  sZt	d| j
 | sz| szt	d	|j
 tjj| ||d
S )a  Associates a tensor value with a forward gradient, the tangent, to create a
    "dual tensor", which is used to compute forward AD gradients.
    The result is a new tensor aliased to :attr:`tensor` with :attr:`tangent` embedded
    as an attribute as-is if it has the same storage layout or copied otherwise.
    The tangent attribute can be recovered with :func:`unpack_dual`.

    This function is backward differentiable.

    Given a function `f` whose jacobian is `J`, it allows one to compute the Jacobian-vector product (`jvp`)
    between `J` and a given vector `v` as follows.

    Example::

        >>> # xdoctest: +SKIP("Undefined variables")
        >>> with dual_level():
        ...     inp = make_dual(x, v)
        ...     out = f(inp)
        ...     y, jvp = unpack_dual(out)

    Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
    for detailed steps on how to use this API.

    ZPYTORCH_JIT1Tr   )decompositions_for_jvpNziTrying to create a dual Tensor for forward AD but no level exists, make sure to enter_dual_level() first.z:Expected primal to be floating point or complex, but got: z;Expected tangent to be floating point or complex, but got: r   )osenvirongetZtorch._decompr   r   r   Zis_floating_pointZ
is_complex
ValueErrorZdtyper   _VFZ
_make_dual)tensortangentr   r   r   r   r   r	   =   s"    (

_UnpackedDualTensorprimalr   c                   @   s   e Zd ZdZdS )r   zNamedtuple returned by :func:`unpack_dual` containing the primal and tangent components of the dual tensor.
    See :func:`unpack_dual` for more details.N)__name__
__module____qualname____doc__r   r   r   r   r      s   c                C   s<   |dkrt }|dk rt| dS tjj| |d\}}t||S )a  Unpacks a "dual tensor" to get both its Tensor value and its forward AD gradient.
    The result is a namedtuple ``(primal, tangent)`` where ``primal`` is a view of
    :attr:`tensor`'s primal and ``tangent`` is :attr:`tensor`'s tangent as-is.
    Neither of these tensors can be dual tensor of level :attr:`level`.

    This function is backward differentiable.

    Example::

        >>> # xdoctest: +SKIP("Undefined variables")
        >>> with dual_level():
        ...     inp = make_dual(x, x_t)
        ...     out = f(inp)
        ...     y, jvp = unpack_dual(out)
        ...     jvp = unpack_dual(out).tangent

    Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
    for detailed steps on how to use this API.
    Nr   r   )r   r   r   r   Z_unpack_dual)r   r   r   Zdualr   r   r   r
      s    
c                   @   s,   e Zd ZdZdd ZeeeddddZdS )r   a  Context-manager that enables forward AD. All forward AD computation must
    be performed in a ``dual_level`` context.

    .. Note::

        The ``dual_level`` context appropriately enters and exit the dual level to
        controls the current forward AD level, which is used by default by the other
        functions in this API.

        We currently don't plan to support nested ``dual_level`` contexts, however, so
        only a single forward AD level is supported. To compute higher-order
        forward grads, one can use :func:`torch.func.jvp`.

    Example::

        >>> # xdoctest: +SKIP("Undefined variables")
        >>> x = torch.tensor([1])
        >>> x_t = torch.tensor([1])
        >>> with dual_level():
        ...     inp = make_dual(x, x_t)
        ...     # Do computations with inp
        ...     out = your_fn(inp)
        ...     _, grad = unpack_dual(out)
        >>> grad is None
        False
        >>> # After exiting the level, the grad is deleted
        >>> _, grad_after = unpack_dual(out)
        >>> grad is None
        True

    Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
    for detailed steps on how to use this API.
    c                 C   s   t  S N)r   selfr   r   r   	__enter__   s    zdual_level.__enter__Nexc_type	exc_value	tracebackreturnc                 C   s
   t   d S r$   )r   r&   r)   r*   r+   r   r   r   __exit__   s    zdual_level.__exit__)r    r!   r"   r#   r'   r   r.   r   r   r   r   r      s   "c                   @   s>   e Zd ZeddddZddddZeeeddd	d
ZdS )_set_fwd_grad_enabledN)moder,   c                 C   s   t  | _tj| d S r$   )_is_fwd_grad_enabledprevr   r   r/   )r&   r0   r   r   r   __init__   s    z_set_fwd_grad_enabled.__init__)r,   c                 C   s   d S r$   r   r%   r   r   r   r'      s    z_set_fwd_grad_enabled.__enter__r(   c                 C   s   t j| j d S r$   )r   r   r/   r2   r-   r   r   r   r.      s    z_set_fwd_grad_enabled.__exit__)r    r!   r"   boolr3   r'   r   r.   r   r   r   r   r/      s   r/   )r   collectionsr   typingr   r   Z	grad_moder   __all__r   r   r   r	   r   r   r
   r   r   r1   r/   r   r   r   r   <module>   s*   
?+