
    ΅iG              	          % S r SSKrSSKrSSKJr  SSKJr  SSKrSSKJr  SSK	J
r
  SSKJr  SS	KJr  \R                  r\R                   rS
r\\R&                  R(                  S4   \S'   Sq/ q\\\/ S4   \\   4      \S'   \R4                  " 5       r\R8                  " 5       r\
" 5       q\" \R&                  S5      (       a  \R&                  R@                  r!O	S\"S\"4S jr!\" \R&                  S5      (       a  \R&                  RF                  r$O	S\"S\"4S jr$S r%S r&S r'S\(4S jr)SES jr* " S S\+5      r,S\(4S jr-S\(4S jr.SFS\SS4S jjr/S\"4S jr0S\"4S  jr1SFS\S\4S! jjr2SFS\S\4S" jjr3 SGS#\S-  S$\S%\"SS4S& jjr4S\5\\4   4S' jr6S(\\"\"\"\"/S4   SS4S) jr7SHS*\(4S+ jjr8SFS\S\\"\"4   4S, jjr9SES- jr:S.\4S/ jr;S\SS4S0 jr<SFS\S\5\\4   4S1 jjr= " S2 S5      r> " S3 S45      r?S5 r@S.\S-  S\?4S6 jrASIS\S\4S7 jjrBS\\   4S8 jrCSIS9\S\SS4S: jjrDS;\\   SS4S< jrES=\"SS4S> jrFS=\"SS4S? jrGS\"4S@ jrHS\"4SA jrIS\"4SB jrJSSCKK7  SSCKL7  / SDQrMg)JzH
This package enables an interface for accessing MTIA backend in python
    N)Callable)Any)Tensor)_LazySeedTracker)Device   )_get_device_index .default_generatorsF_queued_calls_mtia_exchangeDevicedevicereturnc                 &    U S:  a  g[        S5      eNr   z)PyTorch was compiled without MTIA supportRuntimeErrorr   s    M/home/james-whalen/.local/lib/python3.13/site-packages/torch/mtia/__init__.py_exchange_devicer   (       A:FGG    _mtia_maybeExchangeDevicec                 &    U S:  a  g[        S5      er   r   r   s    r   _maybe_exchange_devicer   2   r   r   c                      [        5         g N)
_lazy_initr
   r   r   initr    8   s    Lr   c                  :    [         =(       a    [        5       (       + $ )z9Return whether PyTorch's MTIA state has been initialized.)_initialized_is_in_bad_forkr
   r   r   is_initializedr$   <   s    1 111r   c                    [            [        5       (       a  U " 5       sS S S 5        $ UR                  SS5      (       a*  [        R	                  U [
        R                  " 5       5        OkUR                  SS5      (       a*  [        R                  U [
        R                  " 5       5        O*[        R                  U [
        R                  " 5       45        S S S 5        g ! , (       d  f       g = f)Nseed_allFseed)
_initialization_lockr$   get_lazy_seed_trackerqueue_seed_all	tracebackformat_stack
queue_seedr   append)callablekwargss     r   
_lazy_callr2   A   s    	: 
	
 zz*e,,"11(I<R<R<TUFE**"--h	8N8N8PQ$$h	0F0F0H%IJ 
		s   CB,C
C*c                  >    [         R                  R                  5       $ r   )torch_C_mtia_isInBadForkr
   r   r   r#   r#   O   s    88%%''r   c            	         [        5       (       d  [        [        S5      (       a  g [           [        5       (       a
   S S S 5        g [	        5       (       a  [        S5      e[        5       (       d  [        S5      e[        R                  R                  5         S[        l        [        R                  S [        R                  5        5       5         [         H  u  p U " 5         M     [)        [        S5        SqS S S 5        g ! [          a1  nS[#        U5       SSR%                  U5       3n['        U5      UeS nAff = f! [)        [        S5        f = f! , (       d  f       g = f)	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   6   #    U  H  o(       d  M  Uv   M     g 7fr   r
   ).0callss     r   	<genexpr>_lazy_init.<locals>.<genexpr>u   s     X0NuRWUU0Ns   
	z6MTIA call failed lazily at initialization with error: z(

MTIA call was originally invoked at:

 )r$   hasattr_tlsr(   r#   r   _is_compiledAssertionErrorr4   r5   
_mtia_initr8   r   extendr*   	get_calls	ExceptionstrjoinDeferredMtiaCallErrordelattrr"   )queued_callorig_tracebackemsgs       r   r   r   S   sH   74):;;	  
	 I  ~~ *  	  $X0B0L0L0NXX	-/<+<M 0= D+,Y 
	H ! <PQTUVQWPX YCCE77>CZB[]  04!;< D+,W 
	sN   EBEED%E)E
D?,D::D??EEE
E%c                       \ rS rSrSrg)rI      r
   N)__name__
__module____qualname____firstlineno____static_attributes__r
   r   r   rI   rI      s    r   rI   c                  >    [         R                  R                  5       $ )z*Return true if compiled with MTIA support.)r4   r5   _mtia_isBuiltr
   r   r   rA   rA      s    88!!##r   c                  <    [        5       (       d  g[        5       S:  $ )z'Return true if MTIA device is availableFr   )rA   device_countr
   r   r   is_availablerZ      s    >>>Ar   c                     [         R                  R                  U 5         [         R                  R	                  5       sSSS5        $ ! , (       d  f       g= f)z?Waits for all jobs in all streams on a MTIA device to complete.N)r4   mtiar   r5   _mtia_deviceSynchronizer   s    r   synchronizer^      s0    			6	"xx//1 
#	"	"s   A
Ac                  >    [         R                  R                  5       $ )z,Return the number of MTIA devices available.)r4   r5   _mtia_getDeviceCountr
   r   r   rY   rY           88((**r   c                  >    [         R                  R                  5       $ )z0Return the index of a currently selected device.)r4   r5   %_accelerator_hooks_get_current_devicer
   r   r   current_devicerd      s    8899;;r   c                 P    [         R                  R                  [        U SS95      $ )a;  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)r4   r5   _mtia_getCurrentStreamr	   r   s    r   current_streamri      !     88**+<Vd+STTr   c                 P    [         R                  R                  [        U SS95      $ )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).
Trf   )r4   r5   _mtia_getDefaultStreamr	   r   s    r   default_streamrm      rj   r   enabledstacksmax_entriesc                 d    [        5       (       d  g[        R                  R                  XU5        g)ay  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$   r4   r5   _mtia_recordMemoryHistory)rn   ro   rp   s      r   record_memory_historyrs      s$     	HH&&wDr   c                  >    [         R                  R                  5       $ )z4Return a dictionary of MTIA memory allocator history)r4   r5   _mtia_memorySnapshotr
   r   r   snapshotrv      ra   r   observerc                 B    [         R                  R                  U 5        g)z9Attach an out-of-memory observer to MTIA memory allocatorN)r4   r5   _mtia_attachOutOfMemoryObserver)rw   s    r   attach_out_of_memory_observerrz      s     
HH,,X6r   including_emulationc                     g)zLReturn a bool indicating if the current MTIA device supports dtype bfloat16.Tr
   )r{   s    r   is_bf16_supportedr}      s    r   c                 P    [         R                  R                  [        U SS95      $ )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).
Trf   )r4   r5   _mtia_getDeviceCapabilityr	   r   s    r   get_device_capabilityr      "     88--.?QU.VWWr   c                  >    [         R                  R                  5       $ )zEmpty the MTIA device cache.)r4   r5   _mtia_emptyCacher
   r   r   empty_cacher      s    88$$&&r   streamc                 J    U c  g[         R                  R                  U 5        g)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)r4   r5   _mtia_setCurrentStreamr   s    r   
set_streamr      s     ~	HH##F+r   c                 f    [        U 5      n U S:  a   [        R                  R                  U 5        gg)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	   r4   r5   %_accelerator_hooks_set_current_devicer   s    r   
set_devicer     s,     v&F{66v> r   c                 P    [         R                  R                  [        U SS95      $ )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).
Trf   )r4   r5   _mtia_getDevicePropertiesr	   r   s    r   get_device_propertiesr     r   r   c                   B    \ rS rSrSrS \4S jrS rS\S\S\4S jrS	r	g
)r   i  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                 0    [        USS9U l        SU l        g )NTrf   r   )r	   idxprev_idx)selfr   s     r   __init__device.__init__"  s    $Vd;r   c                 `    [         R                  R                  U R                  5      U l        g r   )r4   r5   (_accelerator_hooks_maybe_exchange_devicer   r   )r   s    r   	__enter__device.__enter__&  s    II$((Sr   typevaluer,   c                 `    [         R                  R                  U R                  5      U l        g)NF)r4   r5   r   r   r   )r   r   r   r,   s       r   __exit__device.__exit__)  s    88DDT]]Sr   )r   r   N)
rQ   rR   rS   rT   __doc__r   r   r   r   rU   r
   r   r   r   r     s3    s TS   r   c                   Z    \ rS rSr% Sr\S-  \S'   S\S-  4S jrS rS\	S	\	S
\	4S jr
Srg)StreamContexti.  a  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_streamr   c                    S U l         Xl        [        S S5      U l        [        R
                  R                  5       (       d  U R                  c  SU l        [        R
                  R                  5       (       d  S O[        R                  R                  S 5      U l	        [        R
                  R                  5       (       d  S U l
        g [        R                  R                  S 5      U l
        g )NTr   )r   r   r	   r   r4   jitis_scriptingr\   rm   src_prev_streamdst_prev_stream)r   r   s     r   r   StreamContext.__init__<  s    $T40yy%%''xx 		..00Dejj6O6OPT6U 	 		..00D 	6;jj6O6OPT6U 	r   c                    U R                   nUb  U R                  S:X  a  g [        R                  R	                  S 5      U l        U R
                  R                  UR                  :w  aL  [        UR                  5         [        R                  R	                  UR                  5      U l        S S S 5        [        R                  R                  U5        g ! , (       d  f       N.= fNr   )	r   r   r4   r\   ri   r   r   r   r   )r   r   s     r   r   StreamContext.__enter__K  s    [[
R$zz88> &&**;*;;
))*',zz'@'@ARAR'S$ +

j) +*s   >/C
C#r   r   r,   c                 0   U R                   nUb  U R                  S:X  a  g U R                  R                  UR                  :w  a)  [        R
                  R                  U R                  5        [        R
                  R                  U R                  5        g r   )r   r   r   r   r4   r\   r   r   )r   r   r   r,   r   s        r   r   StreamContext.__exit__Z  sj    [[
R &&**;*;;JJ!!$"6"67

d223r   )r   r   r   r   r   )rQ   rR   rS   rT   r   Stream__annotations__r   r   r   r   rU   r
   r   r   r   r   .  sB    	 
v} 
*4S 4 4 4r   r   c                 D    [         R                  R                  XU5        g)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)r4   r5   _mtia_setStream)	stream_iddevice_indexdevice_types      r   _set_stream_by_idr   h  s     
HHYkBr   c                     [        U 5      $ )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   s  s       r   c                 v    [        5         [        U SS9nUc
  [        5       n[        U   nUR	                  5       $ )aC  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.
Trf   )r   r	   rd   r   	get_state)r   r   default_generators      r   get_rng_stater   ~  s<     L
FT
2C
{*3/&&((r   c                  h    [        [        5       5       V s/ s H  n [        U 5      PM     nn U$ s  sn f )zRReturns a list of ByteTensor representing the random number states of all devices.)rangerY   r   )iresultss     r   get_rng_state_allr     s/    ).|~)>?)>A}Q)>G?N @s   /	new_statec                 "  ^ ^ [        5       (       dD  [        R                  R                  5          T R	                  [        R
                  S9m SSS5        [        USS9mTc
  [        5       mUU 4S jn[        U5        g! , (       d  f       N8= f)a$  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_formatNTrf   c                  :   > [         T   n U R                  T5        g r   )r   	set_state)r   r   r   s    r   cbset_rng_state.<locals>.cb  s    .s3##I.r   )	r$   r4   r5   _DisableFuncTorchclonecontiguous_formatr	   rd   r2   )r   r   r   r   s   `  @r   set_rng_stater     sm     XX'') "e6M6MNI *
 FT
2C
{/ rN *)s   B  
B
new_statesc                 B    [        U 5       H  u  p[        X!5        M     g)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   states      r   set_rng_state_allr     s     j)e *r   r'   c                 <   ^  [        T 5      m U 4S jn[        USS9  g)au  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                  N   > [        5       n [        U    nUR                  T5        g r   )rd   r   manual_seed)r   r   r'   s     r   r   manual_seed.<locals>.cb  s$    .s3%%d+r   Tr'   Nintr2   r'   r   s   ` r   r   r     s     t9D,
 rr   c                 <   ^  [        T 5      m U 4S jn[        USS9  g)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                  n   > [        [        5       5       H  n [        U    nUR                  T5        M     g r   )r   rY   r   r   )r   r   r'   s     r   r   manual_seed_all.<locals>.cb  s-    |~&A 21 5))$/ 'r   Tr&   Nr   r   s   ` r   manual_seed_allr     s     t9D0
 rD!r   c                      S n [        U SS9$ )ad  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                  H    [        5       n [        U    nUR                  5       $ r   )rd   r   r'   )r   r   s     r   r   seed.<locals>.cb  s$    .s3 %%''r   Tr   r2   r   s    r   r'   r'     s    (
 bt$$r   c                      S n [        U SS9$ )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n Sn[        [        5       5       H8  n[        U   nU(       d  UR                  5       n SnM'  UR	                  U 5        M:     U $ )Nr   FT)r   rY   r   r'   r   )random_seedseededr   r   s       r   r   seed_all.<locals>.cb  sT    |~&A 21 5/446!--k: ' r   Tr   r   r   s    r   r&   r&     s    
 b4((r   c                  X    [        5         [        5       n [        U    R                  5       $ )zvReturns the current random seed of the current MTIA device.

.. warning::
    This function eagerly initializes MTIA.
)r   rd   r   initial_seed)r   s    r   r   r     s%     L

Cc"//11r   )*)#r    rZ   r$   r^   rY   rd   ri   rm   memory_statsmax_memory_allocatedmemory_allocatedreset_peak_memory_statsr   r   rs   rv   rz   r   r   r   r   r   r   r   r   r   r   r   r'   r&   r   r}   	MTIAGraphgraphgraph_pool_handle)r   Nr   )allpythonr   )T)r\   )Nr   	threadingr,   collections.abcr   typingr   r4   r   torch._utilsr   torch.typesr   _utilsr	   Eventr   r   tupler5   	Generatorr   r"   r   listrG   localr@   Lockr(   r*   r?   r   r   r   r   r   r    r$   r2   boolr#   r   rF   rI   rA   rZ   r^   rY   rd   ri   rm   rs   dictrv   rz   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r'   r&   r   memory
mtia_graph__all__r
   r   r   <module>r     s     $    )  % 		 68 E%((,,c12 7   t	(2t8
d3i
'(   ~~' %'  588+,,xx44H H H 588011"XX??Hs Hs H2
K( (0f	I 	$d $
d 2 2$ 2+c +< <
	U6 	UV 	U	U6 	UV 	U MNE4ZE),EFIE	E&+$sCx. +7S#s+T127	74 
X& XE#s(O X'
,v ,	?v 	?$ 	?X& XDcN X (74 74tC!6D= !] !)& )f )$4< V V  2 $v,  4  c d *"# "$ ""%c %")# )*2c 2  $r   