o
    j9:j                     @   sN   d dl Z d dlmZ d dlmZ d dlZd dlmZ G dd deZdgZ	dS )    N)Literal)Self)_acceleratorGraphc                
       s(  e Zd ZdZ	d%ddddedeeef dB ded	 d
ef fddZ		d%ddddedeeef dB ded	 d
df fddZ
d& fddZd& fddZd& fddZd& fddZd& fddZd
eeef f fddZd& fddZded
df fddZd&d d!Zd"ed
dfd#d$Z  ZS )'Grapha\  
    Wrapper around an :ref:`accelerator<accelerators>` graph that supports capture and replay.

    A graph captures a sequence of operations and their dependencies, allowing them to be
    replayed efficiently with reduced overhead. This class can be used as a context manager
    to automatically capture operations on the current stream.

    Arguments:
        keep_graph (bool, optional): If ``False``, the underlying graph is destroyed and the
            executable graph is instantiated on the GPU at the end of ``capture_end``.
            If ``True``, the underlying graph is preserved after ``capture_end``. In this case,
            the executable graph is not instantiated automatically; it must be explicitly created
            by calling ``instantiate``, or it will be instantiated on the first call to ``replay``.
            Defaults to ``False``.
        pool (tuple[int, int], optional): Memory pool identifier for this graph. Multiple graphs
            can share the same pool by passing the same identifier, which can reduce memory overhead.
            Defaults to ``None``.
        capture_error_mode (Literal["default", "global", "thread_local", "relaxed"], optional):
            Specifies the behavior of graph capture. The exact semantics are backend-specific.
            ``"default"``: backend-defined default capture behavior.
            ``"global"``: potentially unsafe API calls are prohibited. Errors may occur if capture
            in the current thread affects other threads.
            ``"thread_local"``: potentially unsafe API calls are prohibited. Errors occur only if
            capture in the current thread affects itself.
            ``"relaxed"``: the current thread is allowed to make potentially unsafe API calls, except
            for calls that inherently conflict with stream capture.
            Default: ``"default"``.

    Example::

        >>> # xdoctest: +SKIP
        >>> x = torch.zeros([2000], device=0)

        >>> stream = torch.Stream()
        >>> graph = torch.accelerator.Graph()
        >>> with stream, graph:
        ...     x += 1

        >>> graph.replay()
    FNdefaultpoolcapture_error_mode
keep_graphr   r	   )r   globalthread_localrelaxedreturnc                   s   t  | |S N)super__new__)clsr
   r   r	   	__class__ _/home/nk/hobo-godmode/plappi-mvp/.venv/lib/python3.10/site-packages/torch/accelerator/graphs.pyr   3   s   	zGraph.__new__c                   s   t  | || _|| _d S r   )r   __init__
graph_poolr	   )selfr
   r   r	   r   r   r   r   >   s   	
zGraph.__init__c                    s   t  j| j| jd dS )a  
        Begin graph capture on the current stream.

        All operations on the current stream after this call will be recorded into the graph until
        ``capture_end`` is called, using the memory pool and capture error mode provided at construction time.
        r   N)r   capture_beginr   r	   r   r   r   r   r   L   s   
zGraph.capture_beginc                       t    dS )z
        End graph capture on the current stream of the current device.

        After this call, the graph can be replayed via ``replay``.
        N)r   capture_endr   r   r   r   r   W      zGraph.capture_endc                    r   )z
        Instantiate the underlying graph. Will be called by ``capture_end``
        if ``keep_graph=False``, or by ``replay`` if ``keep_graph=True`` and
        ``instantiate`` has not already been explicitly called.
        N)r   instantiater   r   r   r   r   _   r   zGraph.instantiatec                    r   )z'Replay the work captured by this graph.N)r   replayr   r   r   r   r    g   s   zGraph.replayc                    r   )z
        Delete the graph currently held by this instance.

        After this call, the graph can be recaptured. Set :attr:`graph_pool` or
        :attr:`capture_error_mode` beforehand to use different settings on the next capture.
        N)r   resetr   r   r   r   r!   k   s   zGraph.resetc                    
   t   S )aT  
        Return 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.

        Example::
            >>> # xdoctest: +SKIP
            >>> g1 = torch.accelerator.Graph()
            >>> g1.capture_begin()
            >>> # ... operations ...
            >>> g1.capture_end()

            >>> # Share g1's memory pool with a new graph
            >>> pool_id = g1.pool()
            >>> g2 = torch.accelerator.Graph(pool=pool_id)
        )r   r   r   r   r   r   r   t   s   
z
Graph.poolc                    r"   )z)Enable debugging mode for ``debug_dump``.)r   enable_debug_moder   r   r   r   r#      s   
zGraph.enable_debug_modepathc                    s   t  |S )a.  
        Dump the captured graph to a file for debugging purposes if the debugging is
        enabled via ``enable_debug_mode``.

        Arguments:
            path (str): Path to dump the graph to.

        Example::
            >>> # xdoctest: +SKIP
            >>> s = torch.Stream()
            >>> g = torch.accelerator.Graph()
            >>> g.enable_debug_mode()

            >>> with s, g:
            >>> # ... operations ...

            >>> # Dump captured graph to a file "graph_dump.dot"
            >>> g.debug_dump("graph_dump.dot")
        )r   
debug_dump)r   r$   r   r   r   r%      s   zGraph.debug_dumpc                 C   s<   t j  t jjjrt  t j  t j	  | 
  d S r   )torchacceleratorsynchronizecompilerconfigforce_cudagraph_gcgccollectempty_cacheempty_host_cacher   r   r   r   r   	__enter__   s   



zGraph.__enter__exc_infoc                 G   s   |    d S r   )r   )r   r1   r   r   r   __exit__   s   zGraph.__exit__)F)r   N)__name__
__module____qualname____doc__booltupleintr   r   r   r   r   r   r   r    r!   r   r#   strr%   r0   objectr2   __classcell__r   r   r   r   r   	   sT    +	
r   )
r,   typingr   typing_extensionsr   r&   torch._Cr   r   __all__r   r   r   r   <module>   s     
)