
    VhVE                     b   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m	Z	 ddl
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mZ d
a ej.                         Z ej2                         Zg aeeeg df   ee   f      ed<    e e
jB                  dd       Z"e	eee#df   Z$ e       a%dZ&ee
jB                  jN                     ed<   de(fdZ) e)       rCe
jB                  jT                  Z*e
jB                  jV                  Z,e
jB                  jZ                  Z.n ed      Z*de#de#fdZ,de#de#fdZ. ed      de#fd       Z/de(fdZ0d Z1d Z2d Z3d Z4d Z5 G d d      Z6 G d  d      Z G d! d"e      Z7de$ddfd#Z8d=dee$   defd$Z9 ed      d=dee$   de:eef   fd%       Z;d=dee$   de*fd&Z<de#fd'Z=de	e#ee
j                  f   de
j                  fd(Z> G d) d*      Z?d+ed,   de?fd-Z@d. ZAd+efd/ZBd=dee$   defd0ZC	 d=d1e#dee$   defd2ZDd=de$ddfd3ZEdee   fd4ZFdefd5ZGde
j                  de
jB                  jN                  fd6ZH	 d>d7e#de	e#ee
j                  f   ddfd8ZId>de	e#ee
j                  f   de#fd9ZJdd:lKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZU dd;lVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_ g d<Z`y)?z
This package introduces support for the XPU backend, specifically tailored for
Intel GPU optimization.

This package is lazily initialized, so you can always import it, and use
:func:`is_available()` to determine if your system supports XPU.
    N)	lru_cache)AnyCallableOptionalUniondevice)_dummy_type_LazySeedTracker   )_get_device_index)EventStreamF_queued_calls_xpu_isInBadForkc                       yNF r       B/home/dcms/DCMS/lib/python3.12/site-packages/torch/xpu/__init__.py<lambda>r      s    r   r   default_generatorsreturnc                  6    t         j                  j                  S )z(Return true if compile with XPU support.)torch_C_has_xpur   r   r   _is_compiledr   #   s    88r   _XpuDevicePropertiesr	   c                     t        d      Nz(PyTorch was compiled without XPU supportNotImplementedErrorr   s    r   _exchange_devicer$   0       !"LMMr   c                     t        d      r!   r"   r   s    r   _maybe_exchange_devicer'   3   r%   r   )maxsizec                  T    t               syt        j                  j                         S )z*Return the number of XPU device available.r   )r   r   r   _xpu_getDeviceCountr   r   r   device_countr+   7   s     >88''))r   c                      t               dkD  S )z7Return a bool indicating if XPU is currently available.r   )r+   r   r   r   is_availabler-   ?   s     >Ar   c                       y)zKReturn a bool indicating if the current XPU device supports dtype bfloat16.Tr   r   r   r   is_bf16_supportedr/   E   s    r   c                  (    t         xr t                S )z8Return whether PyTorch's XPU state has been initialized.)_initialized_is_in_bad_forkr   r   r   is_initializedr3   J   s    1 111r   c                 f   t               r |         y |j                  dd      r)t        j                  | t	        j
                                y |j                  dd      r)t        j                  | t	        j
                                y t        j                  | t	        j
                         f       y )Nseed_allFseed)	r3   get_lazy_seed_trackerqueue_seed_all	tracebackformat_stack
queue_seedr   append)callablekwargss     r   
_lazy_callr@   O   s{    
 ::j%(--h	8N8N8PQZZ&))(I4J4J4LM   (I,B,B,D!EFr   c                      t                y)zInitialize PyTorch's XPU state.
    This is a Python API about lazy initialization that avoids initializing
    XPU until the first time it is accessed. Does nothing if the XPU state is
    already initialized.
    N)
_lazy_initr   r   r   initrC   ]   s	     Lr   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_initializingzuCannot re-initialize XPU in forked subprocess. To use XPU with multiprocessing, you must use the 'spawn' start methodz#Torch not compiled with XPU enabledTc              3   &   K   | ]	  }|s|  y wNr   ).0callss     r   	<genexpr>z_lazy_init.<locals>.<genexpr>}   s     XuRWUXs   z5XPU call failed lazily at initialization with error: z'

XPU call was originally invoked at:

 )r3   hasattr_tls_initialization_lockr2   RuntimeErrorr   AssertionErrorr   r   	_xpu_initrE   r   extendr8   	get_calls	Exceptionstrjoindelattrr1   )queued_callorig_tracebackemsgs       r   rB   rB   f   sA   74):;	 ! 	! ! I  ~ !FGG  $X0B0L0L0NXX	-/< 0+^0M0 D+,C! !2 ! 0OPSTUPVx XBBD''.BYAZ\  $C.a/0 D+,A! !sM   D=BD=9D(C+D(D=+	D%4,D  D%%D((D::D==Ec                   2    e Zd ZdefdZd ZdededefdZy)	_DeviceGuardindexc                      || _         d| _        y N)idxprev_idx)selfr^   s     r   __init__z_DeviceGuard.__init__   s    r   c                 `    t         j                  j                  | j                        | _        y rG   r   xpur$   rb   rc   rd   s    r   	__enter__z_DeviceGuard.__enter__       		22488<r   typevaluer:   c                 `    t         j                  j                  | j                        | _        yr   r   rh   r'   rc   rb   rd   rl   rm   r:   s       r   __exit__z_DeviceGuard.__exit__       9933DMMBr   N)__name__
__module____qualname__intre   rj   r   rq   r   r   r   r]   r]      s-    c =S   r   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 or str): device index to select. It's a no-op if
            this argument is a negative integer or ``None``.
    c                 6    t        |d      | _        d| _        y )NToptionalra   )r   rb   rc   )rd   r	   s     r   re   zdevice.__init__   s    $Vd;r   c                 `    t         j                  j                  | j                        | _        y rG   rg   ri   s    r   rj   zdevice.__enter__   rk   r   rl   rm   r:   c                 `    t         j                  j                  | j                        | _        yr   ro   rp   s       r   rq   zdevice.__exit__   rr   r   N)rs   rt   ru   __doc__r   re   rj   rq   r   r   r   r	   r	      s2    s =S   r   c                   "     e Zd ZdZ fdZ xZS )	device_ofa  Context-manager that changes the current device to that of given object.

    You can use both tensors and storages as arguments. If a given object is
    not allocated on a XPU, this is a no-op.

    Args:
        obj (Tensor or Storage): object allocated on the selected device.
    c                 `    |j                   r|j                         nd}t        |   |       y r`   )is_xpu
get_devicesuperre   )rd   objrb   	__class__s      r   re   zdevice_of.__init__   s$    "%**cnn"r   )rs   rt   ru   r}   re   __classcell__)r   s   @r   r   r      s     r   r   c                 x    t                t        |       } | dk\  r t        j                  j	                  |        yy)zSet the current device.

    Args:
        device (torch.device or int or str): selected device. This function is a
            no-op if this argument is negative.
    r   N)rB   r   r   r   _xpu_setDevicer   s    r   
set_devicer      s1     Lv&F{' r   c                 ,    t        |       j                  S )a  Get the name of a device.

    Args:
        device (torch.device or int or str, optional): device for which to
            return the name. This function is a no-op if this argument is a
            negative integer. It uses the current device, given by :func:`~torch.xpu.current_device`,
            if :attr:`device` is ``None`` (default).

    Returns:
        str: the name of the device
    )get_device_propertiesnamer   s    r   get_device_namer      s     !(---r   c                     t        |       }t        |      D ci c]   }|j                  d      s|t        ||      " c}S c c}w )a  Get the xpu capability of a device.

    Args:
        device (torch.device or int or str, optional): device for which to
            return the device capability. This function is a no-op if this
            argument is a negative integer. It uses the current device, given by
            :func:`~torch.xpu.current_device`, if :attr:`device` is ``None``
            (default).

    Returns:
        Dict[str, Any]: the xpu capability dictionary of the device
    )__
_pybind11_)r   dir
startswithgetattr)r	   propsprops      r   get_device_capabilityr      sM     "&)E J34 	geT""  s   %Ac                 F    t                t        | d      } t        |       S )zGet the properties of a device.

    Args:
        device (torch.device or int or str): device for which to return the
            properties of the device.

    Returns:
        _XpuDeviceProperties: the properties of the device
    Try   )rB   r   _get_device_propertiesr   s    r   r   r      s      Lv5F!&))r   c                  R    t                t        j                  j                         S )z0Return the index of a currently selected device.)rB   r   r   _xpu_getDevicer   r   r   current_devicer     s    L88""$$r   c                     t        | t              rt        j                  |       } | S t        | t              rt        j                  d|       } | S )zReturn the torch.device type object from the passed in device.

    Args:
        device (torch.device or int or str): selected device.
    rh   )
isinstancerU   r   r	   rv   r   s    r   _get_devicer   
  sD     &#f% M 
FC	 eV,Mr   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 XPU 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.xpu.Stream
cur_streamstreamc                 \    || _         t        d d      | _        | j                  d| _        y y )NTra   )r   r   rb   )rd   r   s     r   re   zStreamContext.__init__$  s-    $T4088DH 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r`   )	r   rb   r   rh   current_streamsrc_prev_streamr	   dst_prev_stream
set_stream)rd   r   s     r   rj   zStreamContext.__enter__*  s    [[
R$yy77= &&**;*;;
))* S',yy'?'?
@Q@Q'R$S		Z(S Ss   ;/CCrl   rm   r:   c                 *   | j                   }|| j                  dk(  ry | j                  j                  |j                  k7  r)t        j
                  j                  | j                         t        j
                  j                  | j                         y r`   )r   rb   r   r	   r   rh   r   r   )rd   rl   rm   r:   r   s        r   rq   zStreamContext.__exit__6  sj    [[
R &&**;*;;II  !5!56		T112r   N)
rs   rt   ru   r}   r   __annotations__re   rj   r   rq   r   r   r   r   r     sF    	 +,,x(:; 
)3S 3 3 3r   r   r   r   c                     t        |       S )zWrap 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``.
    )r   r   s    r   r   r   A  s       r   c                 H    t         j                  j                  | ||       y)a  set stream specified by the stream id, device index and device type

    Args: stream_id (int): not visible to the user, used to assigned to the specific stream.
          device_index (int): selected device index.
          device_type (int): selected device type.
    	stream_iddevice_indexdevice_typeN)r   r   _xpu_setStreamr   s      r   _set_stream_by_idr   J  s$     
HH!  r   c                 v    | yt                t        | j                  | 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``.
    Nr   )rB   r   r   r   r   r   s    r   r   r   X  s4     ~L""((&&r   c                     t                t        j                  j                  t	        | d            }t        |d   |d   |d         S )aR  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.xpu.current_device`, if :attr:`device` is ``None``
            (default).
    Try   r   r      r   )rB   r   r   _xpu_getCurrentStreamr   r   )r	   
streamdatas     r   r   r   k  sJ     L//&40J Q-jmTU r   data_ptrc                     t                t        j                  j                  | t	        |d            }t        |d   |d   |d         S )a;  Return a :class:`Stream` from an external SYCL queue.

    This function is used to wrap SYCL queue created in other libraries in order
    to facilitate data exchange and multi-library interactions.

    .. note:: This function doesn't manage the queue life-cycle, it is the user
       responsibility to keep the referenced queue alive while this returned stream is
       being used. The different SYCL queue pointers will result in distinct
       :class:`Stream` objects, even if the SYCL queues they dereference are equivalent.

    Args:
        data_ptr(int): Integer representation of the `sycl::queue*` value passed externally.
        device(torch.device or int, optional): the device where the queue was originally created.
            It is the user responsibility to ensure the device is specified correctly.
    Try   r   r   r   r   )rB   r   r   _xpu_getStreamFromExternalr   r   )r   r	   r   s      r   get_stream_from_externalr   }  sM    $ L44#FT:J Q-jmTU r   c                 n    t                t        | d      } t        j                  j	                  |       S )a*  Wait for all kernels in all streams on a XPU device to complete.

    Args:
        device (torch.device or int, optional): device for which to synchronize.
            It uses the current device, given by :func:`~torch.xpu.current_device`,
            if :attr:`device` is ``None`` (default).
    Try   )rB   r   r   r   _xpu_synchronizer   s    r   synchronizer     s*     Lv5F88$$V,,r   c                  ~    t               sg S t        j                  j                         } | g S | j	                         S )z<Return list XPU architectures this library was compiled for.)r   r   r   _xpu_getArchFlagssplit)
arch_flagss    r   get_arch_listr     s8    >	++-J	r   c                  j    t               } t        |       dk(  ryddj                  d | D               S )zIReturn XPU AOT(ahead-of-time) build flags this library was compiled with.r   rK   z-device ,c              3       K   | ]  }|  y wrG   r   )rH   archs     r   rJ   z$get_gencode_flags.<locals>.<genexpr>  s     :t:s   )r   lenrV   )	arch_lists    r   get_gencode_flagsr     s5    I
9~chh:	::;<<r   c                 l    | j                   }|
t               }t        j                  j                  |   S )zuReturn the XPU Generator object for the given device.

    Args:
        device (torch.device): selected device.
    )r^   r   r   rh   r   )r	   rb   s     r   _get_generatorr     s/     ,,C
{99'',,r   offsetc                 @     t        |       fd}t        |       y)a$  Set the random number generator state offset of the specified GPU.

    Args:
        offset (int): The desired offset
        device (torch.device or int, optional): The device to set the RNG state.
            Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device).
    c                  >    t              } | j                         y rG   )r   
set_offset)default_generatorfinal_devicer   s    r   cbz!_set_rng_state_offset.<locals>.cb  s    *<8$$V,r   N)r   r@   )r   r	   r   r   s   `  @r   _set_rng_state_offsetr     s     v&L- rNr   c                 b    t                t        |       }t        |      }|j                         S )aL  Return the random number generator state offset of the specified GPU.

    Args:
        device (torch.device or int, optional): The device to return the RNG state offset of.
            Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device).

    .. warning::
        This function eagerly initializes XPU.
    )rB   r   r   
get_offset)r	   r   r   s      r   _get_rng_state_offsetr     s-     Lv&L&|4''))r   )
empty_cachemax_memory_allocatedmax_memory_reservedmem_get_infomemory_allocatedmemory_reservedmemory_statsmemory_stats_as_nested_dictreset_accumulated_memory_statsreset_peak_memory_stats)	get_rng_stateget_rng_state_allinitial_seedmanual_seedmanual_seed_allr6   r5   set_rng_stateset_rng_state_all)+r   r   r   r   r   r   r	   r   r+   r   r   r   r   r   r   r   r   r   rC   r   r-   r/   r3   r   r   r   r   r   r   r   r   r   r   r   r6   r5   r   r   r   r   r   streamsr   rG   )rh   )ar}   	threadingr:   	functoolsr   typingr   r   r   r   r   torch._Cr	   _devicetorch._utilsr
   r   _utilsr   r   r   r   r1   localrM   LockrN   r   listtuplerU   r   r   r   r2   rv   	_device_tr8   r   	Generatorboolr   r   _xpu_exchangeDevicer$   _xpu_maybeExchangeDevicer'   r+   r-   r/   r3   r@   rC   rB   r]   r   r   r   dictr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   memoryr   r   r   r   r   r   r   r   r   r   randomr   r   r   r   r   r6   r5   r   r   __all__r   r   r   <module>r      s      1 1   # 6 % " y%y~~'   t	(2t8
d3i
'(  %(($6F'3T)*	%' 02 E%((,,- 2d 
 > 8888xx33"XX>> ''=>N N NNs Ns N 1*c * *d 
2
G%P
 
 ( 
(y 
(T 
(.HY/ .3 . 4(9"5 c3h  4*(9"5 *AU *% %
c345 
%,, 
'3 '3T!8./ !M !v &8I. & & 26#I.6
-	 
-T 
-tCy =3 =	-5<< 	-EHH,>,> 	- :?sC56	&*%S%,,(>"? *C *"  
 
 
,r   