
    Pg2                         d dl mZ d dlZd dlmZmZmZ g dZ G d de      Z G d de      Z	 G d	 d
e      Z
 G d de      Zd Zd Z G d de      Z G d de      Z G d de      Zy)    )AnyN)_DecoratorContextManager_NoParamDecoratorContextManagerF)no_gradenable_gradset_grad_enabledinference_modeset_multithreading_enabledc                   D     e Zd ZdZd
 fdZd
dZdedededdfd	Z xZS )r   a  Context-manager that disables gradient calculation.

    Disabling gradient calculation is useful for inference, when you are sure
    that you will not call :meth:`Tensor.backward()`. It will reduce memory
    consumption for computations that would otherwise have `requires_grad=True`.

    In this mode, the result of every computation will have
    `requires_grad=False`, even when the inputs have `requires_grad=True`.
    There is an exception! All factory functions, or functions that create
    a new Tensor and take a requires_grad kwarg, will NOT be affected by
    this mode.

    This context manager is thread local; it will not affect computation
    in other threads.

    Also functions as a decorator.

    .. note::
        No-grad is one of several mechanisms that can enable or
        disable gradients locally see :ref:`locally-disable-grad-doc` for
        more information on how they compare.

    .. note::
        This API does not apply to :ref:`forward-mode AD <forward-mode-ad>`.
        If you want to disable forward AD for a computation, you can unpack
        your dual tensors.

    Example::
        >>> # xdoctest: +SKIP
        >>> x = torch.tensor([1.], requires_grad=True)
        >>> with torch.no_grad():
        ...     y = x * 2
        >>> y.requires_grad
        False
        >>> @torch.no_grad()
        ... def doubler(x):
        ...     return x * 2
        >>> z = doubler(x)
        >>> z.requires_grad
        False
        >>> @torch.no_grad()
        ... def tripler(x):
        ...     return x * 3
        >>> z = tripler(x)
        >>> z.requires_grad
        False
        >>> # factory function exception
        >>> with torch.no_grad():
        ...     a = torch.nn.Parameter(torch.rand(10))
        >>> a.requires_grad
        True
    returnNc                 l    t         j                  j                         st        |           d| _        y NF)torch_jit_internalis_scriptingsuper__init__prev)self	__class__s    _/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/autograd/grad_mode.pyr   zno_grad.__init__K   s'    ""//1G	    c                 `    t        j                         | _        t        j                  d       y r   )r   is_grad_enabledr   r	   r   s    r   	__enter__zno_grad.__enter__P   s     ))+	u%r   exc_type	exc_value	tracebackc                 B    t        j                  | j                         y N)r   r	   r   r   r   r   r    s       r   __exit__zno_grad.__exit__T   s    tyy)r   r   N)	__name__
__module____qualname____doc__r   r   r   r$   __classcell__r   s   @r   r   r      s4    3j
&* * * * *r   r   c                   0    e Zd ZdZd	dZdedededdfdZy)
r   a  Context-manager that enables gradient calculation.

    Enables gradient calculation, if it has been disabled via :class:`~no_grad`
    or :class:`~set_grad_enabled`.

    This context manager is thread local; it will not affect computation
    in other threads.

    Also functions as a decorator.

    .. note::
        enable_grad is one of several mechanisms that can enable or
        disable gradients locally see :ref:`locally-disable-grad-doc` for
        more information on how they compare.

    .. note::
        This API does not apply to :ref:`forward-mode AD <forward-mode-ad>`.

    Example::
        >>> # xdoctest: +SKIP
        >>> x = torch.tensor([1.], requires_grad=True)
        >>> with torch.no_grad():
        ...     with torch.enable_grad():
        ...         y = x * 2
        >>> y.requires_grad
        True
        >>> y.backward()
        >>> x.grad
        tensor([2.])
        >>> @torch.enable_grad()
        ... def doubler(x):
        ...     return x * 2
        >>> with torch.no_grad():
        ...     z = doubler(x)
        >>> z.requires_grad
        True
        >>> @torch.enable_grad()
        ... def tripler(x):
        ...     return x * 3
        >>> with torch.no_grad():
        ...     z = tripler(x)
        >>> z.requires_grad
        True

    r   Nc                 t    t        j                         | _        t         j                  j	                  d       y )NT)r   r   r   _C_set_grad_enabledr   s    r   r   zenable_grad.__enter__   s$    ))+	""4(r   r   r   r    c                 V    t         j                  j                  | j                         y r"   r   r.   r/   r   r#   s       r   r$   zenable_grad.__exit__       ""499-r   r%   )r&   r'   r(   r)   r   r   r$    r   r   r   r   X   s.    ,\). . . . .r   r   c                   d     e Zd ZdZdeddfdZdedef fdZddZd	e	d
e	de	ddfdZ
ddZ xZS )r	   a  Context-manager that sets gradient calculation on or off.

    ``set_grad_enabled`` will enable or disable grads based on its argument :attr:`mode`.
    It can be used as a context-manager or as a function.

    This context manager is thread local; it will not affect computation
    in other threads.

    Args:
        mode (bool): Flag whether to enable grad (``True``), or disable
                     (``False``). This can be used to conditionally enable
                     gradients.

    .. note::
        set_grad_enabled is one of several mechanisms that can enable or
        disable gradients locally see :ref:`locally-disable-grad-doc` for
        more information on how they compare.

    .. note::
        This API does not apply to :ref:`forward-mode AD <forward-mode-ad>`.

    Example::
        >>> # xdoctest: +SKIP
        >>> x = torch.tensor([1.], requires_grad=True)
        >>> is_train = False
        >>> with torch.set_grad_enabled(is_train):
        ...     y = x * 2
        >>> y.requires_grad
        False
        >>> _ = torch.set_grad_enabled(True)
        >>> y = x * 2
        >>> y.requires_grad
        True
        >>> _ = torch.set_grad_enabled(False)
        >>> y = x * 2
        >>> y.requires_grad
        False

    moder   Nc                     t        j                         | _        || _        t         j                  j                  |       y r"   )r   r   r   r5   r.   r/   r   r5   s     r   r   zset_grad_enabled.__init__   s+    ))+		""4(r   	orig_funcc                 t    t         j                  j                  | j                         t        |   |      S r"   )r   r.   r/   r   r   __call__)r   r8   r   s     r   r:   zset_grad_enabled.__call__   s)    ""499-w	**r   c                 V    t         j                  j                  | j                         y r"   )r   r.   r/   r5   r   s    r   r   zset_grad_enabled.__enter__   r2   r   r   r   r    c                 V    t         j                  j                  | j                         y r"   r1   r#   s       r   r$   zset_grad_enabled.__exit__   r2   r   c                 8    | j                  | j                        S z-
        Create a copy of this class
        r   r5   r   s    r   clonezset_grad_enabled.clone        ~~dii((r   r%   )r   r	   )r&   r'   r(   r)   boolr   r   r:   r   r   r$   r@   r*   r+   s   @r   r	   r	      sZ    &P)T )d )
+! + +.. . . . .)r   r	   c                   b     e Zd ZdZddeddf fdZd fd	ZddZded	ed
eddfdZ	ddZ
 xZS )r
   ag  Context-manager that enables or disables inference mode.

    InferenceMode is a context manager analogous to :class:`~no_grad`
    to be used when you are certain your operations will have no interactions
    with autograd (e.g., model training). Code run under this mode gets better
    performance by disabling view tracking and version counter bumps. Note that
    unlike some other mechanisms that locally enable or disable grad,
    entering inference_mode also disables to :ref:`forward-mode AD <forward-mode-ad>`.

    This context manager is thread local; it will not affect computation
    in other threads.

    Also functions as a decorator.

    .. note::
        Inference mode is one of several mechanisms that can enable or
        disable gradients locally see :ref:`locally-disable-grad-doc` for
        more information on how they compare.

    Args:
        mode (bool or function): Either a boolean flag whether to enable or
            disable inference mode or a Python function to decorate with
            inference mode enabled

    Example::
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> import torch
        >>> x = torch.ones(1, 2, 3, requires_grad=True)
        >>> with torch.inference_mode():
        ...     y = x * x
        >>> y.requires_grad
        False
        >>> # xdoctest: +SKIP("want string isnt quite right")
        >>> y._version
        Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        RuntimeError: Inference tensors do not track version counter.
        >>> @torch.inference_mode()
        ... def func(x):
        ...     return x * x
        >>> out = func(x)
        >>> out.requires_grad
        False
        >>> @torch.inference_mode()
        ... def doubler(x):
        ...     return x * 2
        >>> out = doubler(x)
        >>> out.requires_grad
        False

    r5   r   Nc                 l    t         j                  j                         st        |           || _        y r"   )r   r   r   r   r   r5   )r   r5   r   s     r   r   zinference_mode.__init__  s'    ""//1G	r   c                 \    t        |t              rt        |   |       S   |        |      S r"   )
isinstancerB   r   __new__)clsr5   r   s     r   rG   zinference_mode.__new__  s*    dD!7?3''suT{r   c                     t         j                  j                  | j                        | _        | j                  j                          y r"   )r   r.   _InferenceModer5   _inference_mode_contextr   r   s    r   r   zinference_mode.__enter__  s/    ',xx'>'>tyy'I$$$..0r   r   r   r    c                 >    | j                   j                  |||       y r"   )rK   r$   r#   s       r   r$   zinference_mode.__exit__  s    $$--h	9Mr   c                 8    | j                  | j                        S r>   r?   r   s    r   r@   zinference_mode.clone  rA   r   )Tr%   )r   r
   )r&   r'   r(   r)   rB   r   rG   r   r   r$   r@   r*   r+   s   @r   r
   r
      sQ    2hT T 

1N N N N N)r   r
   c                 d    t         j                  j                  |       }|j                          |S r"   )r   r.   rJ   r   )r5   mode_contexts     r   _enter_inference_moderP     s(    88**40Lr   c                 *    | j                  d d d        y r"   )r$   )r5   s    r   _exit_inference_moderR   !  s    MM$d#r   c                   H    e Zd ZdZdeddfdZddZdeded	eddfd
ZddZ	y)r   a7  Context-manager that sets multithreaded backwards on or off.

    ``set_multithreading_enabled`` will enable or disable multithreaded backwards based on its argument :attr:`mode`.
    It can be used as a context-manager or as a function.

    This context manager is thread local; it will not affect computation
    in other threads.

    Args:
        mode (bool): Flag whether to enable multithreaded backwards (``True``), or disable
                     (``False``).

    .. note::
        This API does not apply to :ref:`forward-mode AD <forward-mode-ad>`.

    r5   r   Nc                     t         j                  j                         | _        t         j                  j	                  |       || _        y r"   )r   r.   _is_multithreading_enabledr   _set_multithreading_enabledr5   r7   s     r   r   z#set_multithreading_enabled.__init__7  s/    HH779	,,T2	r   c                      y r"   r3   r   s    r   r   z$set_multithreading_enabled.__enter__<      r   r   r   r    c                 V    t         j                  j                  | j                         y r"   )r   r.   rV   r   r#   s       r   r$   z#set_multithreading_enabled.__exit__?  s    ,,TYY7r   c                 8    | j                  | j                        S r>   r?   r   s    r   r@   z set_multithreading_enabled.cloneB  rA   r   r%   )r   r   
r&   r'   r(   r)   rB   r   r   r   r$   r@   r3   r   r   r   r   %  sE    "T d 
8 8 8 8 8)r   r   c                   F    e Zd ZdZdeddfdZddZdeded	eddfd
Zd Z	y)_force_original_view_trackingaL  Context-manager that sets whether or not to always enable view-replay in autograd.

    ``set_view_replay_enabled`` will enable or disable view-replay based on its argument :attr:`mode`.
    It can be used as a context-manager or as a function.

    This context manager is thread local; it will not affect computation
    in other threads.

    When a tensor view is mutated, the autograd engine needs to decide whether or not
    to regenerate the "updated view" by either replaying the chain of views from the updated base,
    or with a single call to as_strided.

    If set_view_replay_enabled is set to True, then autograd will always use view replay.
    Otherwise, it will fall back to its existing logic.

    Args:
        mode (bool): Flag whether to enable view-replay (``True``), or disable
                     (``False``).

    r5   r   Nc                     t         j                  j                         | _        t         j                  j	                  |       || _        y r"   )r   r.   _is_view_replay_enabledr   _set_view_replay_enabledr5   r7   s     r   r   z&_force_original_view_tracking.__init___  s/    HH446	))$/	r   c                      y r"   r3   r   s    r   r   z'_force_original_view_tracking.__enter__d  rX   r   r   r   r    c                 V    t         j                  j                  | j                         y r"   )r   r.   r`   r   r#   s       r   r$   z&_force_original_view_tracking.__exit__g  s    ))$))4r   c                 8    | j                  | j                        S r"   r?   r   s    r   r@   z#_force_original_view_tracking.clonej  s    ~~dii((r   r%   r[   r3   r   r   r]   r]   I  sE    *T d 
5 5 5 5 5)r   r]   c                   D    e Zd ZdZdej
                  ddfdZddZddZy)	 _unsafe_preserve_version_countera2  DO NOT USE THIS UNLESS YOU KNOW EXACTLY WHAT YOU'RE DOING.

    This context manager can lead to arbitrary silent-correctness issues in any other part of your code
    (even the ones not touched directly by the context manager)!

    Ordinarily, autograd will track mutations to tensors by incrementing it's `._version` attribute.
    This is generally important for correctness, as for example, mutating a tensor that autograd has saved
    for the backwards pass can result in incorrect gradients, and autograd uses the version counter to detect
    and error out in this situation.

    However, there are rare instances where it might be useful to hide mutations from autograd. For example:
    if a tensor is very large, and you'd like to free its memory by storing it elsewhere, and re-populate
    the tensor right before it is needed by autograd.

    Args:
        tensor (torch.Tensor): the tensor in question, that you would like to preserve the version counter of.

    .. note::
        This API does not apply to :ref:`forward-mode AD <forward-mode-ad>`.

    tensorr   Nc                 4    || _         |j                  | _        y r"   )rf   _versionprev_version)r   rf   s     r   r   z)_unsafe_preserve_version_counter.__init__  s    "OOr   c                      y r"   r3   r   s    r   r   z*_unsafe_preserve_version_counter.__enter__  rX   r   c                     t         j                  j                  j                  | j                  | j
                         y r"   )r   r.   	_autograd_unsafe_set_version_counterrf   ri   )r   argss     r   r$   z)_unsafe_preserve_version_counter.__exit__  s&    66t{{DDUDUVr   r%   )	r&   r'   r(   r)   r   Tensorr   r   r$   r3   r   r   re   re   n  s)    ,,u|| , ,Wr   re   )typingr   r   torch.utils._contextlibr   r   r   __all__r   r   r	   r
   rP   rR   r   r]   re   r3   r   r   <module>rs      s      @*- @*F4.1 4.n<)/ <)~J)- J)Z$!)!9 !)H")$< ")JW'? Wr   