
    [Th              	       "   S SK r S SKrS SKrS SKrS SKJr  S SKJrJr  S SK	J
r
  S SKrS SKJr  S SKJr  S SKJs  Jr  S SKJr  S SKJr  / SQr\R.                  " 5       r " S S	5      r\r " S
 S5      r " S S\R8                  \\5      r " S S\5      r " S S\R8                  \\\S9r  " S S\ 5      r!S r"S r# " S S\!5      r$S-S jr%S r&S.S jr'S r(\'" S SS9r)\'" S  S!\&S"9r*\'" S# S$S%S&9r+\'" S' S(S9r,\%" S) S* S!S9r- " S+ S,\!5      r.g)/    N)OrderedDict)AnyOptional)
deprecated)
_functions)custom_function_call)FunctionCtxBackwardCFunctionFunctionMetaFunctiononce_differentiableInplaceFunctionNestedIOFunctionc                       \ rS rSrS\R
                  4S jrS\R
                  4S jrS\R
                  4S jr\	" S\
S9S	 5       rS\R
                  4S
 jrS\4S jrSrg)r	   "   tensorsc                     Xl         g)a	  Save given tensors for a future call to :func:`~Function.backward`.

``save_for_backward`` should be called at most once, in either the
:func:`setup_context` or :func:`forward` methods, and only with tensors.

All tensors intended to be used in the backward pass should be saved
with ``save_for_backward`` (as opposed to directly on ``ctx``) to prevent
incorrect gradients and memory leaks, and enable the application of saved
tensor hooks. See :class:`torch.autograd.graph.saved_tensors_hooks`.

Note that if intermediary tensors, tensors that are neither inputs
nor outputs of :func:`forward`, are saved for backward, your custom Function
may not support double backward.
Custom Functions that do not support double backward should decorate their
:func:`backward` method with ``@once_differentiable`` so that performing
double backward raises an error. If you'd like to support double backward,
you can either recompute intermediaries based on the inputs during backward
or return the intermediaries as the outputs of the custom Function. See the
`double backward tutorial <https://pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html>`_
for more details.

In :func:`backward`, saved tensors can be accessed through the :attr:`saved_tensors`
attribute. Before returning them to the user, a check is made to ensure
they weren't used in any in-place operation that modified their content.

Arguments can also be ``None``. This is a no-op.

See :ref:`extending-autograd` for more details on how to use this method.

Example::
    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
    >>> class Func(Function):
    >>>     @staticmethod
    >>>     def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
    >>>         w = x * z
    >>>         out = x * y + y * z + w * y
    >>>         ctx.save_for_backward(x, y, w, out)
    >>>         ctx.z = z  # z is not a tensor
    >>>         return out
    >>>
    >>>     @staticmethod
    >>>     @once_differentiable
    >>>     def backward(ctx, grad_out):
    >>>         x, y, w, out = ctx.saved_tensors
    >>>         z = ctx.z
    >>>         gx = grad_out * (y + y * z)
    >>>         gy = grad_out * (x + z + w)
    >>>         gz = None
    >>>         return gx, gy, gz
    >>>
    >>> a = torch.tensor(1., requires_grad=True, dtype=torch.double)
    >>> b = torch.tensor(2., requires_grad=True, dtype=torch.double)
    >>> c = 4
    >>> d = Func.apply(a, b, c)

N)to_save)selfr   s     O/var/www/auris/envauris/lib/python3.13/site-packages/torch/autograd/function.pysave_for_backwardFunctionCtx.save_for_backward#   s
    r     c                 x    U H.  n[        U[        R                  5      (       a  M$  Uc  M)   S5       e   Xl        g)a  Save given tensors for a future call to :func:`~Function.jvp`.

``save_for_forward`` should be called at most once, in either the
:func:`setup_context` or :func:`forward` methods, and all arguments
should be tensors.

In :func:`jvp`, saved objects can be accessed through the :attr:`saved_tensors`
attribute.

Arguments can also be ``None``. This is a no-op.

See :ref:`extending-autograd` for more details on how to use this method.

Example::
    >>> # xdoctest: +SKIP
    >>> class Func(torch.autograd.Function):
    >>>     @staticmethod
    >>>     def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
    >>>         ctx.save_for_backward(x, y)
    >>>         ctx.save_for_forward(x, y)
    >>>         ctx.z = z
    >>>         return x * y * z
    >>>
    >>>     @staticmethod
    >>>     def jvp(ctx, x_t, y_t, _):
    >>>         x, y = ctx.saved_tensors
    >>>         z = ctx.z
    >>>         return z * (y * x_t + x * y_t)
    >>>
    >>>     @staticmethod
    >>>     def vjp(ctx, grad_out):
    >>>         x, y = ctx.saved_tensors
    >>>         z = ctx.z
    >>>         return z * grad_out * y, z * grad_out * x, None
    >>>
    >>>     a = torch.tensor(1., requires_grad=True, dtype=torch.double)
    >>>     t = torch.tensor(1., dtype=torch.double)
    >>>     b = torch.tensor(2., requires_grad=True, dtype=torch.double)
    >>>     c = 4
    >>>
    >>>     with fwAD.dual_level():
    >>>         a_dual = fwAD.make_dual(a, t)
    >>>         d = Func.apply(a_dual, b, c)

Nzgsave_for_forward expects all arguments to be tensors; you should save non-tensors as attributes on ctx.)
isinstancetorchTensorsaved_for_forward)r   r   tensors      r   save_for_forwardFunctionCtx.save_for_forward^   s>    \ Ffell33v~ 9E  ")r   argsc                     Xl         g)a  Mark given tensors as modified in an in-place operation.

This should be called at most once, in either the :func:`setup_context`
or :func:`forward` methods, and all arguments should be inputs.

Every tensor that's been modified in-place in a call to :func:`forward`
should be given to this function, to ensure correctness of our checks.
It doesn't matter whether the function is called before or after
modification.

Examples::
    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
    >>> class Inplace(Function):
    >>>     @staticmethod
    >>>     def forward(ctx, x):
    >>>         x_npy = x.numpy() # x_npy shares storage with x
    >>>         x_npy += 1
    >>>         ctx.mark_dirty(x)
    >>>         return x
    >>>
    >>>     @staticmethod
    >>>     @once_differentiable
    >>>     def backward(ctx, grad_output):
    >>>         return grad_output
    >>>
    >>> a = torch.tensor(1., requires_grad=True, dtype=torch.double).clone()
    >>> b = a * a
    >>> Inplace.apply(a)  # This would lead to wrong gradients!
    >>>                   # but the engine would not know unless we mark_dirty
    >>> # xdoctest: +SKIP
    >>> b.backward() # RuntimeError: one of the variables needed for gradient
    >>>              # computation has been modified by an inplace operation

N)dirty_tensorsr   r"   s     r   
mark_dirtyFunctionCtx.mark_dirty   s    F "r   z`mark_shared_storage` is deprecated. Tensors with shared storages are automatically tracked. Note that calls to `set_()` are not tracked)categoryc                     g N )r   pairss     r   mark_shared_storageFunctionCtx.mark_shared_storage   s     	r   c                     Xl         g)aP  Mark outputs as non-differentiable.

This should be called at most once, in either the :func:`setup_context`
or :func:`forward` methods, and all arguments should be tensor outputs.

This will mark outputs as not requiring gradients, increasing the
efficiency of backward computation. You still need to accept a gradient
for each output in :meth:`~Function.backward`, but it's always going to
be a zero tensor with the same shape as the shape of a corresponding
output.

This is used e.g. for indices returned from a sort. See example::
    >>> class Func(Function):
    >>>     @staticmethod
    >>>     def forward(ctx, x):
    >>>         sorted, idx = x.sort()
    >>>         ctx.mark_non_differentiable(idx)
    >>>         ctx.save_for_backward(x, idx)
    >>>         return sorted, idx
    >>>
    >>>     @staticmethod
    >>>     @once_differentiable
    >>>     def backward(ctx, g1, g2):  # still need to accept g2
    >>>         x, idx = ctx.saved_tensors
    >>>         grad_input = torch.zeros_like(x)
    >>>         grad_input.index_add_(0, idx, g1)
    >>>         return grad_input

N)non_differentiabler%   s     r   mark_non_differentiable#FunctionCtx.mark_non_differentiable   s
    < #'r   valuec                     Xl         g)a  Set whether to materialize grad tensors. Default is ``True``.

This should be called only from either the :func:`setup_context` or
:func:`forward` methods.

If ``True``, undefined grad tensors will be expanded to tensors full of zeros
prior to calling the :func:`backward` and :func:`jvp` methods.

Example::
    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
    >>> class SimpleFunc(Function):
    >>>     @staticmethod
    >>>     def forward(ctx, x):
    >>>         return x.clone(), x.clone()
    >>>
    >>>     @staticmethod
    >>>     @once_differentiable
    >>>     def backward(ctx, g1, g2):
    >>>         return g1 + g2  # No check for None necessary
    >>>
    >>> # We modify SimpleFunc to handle non-materialized grad outputs
    >>> class Func(Function):
    >>>     @staticmethod
    >>>     def forward(ctx, x):
    >>>         ctx.set_materialize_grads(False)
    >>>         ctx.save_for_backward(x)
    >>>         return x.clone(), x.clone()
    >>>
    >>>     @staticmethod
    >>>     @once_differentiable
    >>>     def backward(ctx, g1, g2):
    >>>         x, = ctx.saved_tensors
    >>>         grad_input = torch.zeros_like(x)
    >>>         if g1 is not None:  # We must check for None now
    >>>             grad_input += g1
    >>>         if g2 is not None:
    >>>             grad_input += g2
    >>>         return grad_input
    >>>
    >>> a = torch.tensor(1., requires_grad=True)
    >>> b, _ = Func.apply(a)  # induces g2 to be undefined

N)materialize_grads)r   r3   s     r   set_materialize_grads!FunctionCtx.set_materialize_grads   s    X "'r   )r$   r5   r0   r   r   N)__name__
__module____qualname____firstlineno__r   r   r   r    r&   r   FutureWarningr-   r1   boolr6   __static_attributes__r+   r   r   r	   r	   "   su    9%,, 9v4) 4)l#" #"J 	6 	'U\\ '@,'4 ,'r   r	   c                   $    \ rS rSr\S 5       rSrg)
_HookMixini  c                 j    U c
  [        5       n [        R                  " U 5      nXUR                  '   X4$ r*   )r   hooksRemovableHandleid)backward_hookshookhandles      r   _register_hook_HookMixin._register_hook  s4    !(]N&&~6$(vyy!%%r   r+   N)r8   r9   r:   r;   staticmethodrH   r>   r+   r   r   r@   r@     s    & &r   r@   c                   *    \ rS rSrSrS rS rS rSrg)r
   i  z<
This class is used for internal autograd work. Do not use.
c                     U R                   R                  nU R                   R                  nU[        R                  La  U[        R                  La  [	        S5      eU[        R                  La  UOUnU" U /UQ76 $ )z@
Apply method used when executing this Node during the backward
zsImplementing both 'backward' and 'vjp' for a custom Function is not allowed. You should only implement one of them.)_forward_clsbackwardvjpr   RuntimeError)r   r"   backward_fnvjp_fnuser_fns        r   applyBackwardCFunction.apply$  su     ''00""&&h///F(,,4N 
 #(,,6&Kt#d##r   c                 <    U R                   R                  " U /UQ76 $ )zE
Apply method used when executing forward mode AD during the forward
)rM   jvpr%   s     r   	apply_jvpBackwardCFunction.apply_jvp5  s     
   $$T1D11r   c                 8    U R                   R                  U 5      $ r*   )rM   _compiled_autograd_key)r   s    r   r[   (BackwardCFunction._compiled_autograd_key<  s      77==r   r+   N)	r8   r9   r:   r;   __doc__rT   rX   r[   r>   r+   r   r   r
   r
     s    $"2>r   r
   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )r   i@  zFunction metaclass.

This metaclass sets up the following properties:
    _backward_cls: The Function class corresponding to the differentiated
        version of this function (which is generated on the fly by this
        metaclass).
c                    > [        US-   [        4SU 05      n[        [        5      Ul        S Ul        [        U SS 5      (       a  U R                  R                  Ul        X@l	        [        TU ]-  XU5        g )NBackwardrM   _lazy_backward_info)typer
   nextAUTOGRAD_FUNCTION_COUNTER_autograd_function_id
_bw_modulegetattrra   	bw_module_backward_clssuper__init__)clsnamebasesattrsrQ   	__class__s        r   rk   FunctionMeta.__init__I  ss    : 13nc5J
 -11J,K)!%3-t44%(%<%<%F%FK"'e,r   r+   r8   r9   r:   r;   r]   rk   r>   __classcell__rp   s   @r   r   r   @  s    
- 
-r   r   c            	           \ rS rSr\S\S\S\4S j5       r\S\S\\S4   S	\S\4S
 j5       r\S\S\S\4S j5       r	\	r
\S\S\S\4S j5       rSrg)_SingleLevelFunctioniV  r"   kwargsreturnc                      [        S5      e)a  Define the forward of the custom autograd Function.

This function is to be overridden by all subclasses.
There are two ways to define forward:

Usage 1 (Combined forward and ctx)::

    @staticmethod
    def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any:
        pass

- It must accept a context ctx as the first argument, followed by any
  number of arguments (tensors or other types).
- See :ref:`combining-forward-context` for more details

Usage 2 (Separate forward and ctx)::

    @staticmethod
    def forward(*args: Any, **kwargs: Any) -> Any:
        pass

    @staticmethod
    def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
        pass

- The forward no longer accepts a ctx argument.
- Instead, you must also override the :meth:`torch.autograd.Function.setup_context`
  staticmethod to handle setting up the ``ctx`` object.
  ``output`` is the output of the forward, ``inputs`` are a Tuple of inputs
  to the forward.
- See :ref:`extending-autograd` for more details

The context can be used to store arbitrary data that can be then
retrieved during the backward pass. Tensors should not be stored
directly on `ctx` (though this is not currently enforced for
backward compatibility). Instead, tensors should be saved either with
:func:`ctx.save_for_backward` if they are intended to be used in
``backward`` (equivalently, ``vjp``) or :func:`ctx.save_for_forward`
if they are intended to be used for in ``jvp``.
zEYou must implement the forward function for custom autograd.Function.NotImplementedError)r"   rw   s     r   forward_SingleLevelFunction.forwardY  s    T "S
 	
r   ctxinputs.outputc                     [        S5      e)a5  There are two ways to define the forward pass of an autograd.Function.

Either:

1. Override forward with the signature ``forward(ctx, *args, **kwargs)``.
   ``setup_context`` is not overridden. Setting up the ctx for backward
   happens inside the ``forward``.
2. Override forward with the signature ``forward(*args, **kwargs)`` and
   override ``setup_context``. Setting up the ctx for backward happens
   inside ``setup_context`` (as opposed to inside the ``forward``)

See :meth:`torch.autograd.Function.forward` and :ref:`extending-autograd` for more details.
z!setup_context is not implemented.rz   )r~   r   r   s      r   setup_context"_SingleLevelFunction.setup_context  s     ""EFFr   grad_outputsc                     [        S5      e)aI  Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses.
(Defining this function is equivalent to defining the ``vjp`` function.)

It must accept a context :attr:`ctx` as the first argument, followed by
as many outputs as the :func:`forward` returned (None will be passed in
for non tensor outputs of the forward function),
and it should return as many tensors, as there were inputs to
:func:`forward`. Each argument is the gradient w.r.t the given output,
and each returned value should be the gradient w.r.t. the
corresponding input. If an input is not a Tensor or is a Tensor not
requiring grads, you can just pass None as a gradient for that input.

The context can be used to retrieve tensors saved during the forward
pass. It also has an attribute :attr:`ctx.needs_input_grad` as a tuple
of booleans representing whether each input needs gradient. E.g.,
:func:`backward` will have ``ctx.needs_input_grad[0] = True`` if the
first input to :func:`forward` needs gradient computed w.r.t. the
output.
zwYou must implement either the backward or vjp method for your custom autograd.Function to use it with backward mode AD.rz   )r~   r   s     r   rN   _SingleLevelFunction.backward  s    . "
 	
r   grad_inputsc                     [        S5      e)a  Define a formula for differentiating the operation with forward mode automatic differentiation.

This function is to be overridden by all subclasses.
It must accept a context :attr:`ctx` as the first argument, followed by
as many inputs as the :func:`forward` got (None will be passed in
for non tensor inputs of the forward function),
and it should return as many tensors as there were outputs to
:func:`forward`. Each argument is the gradient w.r.t the given input,
and each returned value should be the gradient w.r.t. the
corresponding output. If an output is not a Tensor or the function is not
differentiable with respect to that output, you can just pass None as a
gradient for that input.

You can use the :attr:`ctx` object to pass any value from the forward to this
functions.
z`You must implement the jvp function for custom autograd.Function to use it with forward mode AD.rz   )r~   r   s     r   rW   _SingleLevelFunction.jvp  s    $ "@
 	
r   r+   N)r8   r9   r:   r;   rJ   r   r|   tupler   rN   rO   rW   r>   r+   r   r   rv   rv   V  s     +
s +
c +
c +
 +
Z G3 Gc3h G G G G  
c 
# 
# 
 
: C
 
C 
C 
 
r   rv   )	metaclassc                   h   ^  \ rS rSrSrS rS r Sr\S 5       r	\
U 4S j5       r\S 5       rS	rU =r$ )
r   i  aO  Base class to create custom `autograd.Function`.

To create a custom `autograd.Function`, subclass this class and implement
the :meth:`forward` and :meth:`backward` static methods. Then, to use your custom
op in the forward pass, call the class method ``apply``. Do not call
:meth:`forward` directly.

To ensure correctness and best performance, make sure you are calling the
correct methods on ``ctx`` and validating your backward function using
:func:`torch.autograd.gradcheck`.

See :ref:`extending-autograd` for more details on how to use this class.

Examples::

    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
    >>> class Exp(Function):
    >>>     @staticmethod
    >>>     def forward(ctx, i):
    >>>         result = i.exp()
    >>>         ctx.save_for_backward(result)
    >>>         return result
    >>>
    >>>     @staticmethod
    >>>     def backward(ctx, grad_output):
    >>>         result, = ctx.saved_tensors
    >>>         return grad_output * result
    >>>
    >>> # Use it by calling the apply method:
    >>> # xdoctest: +SKIP
    >>> output = Exp.apply(input)
c                 R    [         R                  " U R                   S3[        SS9  g )Nz should not be instantiated. Methods on autograd functions are all static, so you should invoke them on the class itself. Instantiating an autograd function will raise an error in a future version of PyTorch.   )
stacklevel)warningswarnrp   DeprecationWarningr   r"   rw   s      r   rk   Function.__init__  s*    ~~ 4 4 	
r   c                     [        S5      e)NzLegacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function))rP   r   s      r   __call__Function.__call__  s    _
 	
r   Fc                     [        S5      e)a  Define the behavior for this autograd.Function underneath :func:`torch.vmap`.

For a :func:`torch.autograd.Function` to support
:func:`torch.vmap`, you must either override this static method, or set
``generate_vmap_rule`` to ``True`` (you may not do both).

If you choose to override this staticmethod: it must accept

- an ``info`` object as the first argument. ``info.batch_size``
  specifies the size of the dimension being vmapped over,
  while ``info.randomness`` is the randomness option passed to
  :func:`torch.vmap`.
- an ``in_dims`` tuple as the second argument.
  For each arg in ``args``, ``in_dims`` has a corresponding
  ``Optional[int]``. It is ``None`` if the arg is not a Tensor or if
  the arg is not being vmapped over, otherwise, it is an integer
  specifying what dimension of the Tensor is being vmapped over.
- ``*args``, which is the same as the args to :meth:`~Function.forward`.

The return of the vmap staticmethod is a tuple of ``(output, out_dims)``.
Similar to ``in_dims``, ``out_dims`` should be of the same structure as
``output`` and contain one ``out_dim`` per output that specifies if the
output has the vmapped dimension and what index it is in.

Please see :ref:`func-autograd-function` for more details.
zrTo use autograd.Function with vmap, you must either override the vmap staticmethod or set generate_vmap_rule=True.rz   )infoin_dimsr"   s      r   vmapFunction.vmap  s    8 "@
 	
r   c                 T  > S n[        U R                  5      nU(       a  U" U R                  /UQ70 UD6n[        R                  R                  5       (       d/  [        R                  R                  U5      n[        TU ](  " U0 UD6$ U(       d  [        S5      e[        U /UQ70 UD6$ )Nc                     [         R                  " U 5      nUR                  " U0 UD6nUR                  5         UR                  $ r*   )inspect	signaturebindapply_defaultsr"   )funcr"   rw   r   
bound_argss        r   bind_default_args)Function.apply.<locals>.bind_default_args1  s;    ))$/I"88J%%'??"r   zIn order to use an autograd.Function with functorch transforms (vmap, grad, jvp, jacrev, ...), it must override the setup_context staticmethod. For more details, please see https://pytorch.org/docs/main/notes/extending.func.html)_is_setup_context_definedr   r|   r   _C _are_functorch_transforms_active
_functorchutilsunwrap_dead_wrappersrj   rT   rP   r   )rl   r"   rw   r   is_setup_ctx_definedrp   s        r   rT   Function.apply/  s    	#  99J9JK$S[[B4B6BDxx88::##88>D7=$1&11#J  $C9$9&99r   c                     U R                   4$ r*   )re   )r~   s    r   r[   Function._compiled_autograd_keyK  s    ))++r   r+   )r8   r9   r:   r;   r]   rk   r   generate_vmap_rulerJ   r   classmethodrT   r[   r>   rs   rt   s   @r   r   r     s[    B

 
 
@ : :6 , ,r   r   c                 (    U [         R                  :g  $ r*   )rv   r   )fns    r   r   r   P  s    %3333r   c                 F   ^  [         R                  " T 5      U 4S j5       nU$ )Nc                   > [         R                  " 5          T" U /UQ76 nS S S 5        [         R                  " 5       (       d  W$ [        S U 5       5      nU(       d  W$ [	        W[
        5      (       d  U4n[        R                  " S[        U5      5      nS nU" U Vs/ s H
  oe" U5      PM     sn6 $ ! , (       d  f       N= fs  snf )Nc              3   |   #    U  H2  n[        U[        R                  5      =(       a    UR                  v   M4     g 7fr*   )r   r   r   requires_grad).0args     r   	<genexpr>7once_differentiable.<locals>.wrapper.<locals>.<genexpr>f  s,      
KOCJsELL)?c.?.??4s   :<sR   trying to differentiate twice a function that was marked with @once_differentiablec                 :    U b  U R                  5       n SU l        U $ )NT)detachr   )vars    r   fake_requires_grad@once_differentiable.<locals>.wrapper.<locals>.fake_requires_gradx  s    jjl$(!Jr   )	r   no_gradis_grad_enabledanyr   r   r   DelayedErrorlen)r~   r"   outputsr   err_fnr   vr   s          r   wrapper$once_differentiable.<locals>.wrapperU  s    ]]_ntnG  $$&&N  
KO
 
 N'5))jG(()L
	 w?w!*1-w?@@O _N @s   
B6!C6
C)	functoolswraps)r   r   s   ` r   r   r   T  s(    __R(A (AT Nr   c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )r   i  y
This class is here only for backward compatibility reasons.
Use :class:`Function` instead of this for any new use case.
c                 .   > [         TU ]  5         Xl        g r*   )rj   rk   inplace)r   r   rp   s     r   rk   InplaceFunction.__init__  s    r   )r   )Frr   rt   s   @r   r   r     s    
 r   r   c                     ^ ^^^ UU UU4S jmT$ )Nc                   > T" U 5      (       a  T" U 5      $ U c  g [        U [        [        45      (       a<  U4S jU  5       n[        U S5      (       a  [	        U 5      " U6 $ [	        U 5      " U5      $ [        U [
        5      (       a  U  Vs0 s H  o"T" X   5      _M     sn$ [        S[        R                  " U 5      -   T(       a  ST-   S-   -   5      eS-   5      es  snf )Nc              3   4   >#    U  H  nT" U5      v   M     g 7fr*   r+   )r   x_maps     r   r   ,_nested_map.<locals>._map.<locals>.<genexpr>  s     +s!d1ggss   _fieldsAAuto nesting doesn't know how to process an input object of type . Accepted types: , or lists/tuples of them )	r   listr   hasattrrb   dict
ValueErrorr   typename)objmappedr   r   	conditioncondition_msgr   s      r   r   _nested_map.<locals>._map  s    S>>c7N[dE]+++s+FsI&&Cy&))9V$$T""-01StCF|OS11+..%&
 % )=8;VV		 	 	 	 2s   Cr+   )r   r   r   r   s   ```@r   _nested_mapr     s     2 Kr   c                 H    [        U S5      (       a  U R                  5       $ U $ )N_jit_unwrap)r   r   )r   s    r   _jit_unwrap_structuredr     s!    sM""  Jr   c                 $   ^ ^^^^ UUU UU4S jmT$ )Nc              3     >#    Tb  T" U 5      n T" U 5      (       a  U v   g U c  g [        U [        [        45      (       a  U  H  nT" U5       S h  vN   M     g [        U [        5      (       a(  U R	                  5        H  nT" U5       S h  vN   M     g T(       a  U v   g [        S[        R                  " U 5      -   T(       a  ST-   S-   -   5      eS-   5      e N NQ7f)Nr   r   r   r   )r   r   r   r   valuesr   r   r   )r   o_iterallow_unknownr   r   
conversions     r   r   _iter_filter.<locals>._iter  s     !S/CS>>I[dE]++ 8## T""ZZ\ 8## "I+..%&
 % )=8;VV		 	 	 	 $ $s%   AC!C<C!CAC!C!r+   )r   r   r   r   r   s   ````@r   _iter_filterr     s     8 Lr   c                 &   ^ U4S jmT" X5      S   $ )Nc                 0  > / n[        US5      (       a  UR                  U 5      $ [        U[        [        45      (       d
  U S   U SS  4$ U H4  nUc  UR                  U5        M  T" X5      u  p@UR                  U5        M6     [        U5      " U5      U 4$ )N	_jit_wrapr      )r   r   r   r   r   appendrb   )inputprotoreseres_eunflatten_helpers        r   r   $_unflatten.<locals>.unflatten_helper  s    ,.5+&&??5))%$//8U12Y&&Ay

1/9

5!  E{3&&r   r   r+   )r   r   r   s     @r   
_unflattenr    s    ' E)!,,r   c                 `    U S L =(       d$    [        U [        R                  R                  5      $ r*   )r   r   r   Valuer   s    r   <lambda>r    s    a4i8:a88r   zjit's Values or None)r   c                 6    [        U [        R                  5      $ r*   r   r   r   r   s    r   r  r        jELL)r   Tensors)r   r   c                 6    [        U [        R                  5      $ r*   r  r  s    r   r  r    r	  r   TzTensors (permissive))r   r   c                 L    U S L =(       d    [        U [        R                  5      $ r*   r  r  s    r   r  r    s    a4i6:a66r   zTensors or Nonec                 6    [        U [        R                  5      $ r*   r  r  s    r   r  r    r	  r   c                     U R                   $ r*   )datar  s    r   r  r    s    QVVr   c                      ^  \ rS rSrSrU 4S jrU 4S jrS\S\4S jr\r	S\S\4S	 jr
S\SS
4S jr\U 4S j5       rS\S\SS
4S jrS\S\SS
4S jrS\SS
4S jrS\SS
4S jrSrU =r$ )r   i  r   c                    > Xl         [        [        U5      5      n[        TU ]  " U6 n[        X0R                  5      nU$ r*   )_nested_inputr   _iter_tensorsrj   _do_forwardr  _nested_output)r   r   
flat_inputflat_outputnested_tensorsrp   s        r   r  NestedIOFunction._do_forward  s=    "=/0
g):6#K1D1DEr   c                 H   > X l         [        TU ]	  X5      nU(       d  U ?U ?U$ r*   )retain_variablesrj   _do_backwardr  _to_save_nested)r   	gradientsr  resultrp   s       r   r  NestedIOFunction._do_backward
  s,     0%iB#$r   r  rx   c                 r    [        XR                  5      nU R                  " U6 n[        [	        U5      5      $ )z
Shared backward utility.
)r  r  backward_extendedr   _iter_None_tensors)r   r  nested_gradientsr  s       r   rN   NestedIOFunction.backward  s7     &i1D1DE'')9:'/00r   r"   c                     [        U R                  5      nU R                  " U6 nU ?X0l        [	        [        U5      5      $ )z
Shared forward utility.
)_map_tensor_datar  forward_extendedr  r   r  )r   r"   r  r  s       r   r|   NestedIOFunction.forward  s@     *$*<*<=&&7$]6*++r   Nc                 B    [        [        U5      5      U l        Xl        g)z)
See :meth:`Function.save_for_backward`.
N)r   r  r   r  r%   s     r   r   "NestedIOFunction.save_for_backward&  s     ]401#r   c                 B   > [         TU ]  n[        XR                  5      $ )z%
See :meth:`Function.saved_tensors`.
)rj   saved_tensorsr  r  )r   flat_tensorsrp   s     r   r-  NestedIOFunction.saved_tensors-  s     
 w,,(<(<==r   rw   c                 8    [        [        X45      5      U l        g)z"
See :meth:`Function.mark_dirty`.
N)r   r  r$   r   s      r   r&   NestedIOFunction.mark_dirty5  s     #=$#@Ar   c                 8    [        [        X45      5      U l        g)z/
See :meth:`Function.mark_non_differentiable`.
N)r   r  r0   r   s      r   r1   (NestedIOFunction.mark_non_differentiable;  s     #(tn(E"Fr   r   c                     [         e)z
User defined forward.
rz   )r   r   s     r   r(  !NestedIOFunction.forward_extendedA  
     "!r   grad_outputc                     [         e)z
User defined backward.
rz   )r   r7  s     r   r"  "NestedIOFunction.backward_extendedG  r6  r   )r  r  r  r$   r0   r  r   )r8   r9   r:   r;   r]   r  r  r   rN   r   r|   r   propertyr-  r&   r1   r(  r"  r>   rs   rt   s   @r   r   r     s    13 13 1 H,S ,S ,$s $t $ > >B Bs Bt BGS GC GD G"s "t ""c "d " "r   r   r*   )FNN)/r   r   	itertoolsr   collectionsr   typingr   r   typing_extensionsr   r   torch._Cr   torch._functorchr   torch.utils.hooksr   rB   r   "torch._functorch.autograd_functionr   __all__countrd   r	   _ContextMethodMixinr@   _FunctionBaser
   rb   r   rv   r   r   r   r   r   r   r   r  _iter_jit_valuesr  _iter_tensors_permissiver#  r'  r   r+   r   r   <module>rI     sS       #   (   % ! !  C &OO- l' l'` " & &>((+z >B-4 -,w
k:w
t},# },@4,^h :@-(  8(  )%
 ()( 
 "6FW  )+;9 
P"x P"r   