
    [i7              	          U d Z ddlZddlZddlmZ ddlmZmZmZ ddl	Z	ddl	m
ZmZ ddlmZmZmZ ddlmZ dd	lmZ eeeef         Ze	j        Ze	j        Zd
Zee	j        j        df         ed<   dag a e!eeg df         e!e         f                  ed<    ej"                    Z# ej$                    Z% e            Z& e'e	j        d          re	j        j(        Z)ndedefdZ) e'e	j        d          re	j        j*        Z+ndedefdZ+d Z,d Z-de.fdZ/d@dZ0 G d de1          Z2de.fdZ3de.fdZ4dAdee         ddfdZ5defdZ6defdZ7dAdee         defd Z8dAdee         defd!Z9	 dBd$ee         d%ed&eddfd'Z:de;eef         fd(Z<d)eeeeegdf         ddfd*Z=dCd,e.fd-Z>dAdee         deeef         fd.Z?d@d/Z@d0efd1ZAdeddfd2ZBdAdee         de;eef         fd3ZC G d4 d          Z
 G d5 d6          ZDd7 ZEd0ed8         deDfd9ZFdDdeeee	j
        f         defd;ZG	 dDd<edeeee	j
        f         ddfd=ZHdd>lIT dd>lJT g d?ZKdS )EzH
This package enables an interface for accessing MTIA backend in python
    N)Callable)AnyOptionalUnion)deviceTensor)_dummy_type_LazySeedTrackerclassproperty)Device   )_get_device_index .default_generatorsF_queued_calls_mtia_exchangeDevicer   returnc                 0    | dk     rdS t          d          Nr   z)PyTorch was compiled without MTIA supportRuntimeErrorr   s    F/var/www/icac/venv/lib/python3.11/site-packages/torch/mtia/__init__.py_exchange_devicer   (       A::2FGGG    _mtia_maybeExchangeDevicec                 0    | dk     rdS t          d          r   r   r   s    r   _maybe_exchange_devicer    2   r   r   c                  "    t                       d S N)
_lazy_initr   r   r   initr$   8   s    LLLLLr   c                  .    t           ot                       S )z9Return whether PyTorch's MTIA state has been initialized.)_initialized_is_in_bad_forkr   r   r   is_initializedr(   <   s    1 1 111r   c                  >    t           j                                        S r"   )torch_C_mtia_isInBadForkr   r   r   r'   r'   A   s    8%%'''r   c            	      2   t                      st          t          d          rd S t          5  t                      r	 d d d            d S t	                      rt          d          t                      st          d          t          j	        
                                 dt          _        t                              d t                                          D                        	 t          D ]Z\  } }	  |              # t           $ r=}dt#          |           dd                    |           }t'          |          |d }~ww xY w	 t)          t          d           n# t)          t          d           w xY wdad d d            d S # 1 swxY w Y   d S )	Nis_initializingzwCannot re-initialize MTIA in forked subprocess. To use MTIA with multiprocessing, you must use the 'spawn' start methodzTorch not compiled with MTIA enabled. Ensure you have `import mtia.host_runtime.torch_mtia.dynamic_library` in your python src file and include `//mtia/host_runtime/torch_mtia:torch_mtia` as your target dependency!Tc              3      K   | ]}||V  	d S r"   r   ).0callss     r   	<genexpr>z_lazy_init.<locals>.<genexpr>g   s(      XXuRWXUXXXXXXr   z6MTIA call failed lazily at initialization with error: z(

MTIA call was originally invoked at:

 )r(   hasattr_tls_initialization_lockr'   r   _is_compiledAssertionErrorr*   r+   
_mtia_initr.   r   extend_lazy_seed_tracker	get_calls	ExceptionstrjoinDeferredMtiaCallErrordelattrr&   )queued_callorig_tracebackemsgs       r   r#   r#   E   s;    74):;; 	 , ,  	, , , , , , , ,  	I   ~~ 	 *   	  $XX0B0L0L0N0NXXXXXX	-/< < <+^<KMMMM  < < <]QTUVQWQW ] ]CE77>CZCZ] ]  044!;<< D+,,,,GD+,,,,Y, , , , , , , , , , , , , , , , , ,sT   F
BF*E#7
DE#
E	8EE		E#F#E::FFFc                       e Zd ZdS )r@   N)__name__
__module____qualname__r   r   r   r@   r@   x   s        Dr   r@   c                  >    t           j                                        S )z*Return true if compiled with MTIA support.)r*   r+   _mtia_isBuiltr   r   r   r7   r7   |   s    8!!###r   c                  F    t                      sdS t                      dk    S )z'Return true if MTIA device is availableFr   )r7   device_countr   r   r   is_availablerN      s"    >> u>>Ar   c                     t           j                            |           5  t           j                                        cddd           S # 1 swxY w Y   dS )z?Waits for all jobs in all streams on a MTIA device to complete.N)r*   mtiar   r+   _mtia_deviceSynchronizer   s    r   synchronizerR      s    			6	"	" 2 2x//112 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2s   AAAc                  >    t           j                                        S )z,Return the number of MTIA devices available.)r*   r+   _mtia_getDeviceCountr   r   r   rM   rM           8((***r   c                  >    t           j                                        S )z0Return the index of a currently selected device.)r*   r+   %_accelerator_hooks_get_current_devicer   r   r   current_devicerX      s    899;;;r   c                 ^    t           j                            t          | d                    S )aS  Return the currently selected :class:`Stream` for a given device.

    Args:
        device (torch.device or int, optional): selected device. Returns
            the currently selected :class:`Stream` for the current device, given
            by :func:`~torch.mtia.current_device`, if :attr:`device` is ``None``
            (default).
    Toptional)r*   r+   _mtia_getCurrentStreamr   r   s    r   current_streamr]      (     8**+<Vd+S+S+STTTr   c                 ^    t           j                            t          | d                    S )a=  Return the default :class:`Stream` for a given device.

    Args:
        device (torch.device or int, optional): selected device. Returns
            the default :class:`Stream` for the current device, given by
            :func:`~torch.mtia.current_device`, if :attr:`device` is ``None``
            (default).
    TrZ   )r*   r+   _mtia_getDefaultStreamr   r   s    r   default_streamra      r^   r   allpythonenabledstacksmax_entriesc                 h    t                      sdS t          j                            | ||           dS )a  Enable/Disable the memory profiler on MTIA allocator

    Args:
        enabled (all or state, optional) selected device. Returns
            statistics for the current device, given by current_device(),
            if device is None (default).

        stacks ("python" or "cpp", optional). Select the stack trace to record.

        max_entries (int, optional). Maximum number of entries to record.
    N)r(   r*   r+   _mtia_recordMemoryHistory)rd   re   rf   s      r   record_memory_historyri      s7      	H&&wDDDDDr   c                  >    t           j                                        S )z4Return a dictionary of MTIA memory allocator history)r*   r+   _mtia_memorySnapshotr   r   r   snapshotrl      rU   r   observerc                 D    t           j                            |            dS )z9Attach an out-of-memory observer to MTIA memory allocatorN)r*   r+   _mtia_attachOutOfMemoryObserver)rm   s    r   attach_out_of_memory_observerrp      s      
H,,X66666r   Tincluding_emulationc                     dS )zLReturn a bool indicating if the current MTIA device supports dtype bfloat16.Tr   )rq   s    r   is_bf16_supportedrs      s    4r   c                 ^    t           j                            t          | d                    S )a  Return capability of a given device as a tuple of (major version, minor version).

    Args:
        device (torch.device or int, optional) selected device. Returns
            statistics for the current device, given by current_device(),
            if device is None (default).
    TrZ   )r*   r+   _mtia_getDeviceCapabilityr   r   s    r   get_device_capabilityrv      )     8--.?QU.V.V.VWWWr   c                  >    t           j                                        S )zEmpty the MTIA device cache.)r*   r+   _mtia_emptyCacher   r   r   empty_cacherz      s    8$$&&&r   streamc                 L    | dS t           j                            |            dS )a  Set the current stream.This is a wrapper API to set the stream.
        Usage of this function is discouraged in favor of the ``stream``
        context manager.

    Args:
        stream (Stream): selected stream. This function is a no-op
            if this argument is ``None``.
    N)r*   r+   _mtia_setCurrentStreamr{   s    r   
set_streamr      s*     ~	H##F+++++r   c                 r    t          |           } | dk    r!t          j                            |            dS dS )zSet the current device.

    Args:
        device (torch.device or int): selected device. This function is a no-op
            if this argument is negative.
    r   N)r   r*   r+   %_accelerator_hooks_set_current_devicer   s    r   
set_devicer      s=     v&&F{{66v>>>>> {r   c                 ^    t           j                            t          | d                    S )zReturn a dictionary of MTIA device properties

    Args:
        device (torch.device or int, optional) selected device. Returns
            statistics for the current device, given by current_device(),
            if device is None (default).
    TrZ   )r*   r+   _mtia_getDevicePropertiesr   r   s    r   get_device_propertiesr     rw   r   c                   8    e Zd ZdZd efdZd ZdededefdZdS )	r   zContext-manager that changes the selected device.

    Args:
        device (torch.device or int): device index to select. It's a no-op if
            this argument is a negative integer or ``None``.
    c                 @    t          |d          | _        d| _        d S )NTrZ   r   )r   idxprev_idx)selfr   s     r   __init__zdevice.__init__  s!    $Vd;;;r   c                 X    t           j                            | j                  | _        d S r"   )r*   r+   (_accelerator_hooks_maybe_exchange_devicer   r   )r   s    r   	__enter__zdevice.__enter__  s    II$(SSr   typevalue	tracebackc                 X    t           j                            | j                  | _        dS )NF)r*   r+   r   r   r   )r   r   r   r   s       r   __exit__zdevice.__exit__  s     8DDT]SSur   N)rG   rH   rI   __doc__r   r   r   r   r   r   r   r   r     st         s    T T TS        r   c                   \    e Zd ZU dZed         ed<   ded         fdZd Zdeded	efd
Z	dS )StreamContexta  Context-manager that selects a given stream.

    All MTIA kernels queued within its context will be enqueued on a selected
    stream.

    Args:
        Stream (Stream): selected stream. This manager is a no-op if it's
            ``None``.
    .. note:: Streams are per-device.
    torch.mtia.Stream
cur_streamr{   c                    d | _         || _        t          d d          | _        t          j                                        s| j        d| _        t          j                                        sd nt          j                            d           | _	        t          j                                        sd nt          j                            d           | _
        d S )NTr   )r   r{   r   r   r*   jitis_scriptingrP   ra   src_prev_streamdst_prev_stream)r   r{   s     r   r   zStreamContext.__init__.  s    $T400y%%'' 	x 	..00UDDej6O6OPT6U6U 	 	..00UDDej6O6OPT6U6U 	r   c                    | j         }|| j        dk    rd S t          j                            d           | _        | j        j        |j        k    rUt          |j                  5  t          j                            |j                  | _        d d d            n# 1 swxY w Y   t          j                            |           d S Nr   )	r{   r   r*   rP   r]   r   r   r   r   )r   r   s     r   r   zStreamContext.__enter__=  s    [
RF$z88>> &**;;;
)** T T',z'@'@AR'S'S$T T T T T T T T T T T T T T T
j)))))s   $*BB!Br   r   r   c                     | j         }|| j        dk    rd S | j        j        |j        k    r$t          j                            | j                   t          j                            | j                   d S r   )r{   r   r   r   r*   rP   r   r   )r   r   r   r   r   s        r   r   zStreamContext.__exit__L  sl    [
RF &**;;;J!!$"6777
d233333r   N)
rG   rH   rI   r   r   __annotations__r   r   r   r   r   r   r   r   r      s         	 	 ,----
x(;< 
 
 
 
* * *4S 4 4 4 4 4 4 4 4r   r   c                 H    t           j                            | ||           dS )zset stream specified by the stream id, device index and
        device type

    Args: stream_id (int): stream id in stream pool
          device_index (int): device index in topo
          device_type (int): enum device type
    N)r*   r+   _mtia_setStream)	stream_iddevice_indexdevice_types      r   _set_stream_by_idr   Z  s$     
HYkBBBBBr   r   c                      t          |           S )a,  Wrap around the Context-manager StreamContext that selects a given stream.

    Arguments:
        stream (Stream): selected stream. This manager is a no-op if it's
            ``None``.
    .. note:: In eager mode stream is of type Stream class while in JIT it doesn't support torch.mtia.stream
    )r   r~   s    r   r{   r{   e  s        r   rP   c                 ~    t          j        dt          d           t          j        dgt          j        |           S )zReturns the random number generator state as a ByteTensor.

    Args:
        device (torch.device or int, optional): The device to return the RNG state of.
            Default: ``'mtia'`` (i.e., ``torch.device('mtia')``, the current mtia device).
    z.get_rng_state is not implemented in torch.mtia   
stacklevelr   )dtyper   )warningswarnUserWarningr*   zerosuint8r   s    r   get_rng_stater   p  sC     M8   
 ;s%+f====r   	new_statec                 >    t          j        dt          d           dS )a  Sets the random number generator state.

    Args:
        new_state (torch.ByteTensor): The desired state
        device (torch.device or int, optional): The device to set the RNG state.
            Default: ``'mtia'`` (i.e., ``torch.device('mtia')``, the current mtia device).
    z.set_rng_state is not implemented in torch.mtiar   r   N)r   r   r   )r   r   s     r   set_rng_stater     s0     M8     r   )*)r$   rN   r(   rR   rM   rX   r]   ra   memory_statsmax_memory_allocatedmemory_allocatedreset_peak_memory_statsrv   r   ri   rl   rp   rz   r   r   r{   r   r   r   rs   	MTIAGraphgraphgraph_pool_handle)r   Nr"   )rb   rc   r   )T)rP   )Lr   	threadingr   collections.abcr   typingr   r   r   r*   r   _devicer   torch._utilsr	   r
   r   torch.typesr   _utilsr   r>   int	_device_tEventStreamr   tupler+   	Generatorr   r&   r   listlocalr5   Lockr6   r;   r4   r   r   r   r    r$   r(   boolr'   r#   r=   r@   r7   rN   rR   rM   rX   r]   ra   ri   dictrl   rp   rs   rv   rz   r   r   r   r   r   r{   r   r   memory
mtia_graph__all__r   r   r   <module>r      sI          $ $ $ $ $ $ ' ' ' ' ' ' ' ' ' '  + + + + + + + + E E E E E E E E E E       % % % % % % '3#$	 		57 E%(,c12 7 7 7  t	(2t8
d3i
'(    y%y~'' %%''  758+,, Hx4H H H H H H 758011 H"X?Hs Hs H H H H  2 2 2
( ( ( ( (0 0 0 0f	 	 	 	 	I 	 	 	$d $ $ $ $
d    2 2+ 2t 2 2 2 2+c + + + +< < < < <
	U 	U8I. 	U& 	U 	U 	U 	U	U 	U8I. 	U& 	U 	U 	U 	U PQE Ec]E,/EILE	E E E E&+$sCx. + + + +7S#s+T127	7 7 7 7 4    
X X(9"5 XsCx X X X X' ' ' '
,v , , , ,	?y 	?T 	? 	? 	? 	?X X(9"5 Xc3h X X X X       (74 74 74 74 74 74 74 74tC C C!8/0 !] ! ! ! !> >%S%, 67 >V > > > >  @F $S#u|%;<	   "          r   