a
    Ž¥»a…/  ã                   @   s´   d dl Z d dlZd dlmZmZmZmZ eedf ee jdf dœdd„Zee ddœdd„Z	eee
 ee j f d	œd
d„Zdd	œdd„ZG dd„ de jjƒZdd„ Zdd„ ZdS )é    N)ÚAnyÚIterableÚListÚTuple.)ÚinputsÚreturnc                 C   sf   t | tƒrRg }| D ]6}t |tjƒs.| |¡ q| ¡ }|j|_| |¡ qt|ƒS tdt| ƒj	ƒ‚d S )Nz@Only tuple of tensors is supported. Got Unsupported input type: )
Ú
isinstanceÚtupleÚtorchÚTensorÚappendÚdetachÚrequires_gradÚRuntimeErrorÚtypeÚ__name__)r   ÚoutÚinpÚx© r   úP/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/utils/checkpoint.pyÚdetach_variable   s    


ÿr   c                 C   s    t dd„ | D ƒƒst d¡ d S )Nc                 s   s    | ]}t |tjƒr|jV  qd S ©N)r   r
   r   r   ©Ú.0r   r   r   r   Ú	<genexpr>   ó    z*check_backward_validity.<locals>.<genexpr>zBNone of the inputs have requires_grad=True. Gradients will be None)ÚanyÚwarningsÚwarn)r   r   r   r   Úcheck_backward_validity   s    r    )r   c               	   G   sh   t tdd„ | D ƒƒƒ}g }|D ]@}tj |¡�  | tj ¡ ¡ W d   ƒ q1 sT0    Y  q||fS )Nc                 s   s(   | ] }t |tjƒr|jr| ¡ V  qd S r   )r   r
   r   Zis_cudaZ
get_device©r   Úargr   r   r   r   &   s   ÿz$get_device_states.<locals>.<genexpr>)ÚlistÚsetr
   ÚcudaÚdevicer   Úget_rng_state)ÚargsÚfwd_gpu_devicesÚfwd_gpu_statesr&   r   r   r   Úget_device_states#   s    0r+   c              	   C   sP   t | |ƒD ]@\}}tj |¡� tj |¡ W d   ƒ q
1 s@0    Y  q
d S r   )Úzipr
   r%   r&   Úset_rng_state)ÚdevicesZstatesr&   Ústater   r   r   Úset_device_states1   s    r0   c                   @   s$   e Zd Zedd„ ƒZedd„ ƒZdS )ÚCheckpointFunctionc                 G   sê   t |ƒ || _|| _t ¡ | _|rPt ¡ | _d| _tj	j
rPd| _t|Ž \| _| _g | _g | _g }t|ƒD ]B\}}t |¡rž| |¡ | j |¡ | j d ¡ qh| j |¡ qh| j|Ž  t ¡ � ||Ž }W d   ƒ n1 sÜ0    Y  |S )NFT)r    Úrun_functionÚpreserve_rng_stater
   Zis_autocast_enabledÚhad_autocast_in_fwdr'   Úfwd_cpu_stateÚhad_cuda_in_fwdr%   Ú_initializedr+   r)   r*   r   Útensor_indicesÚ	enumerateÚ	is_tensorr   Zsave_for_backwardZno_grad)Úctxr2   r3   r(   Ztensor_inputsÚir"   Úoutputsr   r   r   Úforward9   s.    





&zCheckpointFunction.forwardc              
   G   sÊ  t j ¡ stdƒ‚t| jƒ}| j}| j}t|ƒD ]\}}|| ||< q0g }| j	r\| j
r\| j}t jj|| j	d��¤ | j	r–t  | j¡ | j
r–t| j| jƒ tt|ƒƒ}t  ¡ �J t jj | j¡� | j|Ž }	W d   ƒ n1 sÜ0    Y  W d   ƒ n1 sú0    Y  W d   ƒ n1 �s0    Y  t|	t jƒ�r8|	f}	g }
g }tt|	ƒƒD ]>}t  |	| ¡�rL|	| j�rL|
  |	| ¡ |  || ¡ �qLt|
ƒdk�r¢tdƒ‚t j !|
|¡ tdd„ |D ƒƒ}d| S )Nz¢Checkpointing is not compatible with .grad() or when an `inputs` parameter is passed to .backward(). Please use .backward() and do not pass its `inputs` argument.)r.   Zenabledr   zInone of output has requires_grad=True, this checkpoint() is not necessaryc                 s   s$   | ]}t |tjƒr|jnd V  qd S r   )r   r
   r   Zgradr   r   r   r   r   ‹   s   ÿz.CheckpointFunction.backward.<locals>.<genexpr>)NN)"r
   ÚautogradZ_is_checkpoint_validr   r#   r   r8   Zsaved_tensorsr9   r3   r6   r)   ÚrandomZfork_rngr-   r5   r0   r*   r   r	   Zenable_gradr%   ÚampZautocastr4   r2   r   r   ÚrangeÚlenr:   r   r   Úbackward)r;   r(   r   r8   Ztensorsr<   ÚidxZrng_devicesZdetached_inputsr=   Zoutputs_with_gradZargs_with_gradZgradsr   r   r   rD   ]   sJ    
ÿ
fÿÿzCheckpointFunction.backwardN)r   Ú
__module__Ú__qualname__Ústaticmethodr>   rD   r   r   r   r   r1   7   s   
#r1   c                 O   s@   |  dd¡}|r,tdd dd„ |D ƒ¡ ƒ‚tj| |g|¢R Ž S )a*  Checkpoint a model or part of the model

    Checkpointing works by trading compute for memory. Rather than storing all
    intermediate activations of the entire computation graph for computing
    backward, the checkpointed part does **not** save intermediate activations,
    and instead recomputes them in backward pass. It can be applied on any part
    of a model.

    Specifically, in the forward pass, :attr:`function` will run in
    :func:`torch.no_grad` manner, i.e., not storing the intermediate
    activations. Instead, the forward pass saves the inputs tuple and the
    :attr:`function` parameter. In the backwards pass, the saved inputs and
    :attr:`function` is retrieved, and the forward pass is computed on
    :attr:`function` again, now tracking the intermediate activations, and then
    the gradients are calculated using these activation values.

    The output of :attr:`function` can contain non-Tensor values and gradient
    recording is only performed for the Tensor values. Note that if the output
    consists of nested structures (ex: custom objects, lists, dicts etc.)
    consisting of Tensors, these Tensors nested in custom structures will not
    be considered as part of autograd.

    .. warning::
        Checkpointing currently only supports :func:`torch.autograd.backward`
        and only if its `inputs` argument is not passed. :func:`torch.autograd.grad`
        is not supported.

    .. warning::
        If :attr:`function` invocation during backward does anything different
        than the one during forward, e.g., due to some global variable, the
        checkpointed version won't be equivalent, and unfortunately it can't be
        detected.

    .. warning::
        If checkpointed segment contains tensors detached from the computational
        graph by `detach()` or `torch.no_grad()`, the backward pass will raise an
        error. This is because `checkpoint` makes all the outputs require
        gradients which causes issues when a tensor is defined to have no
        gradient in the model. To circumvent this, detach the tensors outside of
        the `checkpoint` function.

    .. warning::
        At least one of the inputs needs to have :code:`requires_grad=True` if
        grads are needed for model inputs, otherwise the checkpointed part of the
        model won't have gradients. At least one of the outputs needs to have
        :code:`requires_grad=True` as well.

    Args:
        function: describes what to run in the forward pass of the model or
            part of the model. It should also know how to handle the inputs
            passed as the tuple. For example, in LSTM, if user passes
            ``(activation, hidden)``, :attr:`function` should correctly use the
            first input as ``activation`` and the second input as ``hidden``
        preserve_rng_state(bool, optional, default=True):  Omit stashing and restoring
            the RNG state during each checkpoint.
        args: tuple containing inputs to the :attr:`function`

    Returns:
        Output of running :attr:`function` on :attr:`*args`
    r3   TúUnexpected keyword arguments: ú,c                 s   s   | ]
}|V  qd S r   r   r!   r   r   r   r   Ñ   r   zcheckpoint.<locals>.<genexpr>)ÚpopÚ
ValueErrorÚjoinr1   Úapply)Úfunctionr(   ÚkwargsÚpreserver   r   r   Ú
checkpoint‘   s    >rR   c           	      K   s¶   |  dd¡}|r,tdd dd„ |D ƒ¡ ƒ‚dd„ }t| tjjƒrNt|  ¡ ƒ} t	| ƒ| }d	}t
d
||d  |ƒD ]&}|| d }t|||| ƒ||d�}qr||d t	| ƒd | ƒ|ƒS )aØ  A helper function for checkpointing sequential models.

    Sequential models execute a list of modules/functions in order
    (sequentially). Therefore, we can divide such a model in various segments
    and checkpoint each segment. All segments except the last will run in
    :func:`torch.no_grad` manner, i.e., not storing the intermediate
    activations. The inputs of each checkpointed segment will be saved for
    re-running the segment in the backward pass.

    See :func:`~torch.utils.checkpoint.checkpoint` on how checkpointing works.

    .. warning::
        Checkpointing currently only supports :func:`torch.autograd.backward`
        and only if its `inputs` argument is not passed. :func:`torch.autograd.grad`
        is not supported.

    .. warning:
        At least one of the inputs needs to have :code:`requires_grad=True` if
        grads are needed for model inputs, otherwise the checkpointed part of the
        model won't have gradients.

    .. warning:
        Since PyTorch 1.4, it allows only one Tensor as the input and
        intermediate outputs, just like :class:`torch.nn.Sequential`.

    Args:
        functions: A :class:`torch.nn.Sequential` or the list of modules or
            functions (comprising the model) to run sequentially.
        segments: Number of chunks to create in the model
        input: A Tensor that is input to :attr:`functions`
        preserve_rng_state(bool, optional, default=True):  Omit stashing and restoring
            the RNG state during each checkpoint.

    Returns:
        Output of running :attr:`functions` sequentially on :attr:`*inputs`

    Example:
        >>> model = nn.Sequential(...)
        >>> input_var = checkpoint_sequential(model, chunks, input_var)
    r3   TrI   rJ   c                 s   s   | ]
}|V  qd S r   r   r!   r   r   r   r     r   z(checkpoint_sequential.<locals>.<genexpr>c                    s   ‡ ‡‡fdd„}|S )Nc                    s$   t ˆˆ d ƒD ]}ˆ| | ƒ} q| S )Né   )rB   )ÚinputÚj©ÚendÚ	functionsÚstartr   r   r>     s    z<checkpoint_sequential.<locals>.run_function.<locals>.forwardr   )rY   rW   rX   r>   r   rV   r   r2     s    z+checkpoint_sequential.<locals>.run_functionéÿÿÿÿr   rS   )r3   )rK   rL   rM   r   r
   ÚnnZ
Sequentialr#   ÚchildrenrC   rB   rR   )	rX   ÚsegmentsrT   rP   rQ   r2   Zsegment_sizerW   rY   r   r   r   Úcheckpoint_sequentialÖ   s    *ÿr^   )r
   r   Útypingr   r   r   r   r   r   r    Úintr+   r0   r?   ZFunctionr1   rR   r^   r   r   r   r   Ú<module>   s   " ZE