
    rh4              	       ,   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j0                  Z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jH                  d      rejH                  jJ                  Z&ndedefdZ& e#ejH                  d      rejH                  jN                  Z(ndedefdZ(d Z)d Z*de+fdZ,d5dZ- G d de.      Z/de+fdZ0de+fdZ1d6dee   ddfdZ2defdZ3defdZ4d6dee   defdZ5d6dee   defdZ6	 d7dee   ded eddfd!Z7de8eef   fd"Z9d#eeeeegdf   ddfd$Z:d6dee   deeef   fd%Z;d5d&Z<d'efd(Z=deddfd)Z>d6dee   de8eef   fd*Z? G d+ d      Z	 G d, d-      Z@d'ed.   de@fd/ZAd8deeeej                  f   defd0ZB	 d8d1edeeeej                  f   ddfd2ZCdd3lD g d4ZEy)9zH
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_exchangeDevicer   returnc                 $    | dk  ryt        d      Nr   z)PyTorch was compiled without MTIA supportRuntimeErrorr   s    f/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/torch/mtia/__init__.py_exchange_devicer   %       A:FGG    _mtia_maybeExchangeDevicec                 $    | dk  ryt        d      r   r   r   s    r   _maybe_exchange_devicer   /   r   r   c                      t                y N)
_lazy_init r   r   initr#   5   s    Lr   c                  (    t         xr t                S )z9Return whether PyTorch's MTIA state has been initialized.)_initialized_is_in_bad_forkr"   r   r   is_initializedr'   9   s    1 111r   c                  >    t         j                  j                         S r    )torch_C_mtia_isInBadForkr"   r   r   r&   r&   >   s    88%%''r   c            	         t               st        t        d      ry t        5  t               r
	 d d d        y t	               rt        d      t               st        d      t        j                  j                          dt        _        t        j                  d t        j                         D               	 t        D ]  \  } }	  |          	 t)        t        d       dad d d        y # t         $ r1}dt#        |       ddj%                  |       }t'        |      |d }~ww xY w# t)        t        d       w xY w# 1 sw Y   y xY w)	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   | ]	  }|s|  y wr    r"   ).0callss     r   	<genexpr>z_lazy_init.<locals>.<genexpr>d   s     XuRWUXs   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!   B   sL   74):;	 , , , I  ~ *  	  $X0B0L0L0NXX	-/< <+^<M< D+,Y, ,H ! <PQTUVQWPX YCCE77>CZB[]  04!;< D+,W, ,sM   D=BD=9D(C+D(D=+	D%4,D  D%%D((D::D==Ec                       e Zd Zy)r?   N)__name__
__module____qualname__r"   r   r   r?   r?   u   s    r   r?   c                  >    t         j                  j                         S )z*Return true if compiled with MTIA support.)r)   r*   _mtia_isBuiltr"   r   r   r6   r6   y   s    88!!##r   c                  2    t               syt               dkD  S )z'Return true if MTIA device is availableFr   )r6   device_countr"   r   r   is_availablerM   ~   s    >>Ar   c                     t         j                  j                  |       5  t         j                  j	                         cddd       S # 1 sw Y   yxY w)z?Waits for all jobs in all streams on a MTIA device to complete.N)r)   mtiar   r*   _mtia_deviceSynchronizer   s    r   synchronizerQ      s9    			6	" 2xx//12 2 2s   AAc                  >    t         j                  j                         S )z,Return the number of MTIA devices available.)r)   r*   _mtia_getDeviceCountr"   r   r   rL   rL           88((**r   c                  >    t         j                  j                         S )z0Return the index of a currently selected device.)r)   r*   %_accelerator_hooks_get_current_devicer"   r   r   current_devicerW      s    8899;;r   c                 V    t         j                  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\      !     88**+<Vd+STTr   c                 V    t         j                  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).
    TrY   )r)   r*   _mtia_getDefaultStreamr   r   s    r   default_streamr`      r]   r   enabledstacksmax_entriesc                 \    t               syt        j                  j                  | ||       y)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)ra   rb   rc   s      r   record_memory_historyrf      s#     	HH&&wDr   c                  >    t         j                  j                         S )z4Return a dictionary of MTIA memory allocator history)r)   r*   _mtia_memorySnapshotr"   r   r   snapshotri      rT   r   observerc                 B    t         j                  j                  |        y)z9Attach an out-of-memory observer to MTIA memory allocatorN)r)   r*   _mtia_attachOutOfMemoryObserver)rj   s    r   attach_out_of_memory_observerrm      s     
HH,,X6r   c                 V    t         j                  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).
    TrY   )r)   r*   _mtia_getDeviceCapabilityr   r   s    r   get_device_capabilityrp      "     88--.?QU.VWWr   c                  >    t         j                  j                         S )zEmpty the MTIA device cache.)r)   r*   _mtia_emptyCacher"   r   r   empty_cachert      s    88$$&&r   streamc                 H    | yt         j                  j                  |        y)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ru   s    r   
set_streamry      s     ~	HH##F+r   c                 d    t        |       } | dk\  r t        j                  j                  |        yy)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                 V    t         j                  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).
    TrY   )r)   r*   _mtia_getDevicePropertiesr   r   s    r   get_device_propertiesr      rq   r   c                   6    e Zd ZdZd efdZd ZdededefdZy)	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                 6    t        |d      | _        d| _        y )NTrY   r   )r   idxprev_idx)selfr   s     r   __init__zdevice.__init__  s    $Vd;r   c                 `    t         j                  j                  | j                        | _        y r    )r)   r*   (_accelerator_hooks_maybe_exchange_devicer   r   )r   s    r   	__enter__zdevice.__enter__  s    II$((Sr   typevalue	tracebackc                 `    t         j                  j                  | j                        | _        y)NF)r)   r*   r   r   r   )r   r   r   r   s       r   __exit__zdevice.__exit__  s    88DDT]]Sr   N)rF   rG   rH   __doc__r   r   r   r   r"   r   r   r   r     s3    s TS   r   c                   N    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	y)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_streamru   c                    d | _         || _        t        d d      | _        t        j
                  j                         s| j                  d| _        t        j
                  j                         sd nt        j                  j                  d       | _	        t        j
                  j                         sd | _
        y t        j                  j                  d       | _
        y )NTr   )r   ru   r   r   r)   jitis_scriptingrO   r`   src_prev_streamdst_prev_stream)r   ru   s     r   r   zStreamContext.__init__&  s    $T40yy%%'xx 		..0Dejj6O6OPT6U 	 		..0D 	6;jj6O6OPT6U 	r   c                    | j                   }|| j                  dk(  ry t        j                  j	                  d       | _        | j
                  j                  |j                  k7  rLt        |j                        5  t        j                  j	                  |j                        | _        d d d        t        j                  j                  |       y # 1 sw Y   )xY wNr   )	ru   r   r)   rO   r\   r   r   r   ry   )r   r   s     r   r   zStreamContext.__enter__5  s    [[
R$zz88> &&**;*;;
))* T',zz'@'@ARAR'S$T

j)T Ts   ;/CCr   r   r   c                 *   | j                   }|| j                  dk(  ry | j                  j                  |j                  k7  r)t        j
                  j                  | j                         t        j
                  j                  | j                         y r   )ru   r   r   r   r)   rO   ry   r   )r   r   r   r   r   s        r   r   zStreamContext.__exit__D  sj    [[
R &&**;*;;JJ!!$"6"67

d223r   N)
rF   rG   rH   r   r   __annotations__r   r   r   r   r"   r   r   r   r     sF    	 ,--
x(;< 
*4S 4 4 4r   r   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   rx   s    r   ru   ru   R  s       r   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   ]  s4     MM8
 ;;s%++f==r   	new_statec                 <    t        j                  dt        d       y)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   l  s     MM8r   )*)r#   rM   r'   rQ   rL   rW   r\   r`   memory_statsmax_memory_allocatedreset_peak_memory_statsrp   r   rf   ri   rm   rt   r|   ry   ru   r   r   r   )r   Nr    )allpythonr   )rO   )Fr   	threadingr   typingr   r   r   r   r)   r   _devicer   torch._utilsr	   r
   r   torch.typesr   _utilsr   r=   int	_device_tEventStreamr%   r   listtupler   localr4   Lockr5   r:   r3   r*   r   r   r   r   r#   r'   boolr&   r!   r<   r?   r6   rM   rQ   rL   rW   r\   r`   rf   dictri   rm   rp   rt   ry   r|   r   r   ru   r   r   memory__all__r"   r   r   <module>r      s.     1 1  + E E  % '3#$	 		  t	(2t8
d3i
'(  y%y~~' %'  588+,xx44H H H 58801"XX??Hs Hs H2
( (0f	I 	$d $
d 2+ 2t 2+c +< <
	U8I. 	U& 	U	U8I. 	U& 	U PQEc]E,/EILE	E&+$sCx. +7S#s+T127	7X(9"5 XsCx X'
,v ,	?y 	?T 	?X(9"5 Xc3h X (74 74t!8/0 !] !>%S%,, 67 >V >  @F$S#u||%;<	" r   