a
    –¥»a“I  ã                   @   s˜   d dl Z d dlZddlmZ eejdƒsHedƒejjd< edƒejjd< d dlmZ d dlm	Z	 d	d
„ Z
G dd„ dejjƒZG dd„ deƒZdd„ ZdS )é    Né   )Ú_dummy_typeZ_CudaStreamBaseÚ
_CUDAGraphÚ_graph_pool_handle)r   ©r   c                   C   s   t ƒ S )zß
    Returns an opaque token representing the id of a graph memory pool.
    See :ref:`Graph memory management<graph-memory-management>`.

    .. warning::
        This API is in beta and may change in future releases.
    r   © r   r   úK/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/cuda/graphs.pyÚgraph_pool_handle   s    r	   c                       sj   e Zd ZdZ‡ fdd„Z‡ fdd„Zd‡ fdd„	Z‡ fd	d
„Z‡ fdd„Z‡ fdd„Z	‡ fdd„Z
‡  ZS )Ú	CUDAGraphzw
    Wrapper around a CUDA graph.

    .. warning::
        This API is in beta and may change in future releases.
    c                    s   t t| ƒ | ¡S ©N)Úsuperr
   Ú__new__)Úcls©Ú	__class__r   r   r   $   s    zCUDAGraph.__new__c                    s   t t| ƒ ¡  d S r   )r   r
   Ú__init__©Úselfr   r   r   r   '   s    zCUDAGraph.__init__Nc                    s,   |du rt t| ƒ ¡  nt t| ƒ |¡ dS )aX  
        Begins capturing CUDA work on the current stream.

        Typically, you shouldn't call ``capture_begin`` yourself.
        Use :class:`~torch.cuda.graph` or :func:`~torch.cuda.make_graphed_callables`,
        which call ``capture_begin`` internally.

        Arguments:
            pool (optional): Token (returned by :func:`~torch.cuda.graph_pool_handle` or
                :meth:`other_Graph_instance.pool()<torch.cuda.CUDAGraph.pool>`) that hints this graph may share memory
                with the indicated pool.  See :ref:`Graph memory management<graph-memory-management>`.
        N)r   r
   Úcapture_begin)r   Úpoolr   r   r   r   *   s    zCUDAGraph.capture_beginc                    s   t t| ƒ ¡  dS )aP  
        Ends CUDA graph capture on the current stream.
        After ``capture_end``, ``replay`` may be called on this instance.

        Typically, you shouldn't call ``capture_end`` yourself.
        Use :class:`~torch.cuda.graph` or :func:`~torch.cuda.make_graphed_callables`,
        which call ``capture_end`` internally.
        N)r   r
   Úcapture_endr   r   r   r   r   >   s    	zCUDAGraph.capture_endc                    s   t t| ƒ ¡  dS )z?
        Replays the CUDA work captured by this graph.
        N)r   r
   Úreplayr   r   r   r   r   I   s    zCUDAGraph.replayc                    s   t t| ƒ ¡  dS )zD
        Deletes the graph currently held by this instance.
        N)r   r
   Úresetr   r   r   r   r   O   s    zCUDAGraph.resetc                    s   t t| ƒ ¡ S )zí
        Returns an opaque token representing the id of this graph's memory pool.
        This id can optionally be passed to another graph's ``capture_begin``,
        which hints the other graph may share the same memory pool.
        )r   r
   r   r   r   r   r   r   U   s    zCUDAGraph.pool)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r   Ú__classcell__r   r   r   r   r
      s   r
   c                   @   s.   e Zd ZdZdZd	dd„Zdd„ Zdd„ ZdS )
Úgraphaœ  
    Context-manager that captures CUDA work into a :class:`torch.cuda.CUDAGraph`
    object for later replay.

    See :ref:`CUDA Graphs <cuda-graph-semantics>` for a general introduction,
    detailed use, and constraints.

    Arguments:
        cuda_graph (torch.cuda.CUDAGraph): Graph object used for capture.
        pool (optional): Opaque token (returned by a call to :func:`~torch.cuda.graph_pool_handle()` or
            :meth:`other_Graph_instance.pool()<torch.cuda.CUDAGraph.pool>`) hinting this graph's capture
            may share memory from the specified pool. See :ref:`Graph memory management<graph-memory-management>`.
        stream (torch.cuda.Stream, optional): If supplied, will be set as the current stream in the context.
            If not supplied, ``graph`` sets its own internal side stream as the current stream in the context.

    .. note::
        For effective memory sharing, if you pass a ``pool`` used by a previous capture and the previous capture
        used an explicit ``stream`` argument, you should pass the same ``stream`` argument to this capture.

    .. warning::
        This API is in beta and may change in future releases.
    Nc                 C   sl   | j jd u rtj ¡ | j _|d u r&dn|f| _|d ur:|n| j j| _| jd usRJ ‚tj | j¡| _|| _	d S )Nr   )
r   Údefault_capture_streamÚtorchÚcudaÚStreamr   Zcapture_streamÚstreamÚ
stream_ctxÚ
cuda_graph)r   r%   r   r#   r   r   r   r   w   s    zgraph.__init__c                 C   s8   t j ¡  t ¡  t j ¡  | j ¡  | jj	| j
Ž  d S r   )r    r!   ÚsynchronizeÚgcZcollectZempty_cacher$   Ú	__enter__r%   r   r   r   r   r   r   r(   ‡   s
    


zgraph.__enter__c                 C   s   | j  ¡  | j |||¡ d S r   )r%   r   r$   Ú__exit__)r   Úexc_typeÚ	exc_valueÚ	tracebackr   r   r   r)   ”   s    
zgraph.__exit__)NN)r   r   r   r   r   r   r(   r)   r   r   r   r   r   ^   s     ý
r   c                     sL  d}t | tƒsd}| f} ˆf‰t| ˆƒD ]€\}}t |tjjƒrŽt|jƒdkrht|jƒdkrht|j	ƒdkspJ dƒ‚t
dd„ | ¡ D ƒƒsŽJ dƒ‚t
dd„ |D ƒƒs(J d	ƒ‚q(d
d„ ˆD ƒ}dd„ | D ƒ‰ ‡ ‡fdd„tt| ƒƒD ƒ}dd„ tt| ƒƒD ƒ}dd„ tt| ƒƒD ƒ}tƒ }	tj ¡  tj tj ¡ ¡�� t| ˆ|ƒD ]r\}
}}tdƒD ]X}|
|Ž }t |tjƒ�rp|fn|}tjj|tdd„ |D ƒƒtdd„ |D ƒƒddd�}�qP~~�q>W d  ƒ n1 �sÈ0    Y  tj ¡  g }g }t| ˆ|ƒD ]z\}
}}tjj||	d�� |
|Ž }W d  ƒ n1 �s*0    Y  t |tjƒ�rT| d¡ |f}n
| d¡ | |¡ �qðg }g }tt|ƒt|ƒt|ƒtˆ ƒƒD ]ì\}}}}t
dd„ |D ƒƒ�sºJ dƒ‚tdd„ |D ƒƒ}tjj||	d��4 tjj|tdd„ |D ƒƒ|ddd�}W d  ƒ n1 �s0    Y  g }d}|D ]0}|j�rR| || ¡ |d7 }n
| d¡ �q.t|ƒ}| |¡ | |¡ �q’tt|ƒƒ}tt|ƒƒ}dd„ }g }t| ƒD ]ˆ\}}
||| || ˆ | || || || || || || ƒ	}t |
tjjƒ�r(dd„ }||
|
j||
jƒ|
_| |
¡ n
| |¡ �q¬|�rD|d S t|ƒS )aÛ  
    Accepts callables (functions or :class:`nn.Module<torch.nn.Module>`\ s)
    and returns graphed versions.

    Each graphed callable's forward pass runs its source callable's
    forward CUDA work as a CUDA graph inside a single autograd node.

    The graphed callable's forward pass also appends
    a backward node to the autograd graph. During backward, this node runs the
    callable's backward work as a CUDA graph.

    Therefore, each graphed callable should be a drop-in replacement for its source callable
    in an autograd-enabled training loop.

    See :ref:`Partial-network capture<partial-network-capture>` for detailed use and constraints.

    If you pass a tuple of several callables, their captures will use the same memory pool.
    See :ref:`Graph memory management<graph-memory-management>` for when this is appropriate.

    Arguments:
        callables (torch.nn.Module or Python function, or tuple of these): Callable or callables to graph.
            See :ref:`Graph memory management<graph-memory-management>` for when passing a tuple of callables
            is appropriate.  If you pass a tuple of callables, their order in the tuple must be the same order
            they'll run in the live workload.
        sample_args (tuple of Tensors, or tuple of tuples of Tensors): Samples args for each callable.
            If a single callable was passed, ``sample_args`` must be a single tuple of argument Tensors.
            If a tuple of callables was passed, ``sample_args`` must be tuple of tuples of argument Tensors.

    .. note::
        The ``requires_grad`` state of each Tensor in ``sample_args`` must match the state
        that's expected for the corresponding real input in the training loop.

    .. warning::
        This API is in beta and may change in future releases.

    .. warning::
        ``sample_args`` for each callable must be a tuple of Tensors. Other types and keyword args
        are not allowed.

    .. warning::
        Returned callables do not support higher order differentiation (e.g., double backward).

    .. warning::
        In any :class:`~torch.nn.Module` passed to :func:`~make_graphed_callables`, only parameters
        may be trainable. Buffers must have ``requires_grad=False``.

    .. warning::
        After you pass a :class:`torch.nn.Module` through :func:`~make_graphed_callables`,
        you may not add or remove any of that Module's parameters or buffers.

    .. warning::
        :class:`torch.nn.Module`\s passed to :func:`~torch.cuda.make_graphed_callables` must not have module hooks
        registered on them at the time they are passed. However, registering hooks on modules *after* passing them
        through :func:`~torch.cuda.make_graphed_callables` is allowed.

    .. warning::
        When running a graphed callable, you must pass its arguments in the same order and format
        they appeared in that callable's ``sample_args``.

    .. warning::
        All Tensor outputs of graphed callables must require grad.
    FTr   z§Modules must not have hooks registered at the time they are passed. However, registering hooks on modules after passing them through make_graphed_callables is allowed.c                 s   s   | ]}|j d u V  qdS )FN©Úrequires_grad©Ú.0Úbr   r   r   Ú	<genexpr>å   ó    z)make_graphed_callables.<locals>.<genexpr>zœIn any :class:`~torch.nn.Module` passed to :func:`~make_graphed_callables`, only parameters may be trainable. All buffers must have ``requires_grad=False``.c                 s   s   | ]}t |tjƒV  qd S r   )Ú
isinstancer    ÚTensor)r0   Úargr   r   r   r2   è   r3   zxIn the beta API, sample_args for each callable must be a tuple of Tensors. Other types and keyword args are not allowed.c                 S   s   g | ]}t |ƒ‘qS r   )Úlen)r0   Úargsr   r   r   Ú
<listcomp>î   r3   z*make_graphed_callables.<locals>.<listcomp>c                 S   s*   g | ]"}t |tjjƒr"t| ¡ ƒnd ‘qS )r   )r4   r    ÚnnÚModuleÚtupleÚ
parameters)r0   Úcr   r   r   r9   ï   s   ÿc                    s   g | ]}ˆ| ˆ |  ‘qS r   r   ©r0   Úi©Zper_callable_module_paramsÚsample_argsr   r   r9   ñ   s   ÿc                 S   s   g | ]}t j ¡ ‘qS r   ©r    r!   r
   ©r0   Ú_r   r   r   r9   ô   r3   c                 S   s   g | ]}t j ¡ ‘qS r   rC   rD   r   r   r   r9   õ   r3   é   c                 s   s   | ]}|j r|V  qd S r   r-   r?   r   r   r   r2     r3   c                 s   s   | ]}t  |¡V  qd S r   ©r    Z
empty_like©r0   Úor   r   r   r2     r3   )ÚoutputsÚinputsZgrad_outputsZonly_inputsZallow_unusedN)r   c                 s   s   | ]}|j V  qd S r   r-   rH   r   r   r   r2   ,  r3   z/Outputs of graphed callables must require grad.c                 s   s   | ]}t  |¡V  qd S r   rG   rH   r   r   r   r2   -  r3   c                 s   s   | ]}|j r|V  qd S r   r-   r?   r   r   r   r2   1  r3   r   c	           
         s8   G ‡‡‡‡‡‡‡	fdd„dt jjƒ‰ ‡ ‡‡fdd„}	|	S )Nc                       s@   e Zd Ze‡‡‡‡fdd„ƒZeejjj‡ ‡‡fdd„ƒƒZ	dS )zOmake_graphed_callables.<locals>.make_graphed_autograd_function.<locals>.Graphedc                    s`   t ˆƒD ].}ˆ|  ¡ ||  ¡ krˆ|  || ¡ qˆ  ¡  tˆtƒsNJ ‚tdd„ ˆD ƒƒS )Nc                 s   s   | ]}|  ¡ V  qd S r   ©ÚdetachrH   r   r   r   r2   ]  r3   zjmake_graphed_callables.<locals>.make_graphed_autograd_function.<locals>.Graphed.forward.<locals>.<genexpr>)ÚrangeÚdata_ptrÚcopy_r   r4   r<   )ÚctxrK   r@   )Ú	fwd_graphÚlen_user_argsÚstatic_input_surfaceÚstatic_outputsr   r   ÚforwardU  s    zWmake_graphed_callables.<locals>.make_graphed_autograd_function.<locals>.Graphed.forwardc                    sl   t ˆ|ƒD ]8\}}|d u r(|d u sBJ ‚q
| ¡ | ¡ kr
| |¡ q
ˆ  ¡  tˆtƒsZJ ‚tdd„ ˆD ƒƒS )Nc                 s   s"   | ]}|d ur|  ¡ n|V  qd S r   rL   r/   r   r   r   r2   n  r3   zkmake_graphed_callables.<locals>.make_graphed_autograd_function.<locals>.Graphed.backward.<locals>.<genexpr>)ÚziprO   rP   r   r4   r<   )rQ   ZgradsÚgÚgrad)Ú	bwd_graphÚstatic_grad_inputsÚstatic_grad_outputsr   r   Úbackward_  s    zXmake_graphed_callables.<locals>.make_graphed_autograd_function.<locals>.Graphed.backwardN)
r   r   r   ÚstaticmethodrV   r    ÚautogradÚfunctionZonce_differentiabler]   r   )rZ   rR   rS   r[   r\   rT   rU   r   r   ÚGraphedT  s
   	ra   c                     s   ˆ j | ˆ Ž }ˆr|d S |S )Nr   )Úapply)Ú	user_argsÚout)ra   Úmodule_paramsÚoutput_was_tensorr   r   Úfunctionalizedp  s    zVmake_graphed_callables.<locals>.make_graphed_autograd_function.<locals>.functionalized)r    r_   ZFunction)
rR   rZ   re   rS   rf   rT   rU   r\   r[   rg   r   )
ra   rZ   rR   rS   re   rf   r[   r\   rT   rU   r   Úmake_graphed_autograd_functionK  s    	$z>make_graphed_callables.<locals>.make_graphed_autograd_functionc                    s   ‡ ‡‡‡fdd„}|S )Nc                     s   ˆ j ˆkrˆ| Ž S ˆ| Ž S d S r   )Útraining)rc   ©ÚfuncÚgraph_training_stateÚgraphedÚorig_fwdr   r   Únew_fwdˆ  s    
zEmake_graphed_callables.<locals>.make_graphed_forward.<locals>.new_fwdr   )rk   rl   rm   rn   ro   r   rj   r   Úmake_graphed_forward‡  s    z4make_graphed_callables.<locals>.make_graphed_forward)r4   r<   rW   r    r:   r;   r7   Z_backward_hooksZ_forward_hooksZ_forward_pre_hooksÚallÚbuffersrN   r	   r!   r&   r#   r"   r5   r_   rY   r   ÚappendÚreversedr.   ÚlistÚ	enumerateri   rV   ) Z	callablesrB   Zjust_one_callabler>   r8   Zper_callable_len_user_argsZ"per_callable_static_input_surfacesZ
fwd_graphsZ
bwd_graphsZmempoolrk   rT   rE   rJ   Zgrad_inputsZper_callable_static_outputsZper_callable_output_was_tensorrR   Z per_callable_static_grad_outputsZper_callable_static_grad_inputsrU   rZ   re   r\   r[   Zgrad_idxr6   rh   Úretr@   rm   rp   r   rA   r   Úmake_graphed_callablesš   sÌ    ?
,ÿÿ
ÿ
þü
(
þ(

ýÿü&	

/ø
	rx   )r'   r    Ú_utilsr   ÚhasattrZ_CÚ__dict__Ztorch._Cr   r   r	   r
   Úobjectr   rx   r   r   r   r   Ú<module>   s   A<