a
    –¥»aºX  ã                   @   s†  d dl Z d dlmZ d dlmZ d dlm  mZ d dlmZ d dl	Z	d dl
Z
d dlmZ d dlmZmZmZ G dd„ deƒZeZG dd	„ d	eƒZG d
d„ dejeeƒZG dd„ deƒZG dd„ deeejeeƒƒZdd„ Zdd„ ZG dd„ deƒZd0dd„Zdd„ Zd1dd„Zdd„ Z edd „ d!d"�Z!ed#d „ d$ed%�Z"ed&d „ d'd(d)�Z#ed*d „ d+d"�Z$ed,d „ d-d „ d$d"�Z%G d.d/„ d/eƒZ&dS )2é    N)Ú
_functions)Úwith_metaclass)ÚOrderedDict)ÚAnyÚListÚOptionalc                   @   sR   e Zd Zejdœdd„Zejdœdd„Zdd„ Zejdœd	d
„Ze	dœdd„Z
dS )ÚFunctionCtx)Útensorsc                 G   s
   || _ dS )aº  Saves given tensors for a future call to :func:`~Function.backward`.

        **This should be called at most once, and only from inside the**
        :func:`forward` **method. This should only be called with input or
        output tensors**

        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::
            >>> class Func(Function):
            >>>     @staticmethod
            >>>     def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
            >>>         w = x * y * z
            >>>         out = x * y + y * z + w
            >>>         ctx.save_for_backward(x, y, out)
            >>>         ctx.z = z  # z is not a tensor
            >>>         ctx.w = w  # w is neither input nor output
            >>>         return out
            >>>
            >>>     @staticmethod
            >>>     def backward(ctx, grad_out):
            >>>         x, y, out = ctx.saved_tensors
            >>>         z = ctx.z
            >>>         gx = grad_out * (y + y * z)
            >>>         gy = grad_out * (x + z + x * z)
            >>>         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	   © r   úQ/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/autograd/function.pyÚsave_for_backward   s    )zFunctionCtx.save_for_backward)Úargsc                 G   s
   || _ dS )a‘  Marks given tensors as modified in an in-place operation.

        **This should be called at most once, only from inside the**
        :func:`forward` **method, 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::
            >>> 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
            >>> b.backward() # RuntimeError: one of the variables needed for gradient
            >>>              # computation has been modified by an inplace operation

        N)Údirty_tensors©r   r   r   r   r   Ú
mark_dirty9   s    !zFunctionCtx.mark_dirtyc                 G   s   t  d¡ d S )Nz†mark_shared_storage is deprecated. Tensors with shared storages are automatically tracked. Note that calls to `set_()` are not tracked)ÚwarningsÚwarn)r   Úpairsr   r   r   Úmark_shared_storage\   s    ÿzFunctionCtx.mark_shared_storagec                 G   s
   || _ dS )a  Marks outputs as non-differentiable.

        **This should be called at most once, only from inside the**
        :func:`forward` **method, 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   r   r   r   Úmark_non_differentiableb   s    z#FunctionCtx.mark_non_differentiable)Úvaluec                 C   s
   || _ dS )a¨  Sets whether to materialize output grad tensors. Default is ``True``.

        **This should be called only from inside the** :func:`forward` **method**

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

        Example::
            >>> 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)Zmaterialize_grads)r   r   r   r   r   Úset_materialize_grads‚   s    *z!FunctionCtx.set_materialize_gradsN)Ú__name__Ú
__module__Ú__qualname__ÚtorchÚTensorr   r   r   r   Úboolr   r   r   r   r   r      s
   +# r   c                   @   s   e Zd Zedd„ ƒZdS )Ú
_HookMixinc                 C   s*   | d u rt ƒ } t | ¡}|| |j< | |fS ©N)r   ÚhooksZRemovableHandleÚid)Zbackward_hooksÚhookÚhandler   r   r   Ú_register_hook³   s
    

z_HookMixin._register_hookN)r   r   r   Ústaticmethodr'   r   r   r   r   r!   ±   s   r!   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚBackwardCFunctionc                 G   sN   | j j}| j j}|tjur,|tjur,tdƒ‚|tjur:|n|}|| g|¢R Ž S )NzsImplementing both 'backward' and 'vjp' for a custom Function is not allowed. You should only implement one of them.)Ú_forward_clsÚbackwardÚvjpÚFunctionÚRuntimeError)r   r   Úbackward_fnZvjp_fnZuser_fnr   r   r   Úapply½   s    zBackwardCFunction.applyc                 G   s   | j j| g|¢R Ž S r"   )r*   Újvpr   r   r   r   Ú	apply_jvpÉ   s    zBackwardCFunction.apply_jvpN)r   r   r   r0   r2   r   r   r   r   r)   ¼   s   r)   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚFunctionMetaa   Function 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                    s4   t |d tfd| iƒ}|| _tt| ƒ |||¡ d S )NZBackwardr*   )Útyper)   Z_backward_clsÚsuperr3   Ú__init__)ÚclsÚnameÚbasesÚattrsr/   ©Ú	__class__r   r   r6   Ö   s    zFunctionMeta.__init__)r   r   r   Ú__doc__r6   Ú__classcell__r   r   r;   r   r3   Î   s   r3   c                   @   sl   e Zd ZdZdd„ Zdd„ ZdZeeeeedœdd	„ƒZ	eeeed
œdd„ƒZ
e
Zeeeedœdd„ƒZdS )r-   aY  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::

        >>> 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:
        >>> output = Exp.apply(input)
    c                 O   s   | j }t |› d�t¡ d S )NzÏ should not be instantiated. Methods on autograd functionsare 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.)r<   r   r   ÚDeprecationWarning)r   r   Úkwargsr7   r   r   r   r6   ý   s    ýzFunction.__init__c                 O   s   t dƒ‚d S )NzÚLegacy 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))r.   ©r   r   r@   r   r   r   Ú__call__  s    ÿzFunction.__call__F)Úctxr   r@   Úreturnc                 O   s   t dƒ‚dS )aW  Performs the operation.

        This function is to be overridden by all subclasses.

        It must accept a context ctx as the first argument, followed by any
        number of arguments (tensors or other types).

        The context can be used to store arbitrary data that can be then
        retrieved during the backward pass.
        zEYou must implement the forward function for custom autograd.Function.N©ÚNotImplementedError)rC   r   r@   r   r   r   Úforward  s    zFunction.forward)rC   Úgrad_outputsrD   c                 G   s   t dƒ‚dS )a‹  Defines a formula for differentiating the operation with backward 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 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 computated 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.NrE   )rC   rH   r   r   r   r+     s    zFunction.backward)rC   Úgrad_inputsrD   c                 G   s   t dƒ‚dS )aƒ  Defines 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.NrE   )rC   rI   r   r   r   r1   :  s    zFunction.jvpN)r   r   r   r=   r6   rB   Úis_traceabler(   r   rG   r+   r,   r1   r   r   r   r   r-   Þ   s   r-   c                    s   t  ˆ ¡‡ fdd„ƒ}|S )Nc                    sœ   t  ¡ �  ˆ| g|¢R Ž }W d   ƒ n1 s.0    Y  t  ¡ sD|S tdd„ |D ƒƒ}|s^|S t|tƒsn|f}t dt|ƒ¡}dd„ ‰ |‡ fdd„|D ƒŽ S )Nc                 s   s    | ]}t |tjƒo|jV  qd S r"   )Ú
isinstancer   r   Úrequires_grad)Ú.0Úargr   r   r   Ú	<genexpr>b  s   ÿz7once_differentiable.<locals>.wrapper.<locals>.<genexpr>sR   trying to differentiate twice a function that was marked with @once_differentiablec                 S   s   | d ur|   ¡ } d| _| S )NT)ÚdetachrL   )Úvarr   r   r   Úfake_requires_gradq  s    z@once_differentiable.<locals>.wrapper.<locals>.fake_requires_gradc                    s   g | ]}ˆ |ƒ‘qS r   r   )rM   Úv©rR   r   r   Ú
<listcomp>w  ó    z8once_differentiable.<locals>.wrapper.<locals>.<listcomp>)	r   Zno_gradZis_grad_enabledÚanyrK   Útupler   ZDelayedErrorÚlen)rC   r   ÚoutputsrL   Zerr_fn©ÚfnrT   r   ÚwrapperQ  s"    
.ÿ
þz$once_differentiable.<locals>.wrapper)Ú	functoolsÚwraps)r\   r]   r   r[   r   Úonce_differentiableO  s    &r`   c                 C   s
   d| _ | S )aÙ  Marks Function as traceable for the JIT.

    Traceable functions have additional restrictions - they can't pass any
    data-dependent values to backward (e.g. Prod passes the output, which makes
    it non-traceable), and their backward should be implemented entirely in terms
    of operations on autograd Tensors in all cases.

    DON'T USE THIS DECORATOR. IT IS FOR INTERNAL USE ONLY AND SHOULD BE HANDLED WITH
    CARE (or can give incorrect results otherwise).
    T)rJ   )Zfn_clsr   r   r   Ú	traceable{  s    ra   c                       s   e Zd Zd‡ fdd„	Z‡  ZS )ÚInplaceFunctionFc                    s   t t| ƒ ¡  || _d S r"   )r5   rb   r6   Úinplace)r   rc   r;   r   r   r6   Œ  s    zInplaceFunction.__init__)F)r   r   r   r6   r>   r   r   r;   r   rb   Š  s   rb   c                    s   ‡ ‡‡‡fdd„‰ ˆ S )Nc                    s¦   ˆˆ ƒrˆˆ ƒS ˆ d u rd S t ˆ ttfƒr^‡fdd„ˆ D ƒ}tˆ dƒrRtˆ ƒ|Ž S tˆ ƒ|ƒS t ˆ tƒr|‡‡ fdd„ˆ D ƒS tdt ˆ ¡ ˆršdˆ d nd	 ƒ‚d S )
Nc                 3   s   | ]}ˆ |ƒV  qd S r"   r   ©rM   Úx)Ú_mapr   r   rO   ˜  rV   z,_nested_map.<locals>._map.<locals>.<genexpr>Ú_fieldsc                    s   i | ]}|ˆ ˆ| ƒ“qS r   r   rd   )rf   Úobjr   r   Ú
<dictcomp>ž  rV   z-_nested_map.<locals>._map.<locals>.<dictcomp>úAAuto nesting doesn't know how to process an input object of type ú. Accepted types: ú, or lists/tuples of themÚ )	rK   ÚlistrX   Úhasattrr4   ÚdictÚ
ValueErrorr   Útypename)rh   Zmapped©rf   Ú	conditionÚcondition_msgr\   ©rh   r   rf   ’  s(    

ÿþÿüz_nested_map.<locals>._mapr   )rt   r\   ru   r   rs   r   Ú_nested_map‘  s    rw   c                 C   s   t | dƒr|  ¡ S | S )NÚ_jit_unwrap)ro   rx   rv   r   r   r   Ú_jit_unwrap_structured©  s    
ry   Fc                    s   ‡ ‡‡‡‡fdd„‰ ˆ S )Nc                 3   s¾   ˆd urˆ| ƒ} ˆ| ƒr | V  nš| d u r,d S t | ttfƒrZ| D ]}ˆ |ƒD ]
}|V  qJq>n`t | tƒrˆ|  ¡ D ]}ˆ |ƒD ]
}|V  qxqln2ˆr”| V  n&tdt | ¡ ˆr²dˆ d nd ƒ‚d S )Nrj   rk   rl   rm   )rK   rn   rX   rp   Úvaluesrq   r   rr   )rh   ÚorQ   ©Ú_iterÚallow_unknownrt   ru   Ú
conversionr   r   r}   ±  s2    
ÿþÿüz_iter_filter.<locals>._iterr   )rt   r~   ru   r   r   r|   r   Ú_iter_filter¯  s    r€   c                    s   ‡ fdd„‰ ˆ | |ƒd S )Nc                    s€   g }t |dƒr| | ¡S t|ttfƒs:| d | dd … fS |D ]0}|d u rV| |¡ q>ˆ | |ƒ\}} | |¡ q>t|ƒ|ƒ| fS )NÚ	_jit_wrapr   é   )ro   r�   rK   rn   rX   Úappendr4   )ÚinputÚprotoÚresÚeZres_e©Úunflatten_helperr   r   r‰   Ð  s    

z$_unflatten.<locals>.unflatten_helperr   r   )r„   r…   r   rˆ   r   Ú
_unflattenÍ  s    rŠ   c                 C   s   | d u pt | tjjƒS r"   )rK   r   Ú_CÚValue©r{   r   r   r   Ú<lambda>á  rV   rŽ   zjit's Values or None)ru   c                 C   s   t | tjƒS r"   ©rK   r   r   ©re   r   r   r   rŽ   ã  rV   ZTensors)ru   r   c                 C   s   t | tjƒS r"   r�   r�   r   r   r   rŽ   å  rV   TzTensors (permissive))r~   ru   c                 C   s   | d u pt | tjƒS r"   r�   r�   r   r   r   rŽ   è  rV   zTensors or Nonec                 C   s   t | tjƒS r"   r�   r�   r   r   r   rŽ   ê  rV   c                 C   s   | j S r"   )Údatar�   r   r   r   rŽ   ê  rV   c                       s°   e Zd Z‡ fdd„Z‡ fdd„Zeedœdd„ZeZeedœd	d
„Zeddœdd„Z	e
‡ fdd„ƒZeeddœdd„Zeeddœdd„Zeddœdd„Zeddœdd„Z‡  ZS )ÚNestedIOFunctionc                    s8   || _ tt|ƒƒ}tt| ƒj|Ž }| j}t|| jƒ}|S r"   )Ú_nested_inputrX   Ú_iter_tensorsr5   r’   Ú_do_forwardÚ_nested_outputrŠ   )r   r„   Z
flat_inputZflat_outputZnested_outputÚnested_tensorsr;   r   r   r•   ò  s    zNestedIOFunction._do_forwardc                    s(   || _ tt| ƒ ||¡}|s$| `| `|S r"   )Úretain_variablesr5   r’   Ú_do_backwardr–   Ú_to_save_nested)r   Ú	gradientsr˜   Úresultr;   r   r   r™   ú  s    zNestedIOFunction._do_backward)r›   rD   c                 G   s"   t || jƒ}| j|Ž }tt|ƒƒS r"   )rŠ   r–   Úbackward_extendedrX   Ú_iter_None_tensors)r   r›   Znested_gradientsrœ   r   r   r   r+     s    
zNestedIOFunction.backward)r   rD   c                 G   s*   t | jƒ}| j|Ž }| `|| _tt|ƒƒS r"   )Ú_map_tensor_datar“   Úforward_extendedr–   rX   r”   )r   r   r—   rœ   r   r   r   rG   	  s
    

zNestedIOFunction.forwardNc                 G   s   t t|ƒƒ| _|| _d S r"   )rX   r”   r
   rš   r   r   r   r   r     s    z"NestedIOFunction.save_for_backwardc                    s   t t| ƒj}t|| jƒS r"   )r5   r’   Úsaved_tensorsrŠ   rš   )r   Zflat_tensorsr;   r   r   r¡     s    zNestedIOFunction.saved_tensors)r   r@   rD   c                 O   s   t t||fƒƒ| _d S r"   )rX   r”   r   rA   r   r   r   r     s    zNestedIOFunction.mark_dirtyc                 O   s   t t||fƒƒ| _d S r"   )rX   r”   r   rA   r   r   r   r     s    z(NestedIOFunction.mark_non_differentiable)r„   rD   c                 G   s   t ‚d S r"   rE   )r   r„   r   r   r   r      s    z!NestedIOFunction.forward_extended)Úgrad_outputrD   c                 G   s   t ‚d S r"   rE   )r   r¢   r   r   r   r�   "  s    z"NestedIOFunction.backward_extended)r   r   r   r•   r™   r   r+   rB   rG   r   Úpropertyr¡   r   r   r    r�   r>   r   r   r;   r   r’   î  s   r’   )N)FNN)'r   Ztorch._Cr‹   r   Ztorch.utils.hooksÚutilsr#   Z
torch._sixr   r^   r   Úcollectionsr   Útypingr   r   r   Úobjectr   Z_ContextMethodMixinr!   Z_FunctionBaser)   r4   r3   r-   r`   ra   rb   rw   ry   r€   rŠ   Z_iter_jit_valuesr”   Z_iter_tensors_permissiverž   rŸ   r’   r   r   r   r   Ú<module>   sR    $q,
  ÿ
ÿ
ÿþÿÿ