o
    ki J                  	   @   s  U d Z ddlZddlZddlmZ ddlmZ ddlZddlmZ ddl	m
Z
mZ ddlmZ ddlmZ d	d
lm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 Ze Z e a!e"ejdrwejj#Z$n	de%de%fddZ$e"ejdrejj&Z'n	de%de%fddZ'dd Z(dd Z)dd Z*de+fddZ,djd d!Z-G d"d# d#e.Z/de+fd$d%Z0de+fd&d'Z1dkdeddfd(d)Z2de%fd*d+Z3de%fd,d-Z4dkdedefd.d/Z5dkdedefd0d1Z6	dld4edB d5ed6e%ddfd7d8Z7de8eef fd9d:Z9d;ee%e%e%e%gdf ddfd<d=Z:dmd?e+fd@dAZ;dkdedee%e%f fdBdCZ<djdDdEZ=dFefdGdHZ>deddfdIdJZ?dkdede8eef fdKdLZ@G dMd dZAG dNdO dOZBdPdQ ZCdFedB deBfdRdFZDdndedefdTdUZEdee fdVdWZFdndXededdfdYdZZGd[ee ddfd\d]ZHd^e%ddfd_d`ZId^e%ddfdadbZJde%fdcd^ZKde%fdddeZLde%fdfdgZMd	dhlNT d	dhlOT g diZPdS )ozH
This package enables an interface for accessing MTIA backend in python
    N)Callable)Any)Tensor)	is_fbcodeis_prod)_LazySeedTracker)Device   )_get_device_index .default_generatorsF_queued_calls_mtia_exchangeDevicedevicereturnc                 C      | dk rdS t dNr   z)PyTorch was compiled without MTIA supportRuntimeErrorr   r   r   ]/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/mtia/__init__.py_exchange_device)      r   _mtia_maybeExchangeDevicec                 C   r   r   r   r   r   r   r   _maybe_exchange_device3   r   r   c                   C   s
   t   d S N)
_lazy_initr   r   r   r   init9      
r   c                   C   s   t ot  S )z9Return whether PyTorch's MTIA state has been initialized.)_initialized_is_in_bad_forkr   r   r   r   is_initialized=   s   r"   c                 K   s   t M t r|  W  d    S |ddrt| t  n |ddr.t| t  nt	| t f W d    d S W d    d S W d    d S 1 sRw   Y  d S )Nseed_allFseed)
_initialization_lockr"   get_lazy_seed_trackerqueue_seed_all	tracebackformat_stack
queue_seedr   append)callablekwargsr   r   r   
_lazy_callB   s   "r/   c                   C   
   t j S r   )torch_C_mtia_isInBadForkr   r   r   r   r!   P   r   r!   c                  C   sF  t  sttdr
d S t t  r	 W d    d S t r tdt s'tdt rCt	 rCzddl
m}  |   W n	 tyB   Y nw tj  dt_tdd t D  z1tD ]'\}}z|  W qZ ty } zd	t| d
d| }t||d }~ww W ttd nttd w daW d    d S 1 sw   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!r   )cxx_resource_managerTc                 s   s    | ]}|r|V  qd S r   r   ).0callsr   r   r   	<genexpr>   s    z_lazy_init.<locals>.<genexpr>z6MTIA call failed lazily at initialization with error: z(

MTIA call was originally invoked at:

 )r"   hasattr_tlsr%   r!   r   _is_compiledAssertionErrorr   r   libfb.py.cxx_resourcesr5   installModuleNotFoundErrorr1   r2   
_mtia_initr4   r   extendr'   	get_calls	ExceptionstrjoinDeferredMtiaCallErrordelattrr    )r5   queued_callorig_tracebackemsgr   r   r   r   T   sP   	



"r   c                   @   s   e Zd ZdS )rG   N)__name__
__module____qualname__r   r   r   r   rG      s    rG   c                   C   r0   )z*Return true if compiled with MTIA support.)r1   r2   _mtia_isBuiltr   r   r   r   r<         
r<   c                   C   s   t  sdS t dkS )z'Return true if MTIA device is availableFr   )r<   device_countr   r   r   r   is_available   s   
rS   c                 C   s:   t j|  t j W  d   S 1 sw   Y  dS )z?Waits for all jobs in all streams on a MTIA device to complete.N)r1   mtiar   r2   _mtia_deviceSynchronizer   r   r   r   synchronize   s   $rV   c                   C   r0   )z,Return the number of MTIA devices available.)r1   r2   _mtia_getDeviceCountr   r   r   r   rR         
rR   c                   C   r0   )z0Return the index of a currently selected device.)r1   r2   %_accelerator_hooks_get_current_devicer   r   r   r   current_device   rQ   rZ   c                 C      t jt| d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)r1   r2   _mtia_getCurrentStreamr
   r   r   r   r   current_stream      	r_   c                 C   r[   )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).
    Tr\   )r1   r2   _mtia_getDefaultStreamr
   r   r   r   r   default_stream   r`   rb   allpythonenabledstacksmax_entriesc                 C   s   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"   r1   r2   _mtia_recordMemoryHistory)re   rf   rg   r   r   r   record_memory_history   s   ri   c                   C   r0   )z4Return a dictionary of MTIA memory allocator history)r1   r2   _mtia_memorySnapshotr   r   r   r   snapshot   rX   rk   observerc                 C   s   t j|  dS )z9Attach an out-of-memory observer to MTIA memory allocatorN)r1   r2   _mtia_attachOutOfMemoryObserver)rl   r   r   r   attach_out_of_memory_observer   s   rn   Tincluding_emulationc                 C   s   dS )zLReturn a bool indicating if the current MTIA device supports dtype bfloat16.Tr   )ro   r   r   r   is_bf16_supported   s   rp   c                 C   r[   )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).
    Tr\   )r1   r2   _mtia_getDeviceCapabilityr
   r   r   r   r   get_device_capability      rr   c                   C   r0   )zEmpty the MTIA device cache.)r1   r2   _mtia_emptyCacher   r   r   r   empty_cache   rQ   ru   streamc                 C   s   | du r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)r1   r2   _mtia_setCurrentStreamrv   r   r   r   
set_stream  s   	ry   c                 C   s$   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
   r1   r2   %_accelerator_hooks_set_current_devicer   r   r   r   
set_device  s   r{   c                 C   r[   )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).
    Tr\   )r1   r2   _mtia_getDevicePropertiesr
   r   r   r   r   get_device_properties  rs   r}   c                   @   s<   e Zd ZdZd efddZdd Zdededefd	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                 C   s   t |dd| _d| _d S )NTr\   r   )r
   idxprev_idx)selfr   r   r   r   __init__.  s   
zdevice.__init__c                 C   s   t j| j| _d S r   )r1   r2   (_accelerator_hooks_maybe_exchange_devicer~   r   )r   r   r   r   	__enter__2  s   zdevice.__enter__typevaluer)   c                 C   s   t j| j| _dS )NF)r1   r2   r   r   r~   )r   r   r   r)   r   r   r   __exit__5  s   zdevice.__exit__N)rM   rN   rO   __doc__r   r   r   r   r   r   r   r   r   &  s
    c                   @   sN   e Zd ZU dZedB ed< dedB fddZdd Zd	ed
edefd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.
    N
cur_streamrv   c                 C   st   d | _ || _td d| _tj s| jd u rd| _tj s d ntjd | _	tj s1d | _
d S tjd | _
d S )NTr   )r   rv   r
   r~   r1   jitis_scriptingrT   rb   src_prev_streamdst_prev_stream)r   rv   r   r   r   r   H  s   


zStreamContext.__init__c                 C   s   | j }|d u s| jdkrd S tjd | _| jj|jkr9t|j tj|j| _W d    n1 s4w   Y  tj| d S Nr   )	rv   r~   r1   rT   r_   r   r   r   ry   )r   r   r   r   r   r   W  s   zStreamContext.__enter__r   r   r)   c                 C   sJ   | j }|d u s| jdkrd S | jj|jkrtj| j tj| j d S r   )rv   r~   r   r   r1   rT   ry   r   )r   r   r   r)   r   r   r   r   r   f  s   zStreamContext.__exit__)
rM   rN   rO   r   Stream__annotations__r   r   r   r   r   r   r   r   r   :  s   
 r   c                 C   s   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)r1   r2   _mtia_setStream)	stream_iddevice_indexdevice_typer   r   r   _set_stream_by_idt  rs   r   c                 C   s   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   rx   r   r   r   rv     s   rT   c                 C   s0   t   t| dd}|du rt }t| }| S )a[  Returns the random number generator state of the specified MTIA device 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).

    .. warning::
        This function eagerly initializes MTIA.
    Tr\   N)r   r
   rZ   r   	get_state)r   r~   default_generatorr   r   r   get_rng_state  s   
r   c                  C   s   dd t t D } | S )zRReturns a list of ByteTensor representing the random number states of all devices.c                 S   s   g | ]}t |qS r   )r   )r6   ir   r   r   
<listcomp>  s    z%get_rng_state_all.<locals>.<listcomp>)rangerR   )resultsr   r   r   get_rng_state_all  s   r   	new_statec                    sr   t  stj  jtjdW d   n1 sw   Y  t|dd  du r,t   fdd}t| dS )a8  Sets the random number generator state of the specified MTIA device.

    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).
    )memory_formatNTr\   c                     s   t   } |  d S r   )r   	set_state)r   r~   r   r   r   cb  s   zset_rng_state.<locals>.cb)	r"   r1   r2   _DisableFuncTorchclonecontiguous_formatr
   rZ   r/   )r   r   r   r   r   r   set_rng_state  s   r   
new_statesc                 C   s    t | D ]	\}}t|| qdS )zSets the random number generator state of all devices.

    Args:
        new_states (Iterable of torch.ByteTensor): The desired state for each device.
    N)	enumerater   )r   r   stater   r   r   set_rng_state_all  s   r   r$   c                    $   t    fdd}t|dd dS )a  Sets the seed for generating random numbers for the current MTIA device.
    It's safe to call this function if MTIA is not available; in that case, it is silently ignored.

    Args:
        seed (int): The desired seed.

    .. warning::
        If you are working with a multi-GPU model, this function is insufficient
        to get determinism.  To seed all GPUs, use :func:`manual_seed_all`.
    c                     s   t  } t|  }|  d S r   )rZ   r   manual_seedr~   r   r$   r   r   r     s   zmanual_seed.<locals>.cbTr   Nintr/   r$   r   r   r   r   r     s   r   c                    r   )zSets the seed for generating random numbers on all MTIA devices.
    It's safe to call this function if MTIA is not available; in that case, it is silently ignored.

    Args:
        seed (int): The desired seed.
    c                     s&   t t D ]} t|  }|  qd S r   )r   rR   r   r   )r   r   r   r   r   r     s   zmanual_seed_all.<locals>.cbTr#   Nr   r   r   r   r   manual_seed_all  s   r   c                  C      dd } t | ddS )ax  Sets the seed for generating random numbers to a random number for the current MTIA device.
    It's safe to call this function if MTIA is not available; in that case, it is silently ignored.

    .. warning::
        If you are working with a multi-GPU model, this function will only initialize
        the seed on one GPU.  To initialize all GPUs, use :func:`seed_all`.
    c                  S   s   t  } t|  }| S r   )rZ   r   r$   r   r   r   r   r     s   zseed.<locals>.cbTr   r/   r   r   r   r   r$     s   	c                  C   r   )zSets the seed for generating random numbers to a random number on all MTIA devices.

    It's safe to call this function if MTIA is not available; in that case, it is silently ignored.
    c                  S   s@   d} d}t t D ]}t| }|s| } d}q	||  q	| S )Nr   FT)r   rR   r   r$   r   )random_seedseededr   r   r   r   r   r     s   zseed_all.<locals>.cbTr   r   r   r   r   r   r#     s   r#   c                  C   s   t   t } t|   S )zReturns the current random seed of the current MTIA device.

    .. warning::
        This function eagerly initializes MTIA.
    )r   rZ   r   initial_seed)r~   r   r   r   r     s   r   )*)#r   rS   r"   rV   rR   rZ   r_   rb   memory_statsmax_memory_allocatedmemory_allocatedreset_peak_memory_statsrr   r}   ri   rk   rn   ru   r{   ry   rv   r   r   r   r   r   r   r   r$   r#   r   rp   	MTIAGraphgraphgraph_pool_handle)r   Nr   )rc   rd   r   )T)rT   )Qr   	threadingr)   collections.abcr   typingr   r1   r   torch._environmentr   r   torch._utilsr   torch.typesr   _utilsr
   Eventr   r   tupler2   	Generatorr   r    r   listrE   localr;   Lockr%   r'   r:   r   r   r   r   r   r   r"   r/   boolr!   r   rD   rG   r<   rS   rV   rR   rZ   r_   rb   ri   dictrk   rn   rp   rr   ru   ry   r{   r}   r   r   r   rv   r   r   r   r   r   r   r$   r#   r   memory
mtia_graph__all__r   r   r   r   <module>   s   


>


:
