a
    h4                     @   s  U d Z ddlZddlZddlmZ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	ag aeeeg df ee f  ed
< e Ze  Z!e Z"e#ej$drej$j%Z&needddZ&e#ej$drej$j'Z(needddZ(dd Z)dd Z*e+dddZ,ddddZ-G dd de.Z/e+dddZ0e+ddd Z1dPee ddd!d"Z2edd#d$Z3edd%d&Z4dQee edd'd(Z5dRee edd)d*Z6dSee eedd-d.d/Z7e8eef dd0d1Z9eeeeegdf dd2d3d4Z:dTee eeef dd5d6Z;ddd7d8Z<ed9d:d;Z=eddd<d=Z>dUee e8eef dd>d?Z?G d@dA dAZ	G dBdC dCZ@edD e@dEdFdGZAdVeeeej	f eddIdJZBdWeeeeej	f ddKdLdMZCddNlDT g dOZEdS )XzH
This package enables an interface for accessing MTIA backend in python
    N)AnyCallableOptionalUnion)deviceTensor)_dummy_type_LazySeedTrackerclassproperty)Device   )_get_device_indexF_queued_calls_mtia_exchangeDevice)r   returnc                 C   s   | dk rdS t dd S Nr   z)PyTorch was compiled without MTIA supportRuntimeErrorr    r   A/var/www/auris/lib/python3.9/site-packages/torch/mtia/__init__.py_exchange_device%   s    r   _mtia_maybeExchangeDevicec                 C   s   | dk rdS t dd S r   r   r   r   r   r   _maybe_exchange_device/   s    r   c                   C   s
   t   d S N)
_lazy_initr   r   r   r   init5   s    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_initialized9   s    r    )r   c                   C   s
   t j S r   )torch_CZ_mtia_isInBadForkr   r   r   r   r   >   s    r   c                  C   s  t  sttdrd S t t  r0W d    d S t r>tdt sLtdtj	
  dt_tdd t D  zptD ]\\} }z
|   W qz ty } z0dt| dd	| }t||W Y d }~qzd }~0 0 qzW ttd nttd 0 daW d    n1 s0    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                 s   s   | ]}|r|V  qd S r   r   ).0Zcallsr   r   r   	<genexpr>d       z_lazy_init.<locals>.<genexpr>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"   Z
_mtia_initr#   r   extend_lazy_seed_trackerZ	get_calls	ExceptionstrjoinDeferredMtiaCallErrordelattrr   )Zqueued_callZorig_tracebackemsgr   r   r   r   B   s8    

$r   c                   @   s   e Zd ZdS )r2   N)__name__
__module____qualname__r   r   r   r   r2   u   s   r2   c                   C   s
   t j S )z*Return true if compiled with MTIA support.)r!   r"   Z_mtia_isBuiltr   r   r   r   r+   y   s    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    r:   c                 C   s:   t j|  t j W  d   S 1 s,0    Y  dS )z?Waits for all jobs in all streams on a MTIA device to complete.N)r!   mtiar   r"   Z_mtia_deviceSynchronizer   r   r   r   synchronize   s    r<   c                   C   s
   t j S )z,Return the number of MTIA devices available.)r!   r"   Z_mtia_getDeviceCountr   r   r   r   r9      s    r9   c                   C   s
   t j S )z0Return the index of a currently selected device.)r!   r"   Z%_accelerator_hooks_get_current_devicer   r   r   r   current_device   s    r=   c                 C   s   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)r!   r"   Z_mtia_getCurrentStreamr   r   r   r   r   current_stream   s    	r@   c                 C   s   t jt| d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).
    Tr>   )r!   r"   Z_mtia_getDefaultStreamr   r   r   r   r   default_stream   s    	rA   allpython)enabledstacksmax_entriesr   c                 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    r!   r"   Z_mtia_recordMemoryHistory)rD   rE   rF   r   r   r   record_memory_history   s    rG   c                   C   s
   t j S )z4Return a dictionary of MTIA memory allocator history)r!   r"   Z_mtia_memorySnapshotr   r   r   r   snapshot   s    rH   )observerr   c                 C   s   t j|  dS )z9Attach an out-of-memory observer to MTIA memory allocatorN)r!   r"   Z_mtia_attachOutOfMemoryObserver)rI   r   r   r   attach_out_of_memory_observer   s    rJ   c                 C   s   t jt| d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).
    Tr>   )r!   r"   Z_mtia_getDeviceCapabilityr   r   r   r   r   get_device_capability   s    rK   c                   C   s
   t j S )zEmpty the MTIA device cache.)r!   r"   Z_mtia_emptyCacher   r   r   r   empty_cache   s    rL   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)r!   r"   Z_mtia_setCurrentStreamrM   r   r   r   
set_stream   s    	rO   c                 C   s    t | } | dkrtj|  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"   Z%_accelerator_hooks_set_current_devicer   r   r   r   
set_device   s    rP   c                 C   s   t jt| d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).
    Tr>   )r!   r"   Z_mtia_getDevicePropertiesr   r   r   r   r   get_device_properties   s    rQ   c                   @   s8   e Zd ZdZedddZdd Zeeed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``.
    r   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   )r!   r"   (_accelerator_hooks_maybe_exchange_devicerR   rS   )rT   r   r   r   	__enter__  s    zdevice.__enter__typevalue	tracebackc                 C   s   t j| j| _dS )NF)r!   r"   rV   rS   rR   )rT   rY   rZ   r[   r   r   r   __exit__  s    zdevice.__exit__N)r6   r7   r8   __doc__r   rU   rW   r\   r   r   r   r   r     s   r   c                   @   sJ   e Zd ZU dZed ed< ed dddZdd Zeeed	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.
    torch.mtia.Stream
cur_streamrM   c                 C   sn   d | _ || _td d| _tj s2| jd u r2d| _tj s@d n
tjd | _	tj s\d n
tjd | _
d S )NTr   )r`   rN   r   rR   r!   ZjitZis_scriptingr;   rA   src_prev_streamdst_prev_stream)rT   rN   r   r   r   rU   &  s    

zStreamContext.__init__c                 C   s   | j }|d u s| jdkrd S tjd | _| jj|jkrrt|j  tj|j| _W d    n1 sh0    Y  tj| d S Nr   )	rN   rR   r!   r;   r@   ra   r   rb   rO   )rT   r`   r   r   r   rW   5  s    .zStreamContext.__enter__rX   c                 C   sJ   | j }|d u s| jdkrd S | jj|jkr8tj| j tj| j d S rc   )rN   rR   ra   r   r!   r;   rO   rb   )rT   rY   rZ   r[   r`   r   r   r   r\   D  s    zStreamContext.__exit__N)
r6   r7   r8   r]   r   __annotations__rU   rW   r   r\   r   r   r   r   r^     s
   
r^   r_   )rN   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^   rM   r   r   r   rN   R  s    rN   r;   c                 C   s$   t jdtdd tjdgtj| d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   )Zdtyper   )warningswarnUserWarningr!   zerosZuint8r   r   r   r   get_rng_state]  s    rl   )	new_stater   r   c                 C   s   t jdtd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.mtiare   rf   N)rh   ri   rj   )rm   r   r   r   r   set_rng_statel  s
    
rn   )*)r   r:   r    r<   r9   r=   r@   rA   Zmemory_statsZmax_memory_allocatedZreset_peak_memory_statsrK   rQ   rG   rH   rJ   rL   rP   rO   rN   r   rn   rl   )N)N)N)rB   rC   r   )N)N)r;   )r;   )Fr]   	threadingrh   typingr   r   r   r   r!   r   Z_devicer   Ztorch._utilsr   r	   r
   Ztorch.typesr   _utilsr   r0   intZ	_device_tEventZStreamr   r   listtuplerd   localr)   Lockr*   r.   r(   r"   r   r   r   r   r   r    boolr   r   r/   r2   r+   r:   r<   r9   r=   r@   rA   rG   dictrH   rJ   rK   rL   rO   rP   rQ   r^   rN   rl   rn   Zmemory__all__r   r   r   r   <module>   s|   

3 
: 