
    ^j                    :   U d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZmZmZ ddlZddlZddlmZmZ erddlmZ dd	lmZ d
dlmZ d
dl m!Z!m"Z"m#Z#m$Z$m%Z% d
dl&m'Z'm(Z( da) ejT                         Z+ ejX                         Z-g a.de/d<    e0ejb                  dd       Z2 e       a3dZ4de/d<   da5de/d<   ejl                   G d d             Z7g a8de/d<   dZ9dYdZ: e:       rCejb                  jv                  Z;ejb                  jx                  Z=ejb                  j|                  Z?n ed      Z;dZd Z=dZd!Z?d[d\d"Z@d]d#ZAd]d$ZBd^d%ZCd^d&ZDdYd'ZEd_d`d(ZFdYd)ZGd* ZHdad+ZIdad,ZJdad-ZK G d. d/      ZL G d0 d      ZM G d1 d2eM      ZNdbd3ZOdcddd4ZP ed      dcded5       ZQ	 dc	 	 	 dfd6ZRd^d7ZSdgd8ZTdhd9ZU G d: d;      ZVdid<ZWdad=ZXdjd>ZYdcdkd?ZZdcdld@Z[dcdbdAZ\dmdBZ]dndCZ^dodDZ_	 dp	 	 	 	 	 dqdEZ`dpdrdFZadG ZbdsdHZcdtdIZddcdudJZedcdvdKZfdcdudLZgdcdvdMZhdcdudNZidcdvdOZjdcdudPZkdcdvdQZldcdudRZmdcdvdSZndcdwdTZod
dUlpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZ d
dVlmZmZmZmZmZmZmZmZmZ  edWeeef         Zg dXZy)xz
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.
    )annotationsN)byrefc_doublec_uint32c_void_pcastpointer)	lru_cache)AnyNewTypeTYPE_CHECKING)_dummy_type_LazySeedTracker)Callable)Device   )_get_device_index)graphgraph_pool_handleis_current_stream_capturingmake_graphed_callablesXPUGraph)EventStreamFz*list[tuple[Callable[[], None], list[str]]]_queued_calls_xpu_isInBadForkc                      yNF r       ]/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/xpu/__init__.py<lambda>r"   0   s    r    r   ztuple[torch._C.Generator]default_generators
int | None_cached_device_countc                  z    e Zd ZU ded<   dZded<   dZded<   dZd	ed
<   dZd	ed<   dZd	ed<   dZ	d	ed<   dZ
d	ed<   y)_ZesDeviceInfor   device_handleNr$   subdevice_idFboolis_integratedzc_void_p | Nonetemperature_handlefrequency_handlepower_handleengine_handlememory_handle)__name__
__module____qualname____annotations__r)   r+   r,   r-   r.   r/   r0   r   r    r!   r'   r'   6   sP    #L*#M4*..(,o,$(L/(%)M?)%)M?)r    r'   zlist[_ZesDeviceInfo]_cached_zes_device_infos   c                 6    t         j                  j                  S )z(Return true if compile with XPU support.)torch_C_has_xpur   r    r!   _is_compiledr;   G   s    88r    _XpuDevicePropertiesdevicec                    t        d      Nz(PyTorch was compiled without XPU supportNotImplementedErrorr=   s    r!   _exchange_devicerC   T       !"LMMr    c                    t        d      r?   r@   rB   s    r!   _maybe_exchange_devicerF   W   rD   r    c                B   t        j                  d      }|t        t        d            S g }|j	                  d      D ]8  }	 t        |j                               }|dk\  s#||vs(|j                  |       : |S # t        $ r | rt        d| d      dg cY c S w xY w)a,  Parse ``ZE_AFFINITY_MASK`` and return visible device ordinals.

    Returns a list of non-negative device ordinals specified by the mask.
    When the mask is unset, returns ``[0, 1, ..., 127]`` (the maximum range
    for ``int8_t`` device indices).  Returns an empty list for unsupported
    COMPOSITE-style masks (e.g. ``"0.0,0.1"``).

    Args:
        strict (bool): If ``True``, raises ``ValueError`` on unsupported mask
            formats (e.g. COMPOSITE-style ``"0.0,0.1"``).  If ``False``
            (default), returns an empty list instead.
    ZE_AFFINITY_MASKN   ,z&Unsupported ZE_AFFINITY_MASK format: 'z='. Expected a comma-separated list of integers, e.g. '0,1,2'.r   )	osgetenvlistrangesplitintstrip
ValueErrorappend)strictvarvisible_deviceselemxs        r!   _parse_visible_devicesrY   [   s     ))&
'C
{ E#J!#O		# &
	DJJL!A 6a.""1%&   	  <SEA~ I	s   A<<BBc           	     d   	 ddl dfd} |j                  d      d      ryt        d      } |j	                  t        |      d      d      ry|j                  dk(  ry j                  |j                  z         } |j	                  t        |      |      d      ryt        d      } |j                  |d   t        |      d      d      ry j                  |j                  z         } |j                  |d   t        |      |      d	      ryd
}t        j                  d      dk7  }t        j                          t        |       }d}	d}
d}|D ]  }j                         }j                   |_        j%                         }j&                  |_        t)        t+        |      t,              |_         |j1                  |t        |            d      r yt3        |j4                  |z        }| xr |j6                  dkD  xr |}|r|j6                  nd
}t9        |      D ]=  }|	|v r2t        j;                  t=        ||r|nd|             |r|
d
z  }
n|d
z  }|	d
z  }	?  |r#|
r!t        D cg c]  }|j>                  r| c}a|xs |
S # t        $ r Y yw xY wc c}w )a  Enumerate visible XPU devices via Level Zero Sysman and cache their info.

    Enumerates devices from the first Level Zero Sysman driver and counts those
    whose logical index appears in *visible_mask*.  Only devices listed in
    the visible mask participate in counting.
    The populated ``_cached_zes_device_infos`` list is indexed by PyTorch
    device ordinal.

    Discrete GPUs (dGPUs) take priority: if any visible dGPU is found, only
    dGPUs are counted; integrated GPUs (iGPUs) are counted only when no
    visible dGPU exists.

    For tiled dGPUs (``numSubdevices > 0``), the counting depends on
    ``ZE_FLAT_DEVICE_HIERARCHY``:

    - **FLAT / COMBINED** (default): each sub-device is exposed as a
      separate top-level device and counted individually.
    - **COMPOSITE**: sub-devices are hidden; the whole physical device
      counts as one.

    Returns the visible device count, or a negative value on failure.
    r   Nc                n    | j                   k7  rt        j                  |d       | j                   k7  S )zQReturn True if the call failed (rc != ZE_RESULT_SUCCESS) after issuing a warning.   )
stacklevel)ZE_RESULT_SUCCESSwarningswarnrcmsgpyzess     r!   _zes_check_warnz/_enum_zes_device_infos.<locals>._zes_check_warn   s0    (((MM#!,U,,,,r    z"Can't initialize Level Zero Sysmanz(Can't get Level Zero Sysman driver countz*Can't get Level Zero Sysman driver handlesz(Can't get Level Zero Sysman device countz*Can't get Level Zero Sysman device handlesr   ZE_FLAT_DEVICE_HIERARCHY	COMPOSITEz-Can't get Level Zero Sysman device properties)r(   r)   r+   )rc   rP   rd   strreturnr*   ) re   	ExceptionzesInitr   zesDriverGetr   valuezes_driver_handle_tzesDeviceGetzes_device_handle_trK   rL   r5   clearsetzes_device_properties_t$ZES_STRUCTURE_TYPE_DEVICE_PROPERTIESstypezes_device_ext_properties_t(ZES_STRUCTURE_TYPE_DEVICE_EXT_PROPERTIESr   r	   r   pNextzesDeviceGetPropertiesr*   flagsnumSubdevicesrN   rS   r'   r+   )visible_maskrf   driver_countdriversdevice_countdevices#ZES_DEVICE_PROPERTY_FLAG_INTEGRATEDexpose_subdevicesvisiblelogical_indexnum_igpunum_dgpur=   props	ext_propsr+   tiled	num_slotsslotinfore   s                       @r!   _enum_zes_device_infosr      s   .- u}}Q')MNA;L5.52 Q=u((<+=+==@G5.84 A;L71:u\':DA2 =u((<+=+==@G71:u\':GD4  +1'		"<=L""$,GMHH  --/@@557	HH	79-x8((u>;
 Y__/RRS "!Se&9&9A&=SBS+0E''a	)$ 	D'(//"&,-2T&3 !MHMHQM	' F H5$
T=O=OD$
  x{  t$
s   J ?J-J-	J*)J*c                    t        |       S )zRReturn the visible XPU device count via Level Zero Sysman, or negative on failure.)r   )r}   s    r!   _raw_device_count_zesr      s    !,//r    c                 2    t               } | syt        |       S )z;Return the number of visible XPU devices, or -1 on failure.r[   )rY   r   )rV   s    r!   _device_count_zesr      s    ,.O 11r    c                    t               syt        t        S t        st        t        d      rt
        j                  j                         } n/t               }|dk  rt
        j                  j                         n|} t        r| a| S )z
    Return the number of XPU device available.

    .. note:: This API will NOT poison fork if Level Zero Sysman discovery succeeds.
        See :ref:`multiprocessing-poison-fork-note` for more details.
    r   is_initializing)	r;   r%   _initializedhasattr_tlsr8   r9   _xpu_getDeviceCountr   )count	zes_counts     r!   r   r     si     >'##wt%67,,.%'	2;a-,,.Y $Lr    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                p    t               sy| xs( t        j                  j                         j                  S )zKReturn a bool indicating if the current XPU device supports dtype bfloat16.F)r   r8   xpuget_device_propertieshas_bfloat16_conversions)including_emulations    r!   is_bf16_supportedr   %  s.    > 	F99**,EEr    c                 h    t               syt        j                  j                         j                  S )zGReturn a bool indicating if the current XPU device supports dtype tf32.F)r   r8   r   r   'has_subgroup_matrix_multiply_accumulater   r    r!   is_tf32_supportedr   /  s%    >
 99**,TTTr    c                 (    t         xr t                S )z8Return whether PyTorch's XPU state has been initialized.)r   _is_in_bad_forkr   r    r!   is_initializedr   :  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)	r   get_lazy_seed_trackerqueue_seed_all	tracebackformat_stack
queue_seedr   rS   )callablekwargss     r!   
_lazy_callr   ?  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!   initr   M  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)	Nr   zuCannot 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>m  s     XuRWUXs   z5XPU call failed lazily at initialization with error: z'

XPU call was originally invoked at:

 )r   r   r   _initialization_lockr   RuntimeErrorr;   AssertionErrorr8   r9   	_xpu_initr   r   extendr   	get_callsrk   ri   joindelattrr   )queued_callorig_tracebackerd   s       r!   r   r   V  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                  "    e Zd ZddZd ZddZy)_DeviceGuardc                     || _         d| _        y Nr[   )idxprev_idx)selfindexs     r!   __init__z_DeviceGuard.__init__  s    r    c                `    t         j                  j                  | j                        | _        y r   r8   r   rC   r   r   r   s    r!   	__enter__z_DeviceGuard.__enter__      		22488<r    c                `    t         j                  j                  | j                        | _        yr   r8   r   rF   r   r   r   typern   r   s       r!   __exit__z_DeviceGuard.__exit__      9933DMMBr    N)r   rP   rj   Noner   r   rn   r   r   r   )r1   r2   r3   r   r   r   r   r    r!   r   r   ~  s    =r    r   c                  &    e Zd ZdZddZd Zd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optionalr[   )r   r   r   )r   r=   s     r!   r   zdevice.__init__  s    $Vd;r    c                `    t         j                  j                  | j                        | _        y r   r   r   s    r!   r   zdevice.__enter__  r   r    c                `    t         j                  j                  | j                        | _        yr   r   r   s       r!   r   zdevice.__exit__  r   r    N)r=   r   rj   r   r   )r1   r2   r3   __doc__r   r   r   r   r    r!   r=   r=     s    =r    c                  $     e Zd ZdZd 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superr   )r   objr   	__class__s      r!   r   zdevice_of.__init__  s$    "%**cnn"r    rj   r   )r1   r2   r3   r   r   __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)r   r   r8   r9   _xpu_setDevicerB   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
    )r   namerB   s    r!   get_device_namer     s     !(---r    c           	        t        |       }t        t        t        t        t        d      t        t        t        f}t        |      D ci c].  }|j                  d      st        t        ||      x}|      r||0 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
    N__)r   rP   floatr*   ri   r   rM   tupledictdir
startswith
isinstancegetattr)r=   r   serializable_typeskeyrn   s        r!   get_device_capabilityr    sv     "&)EudCdT5$O u:~~d#!447IJ 	U
  s   3A>c                F    t                t        | d      } t        |       S )a	  Get the properties of a device. Returns _XpuDeviceProperties containing the following device properties:

    - ``name`` (str): device name.
    - ``platform_name`` (str): SYCL platform name.
    - ``vendor`` (str): device vendor.
    - ``device_id`` (int): device identifier (product ID).
    - ``driver_version`` (str): driver version.
    - ``version`` (str): runtime version.
    - ``max_compute_units`` (int): number of parallel compute units.
    - ``gpu_eu_count`` (int): number of EUs (Execution Unit).
    - ``max_work_group_size``: (int): maximum number of work-items permitted in a work-group.
    - ``max_num_sub_groups`` (int): maximum number of sub-groups supported in a work-group.
    - ``memory_clock_rate`` (int) maximum clock rate of device's global memory in MHz.
    - ``memory_bus_width`` (int) maximum bus width between device and memory in bits.
    - ``sub_group_sizes``: (list[int]): a list of supported sub-group sizes.
    - ``local_mem_size`` (int): device local memory capacity that can be allocated per work-group in bytes.
    - ``last_level_cache_size`` (int): size in bytes of the device's last-level memory cache, shared across all Xe Cores (analogous to CUDA ``L2_cache_size``).
    - ``has_fp16`` (bool): whether float16 dtype is supported.
    - ``has_fp64`` (bool): whether float64 dtype is supported.
    - ``has_atomic64`` (bool): whether 64-bit atomic operations are supported.
    - ``has_bfloat16_conversions`` (bool): whether bfloat16 conversions are supported.
    - ``has_subgroup_matrix_multiply_accumulate`` (bool): whether DPAS (Dot Product Accumulate Systolic) is supported.
    - ``has_subgroup_matrix_multiply_accumulate_tensor_float32`` (bool): whether DPAS with tf32 inputs is supported.
    - ``has_subgroup_2d_block_io`` (bool): whether 2D block I/O for efficient matrix multiplication is supported.
    - ``is_integrated_gpu`` (bool): whether the device is an integrated GPU (iGPU).
    - ``total_memory`` (int): device global memory in bytes.
    - ``gpu_subslice_count`` (int): number of subslice.
    - ``architecture`` (int): device architecture identifier (experimental).
    - ``type`` (str): device type, e.g. 'cpu', 'gpu', accelerator', 'host', 'unknown'.
    - ``uuid`` (Any): device UUID (Universal Unique ID), 16 bytes.

    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
    Tr   )r   r   _get_device_propertiesrB   s    r!   r   r     s!    R Lv5F!&))r    c                 R    t                t        j                  j                         S )z0Return the index of a currently selected device.)r   r8   r9   _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.
    r   )r   ri   r8   r=   rP   rB   s    r!   _get_devicer	    sD     &#f% M 
FC	 eV,Mr    c                    t                t        | d      } t        |d      }t        j                  j	                  | |      S )a/  Query whether a device can access a peer device's memory.

    Args:
        device (torch.device or int or str): selected device.
        peer (torch.device or int or str): peer device to query access to.

    Returns:
        bool: ``True`` if ``device`` can access ``peer``, ``False`` otherwise.
    Tr   )r   r   r8   r9   _xpu_canDeviceAccessPeer)r=   peers     r!   can_device_access_peerr  $  s8     Lv5FTD1D88,,VT::r    c                  2    e Zd ZU dZded<   ddZd Zd	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 | None
cur_streamc                \    || _         t        d d      | _        | j                  d| _        y y )NTr[   )streamr   r   )r   r  s     r!   r   zStreamContext.__init__B  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  r   r8   r   current_streamsrc_prev_streamr=   dst_prev_stream
set_stream)r   r  s     r!   r   zStreamContext.__enter__H  s    [[
R$yy77= &&**;*;;
))* S',yy'?'?
@Q@Q'R$S		Z(S Ss   ;/CCc                *   | j                   }|| j                  dk(  ry | j                  j                  |j                  k7  r)t        j
                  j                  | j                         t        j
                  j                  | j                         y r   )r  r   r  r=   r8   r   r  r  )r   r   rn   r   r  s        r!   r   zStreamContext.__exit__T  sj    [[
R &&**;*;;II  !5!56		T112r    N)r  r  rj   r   r   )r1   r2   r3   r   r4   r   r   r   r   r    r!   r  r  4  s    	 ('
)3r    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  _  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)r8   r9   _xpu_setStreamr  s      r!   _set_stream_by_idr"  h  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  )r   r"  r  r  r   r  s    r!   r  r  v  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).
    Tr   r   r      r  )r   r8   r9   _xpu_getCurrentStreamr   r   )r=   
streamdatas     r!   r  r    sJ     L//&40J Q-jmTU r    c                    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.
    Tr   r   r   r%  r  )r   r8   r9   _xpu_getStreamFromExternalr   r   )data_ptrr=   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).
    Tr   )r   r   r8   r9   _xpu_synchronizerB   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;   r8   r9   _xpu_getArchFlagsrO   )
arch_flagss    r!   get_arch_listr2    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   r   z-device rJ   c              3      K   | ]  }|  y wr   r   )r   archs     r!   r   z$get_gencode_flags.<locals>.<genexpr>  s     :t:s   )r2  lenr   )	arch_lists    r!   get_gencode_flagsr8    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  r8   r   r#   )r=   r   s     r!   _get_generatorr:    s/     ,,C
{99'',,r    c                B     t        |      d 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 r   )r:  
set_offset)default_generatorfinal_deviceoffsets    r!   cbz!_set_rng_state_offset.<locals>.cb  s    *<8$$V,r    Nr   )r	  r   )r@  r=   rA  r?  s   `  @r!   _set_rng_state_offsetrB    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.
    )r   r	  r:  
get_offset)r=   r?  r>  s      r!   _get_rng_state_offsetrE    s-     Lv&L&|4''))r    c                 r    	 ddl } | S # t        $ r t        d      dt        $ r}t        d      |d}~ww xY w)znReturn the imported pyzes module; raise ImportError if missing, RuntimeError if the GPU driver is unavailable.r   Nz7pyzes is required; install it with 'pip install pyzes'.zZFailed to import pyzes. Ensure the GPU driver is installed with Level Zero Sysman support.)re   ImportErrorrk   r   )re   errs     r!   _import_pyzesrI    sS    	 L  E
	  h
	s    616c                L    ddl }| |j                  k7  rt        | d|  d      y)zRRaise RuntimeError if the Level Zero Sysman call failed (rc != ZE_RESULT_SUCCESS).r   Nz (rc=))re   r_   r   rb   s      r!   
_zes_checkrL    s0    	U$$$cU%t1-.. %r    c                    t         s#t        t        d            dk  rt        d      t	        t               }| |k\  rt        d|  d| d      y)	zLEnsure the ZES device info cache is populated and validate the device index.T)rT   r   z2Failed to enumerate devices via Level Zero Sysman.zThe device zD is out of range for Level Zero Sysman. It must be in the range [0, ).N)r5   r   rY   r   r6  )r=   total_devicess     r!   _zes_ensure_device_infosrP    s_    #!"8"EFJSTT01M&!efsettvw
 	
 r    c           	     :   t               }t        | d      } t        |        t        |    }|j                  |j                  S |j
                  }|j                  }t        d      }t        |j                  |t        |      d      d       |j                  dk(  rt        d       |j                  |j                  z         }t        |j                  |t        |      |      d       d}|D ]  }|j                         }	|j                  |	_        t        |j#                  |t        |	            d       |	j$                  |j&                  k7  rc|!|	j(                  sr|	j*                  |k(  s|} n|	j(                  r|} n |t        d	      ||_        |S )
a  Return the Level Zero Sysman GPU temperature sensor handle for the specified device.

    The result is cached in ``_ZesDeviceInfo.temperature_handle`` so that
    repeated calls skip sensor enumeration.  ``_cached_zes_device_infos``
    is lazily populated on the first call.

    Args:
        device (torch.device, str or int, optional): target device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).
    Tr   Nr   z5Can't get Level Zero Sysman temperature sensor count.z/No Level Zero Sysman temperature sensors found.z7Can't get Level Zero Sysman temperature sensor handles.z3Can't get Level Zero Sysman temperature properties.z2No Level Zero Sysman GPU temperature handle found.)rI  r   rP  r5   r,   r(   r)   r   rL  zesDeviceEnumTemperatureSensorsr   rn   r   zes_temp_handle_tzes_temp_properties_t"ZES_STRUCTURE_TYPE_TEMP_PROPERTIESrv   zesTemperatureGetPropertiesr   ZES_TEMP_SENSORS_GPUonSubdevicesubdeviceId)
r=   re   r   r(   r)   
temp_counttemp_handlesr,   temp_handle
temp_propss
             r!   _get_zes_temperature_handler^  &  s    OEv5FV$#F+D*&&&&&M$$L
 !J--mU:=NPTU? 1LMM>E++j.>.>>AL--5,l	
 	B	 # 002
 CC
--k5;LMA	
 ??e888#%%**@*@L*P%0"))%0"!$ !OPP0Dr    c                    t        |       }ddl}t        d      }|j                  |t	        |            }||j
                  k(  rt        d      ||j                  k7  rt        d| d      |j                  S )ag  Return the GPU temperature in degrees Celsius.

    Args:
        device (torch.device, str or int, optional): selected device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).

    .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU temperature information.
    r   Ng        z\GPU temperature querying is not available. Try running with elevated privileges (e.g. sudo).z0Can't get Level Zero Sysman GPU temperature (rc=rN  )	r^  re   r   zesTemperatureGetStater   ZE_RESULT_ERROR_NOT_AVAILABLEr   r_   rn   )r=   r,   re   temprc   s        r!   temperaturerc  i  s     5V<C=D		%	%&8%+	FB	U000j
 	
 
U$$$MbTQSTUU::r    c                   t               }t        | d      } t        |        t        |    }|j                  |j                  S |j
                  }t        d      }t        |j                  |t        |      d      d       |j                  dk(  rt        d       |j                  |j                  z         }t        |j                  |t        |      |      d       |d   }||_        |S )a  Return the Level Zero Sysman GPU frequency domain handle for the specified device.

    The result is cached in ``_ZesDeviceInfo.frequency_handle`` so that
    repeated calls skip domain enumeration.  ``_cached_zes_device_infos``
    is lazily populated on the first call.

    Args:
        device (torch.device, str or int, optional): target device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).
    Tr   Nr   z4Can't get Level Zero Sysman frequency domains count.z-No Level Zero Sysman frequency domains found.z5Can't get Level Zero Sysman frequency domain handles.)rI  r   rP  r5   r-   r(   r   rL  zesDeviceEnumFrequencyDomainsr   rn   r   zes_freq_handle_t)r=   re   r   r(   
freq_countfreq_handlesr-   s          r!   _get_zes_frequency_handleri    s     OEv5FV$#F+D($$$&&M !J++M5;LdS> 1JKK>E++j.>.>>AL++5,l	
 	@	 $A,Dr    c                    t        |       }ddl}|j                         }|j                  |t	        |            }||j
                  k7  rt        d| d      |j                  S )zReturn the GPU clock rate in MHz.

    Args:
        device (torch.device, str or int, optional): selected device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).
    r   Nz/Can't get Level Zero Sysman GPU clock rate (rc=rN  )ri  re   zes_freq_state_tzesFrequencyGetStater   r_   r   actual)r=   r-   re   
freq_staterc   s        r!   
clock_ratero    sh     18'')J		#	#$4eJ6G	HB	U$$$LRDPRSTTr    c                   t               }t        | d      } t        |        t        |    }|j                  |j                  S |j
                  }t        d      }t        |j                  |t        |      d      d       |j                  dk(  rt        d       |j                  |j                  z         }t        |j                  |t        |      |      d       |d   }||_        |S )a  Return the Level Zero Sysman GPU power domain handle for the specified device.

    The result is cached in ``_ZesDeviceInfo.power_handle`` so that
    repeated calls skip domain enumeration.  ``_cached_zes_device_infos``
    is lazily populated on the first call.

    Args:
        device (torch.device, str or int, optional): target device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).
    Tr   Nr   z0Can't get Level Zero Sysman power domains count.z)No Level Zero Sysman power domains found.z1Can't get Level Zero Sysman power domain handles.)rI  r   rP  r5   r.   r(   r   rL  zesDeviceEnumPowerDomainsr   rn   r   zes_pwr_handle_t)r=   re   r   r(   power_countpower_handlesr.   s          r!   _get_zes_power_handleru    s     OEv5FV$#F+D$   &&M 1+K''u[7I4P: AFGG?U++k.?.??BM''5-}	
 	<	 !#L$Dr    c                   t        |       }ddl}|j                         }|j                  |t	        |            }||j
                  k(  rt        d      ||j                  k7  rt        d| d      ddl}|j                  t        dz         |j                         }t        |j                  |t	        |            d       |j                  |j                  z
  }|j                  |j                  z
  |z  S )a  Return the GPU card power draw in watts.

    The value is computed by dividing the energy delta by the time delta between
    two energy-counter reads separated by a 100ms sampling interval.

    Args:
        device (torch.device, str or int, optional): selected device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).

    .. note:: This function blocks for approximately 100ms per call due to the
        sampling interval required to compute an accurate power reading.

    .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU power information.
    r   Nz[GPU power draw querying is not available. Try running with elevated privileges (e.g. sudo).z/Can't get Level Zero Sysman GPU power draw (rc=rN       @@z5Can't get Level Zero Sysman GPU power energy counter.)ru  re   zes_power_energy_counter_tzesPowerGetEnergyCounterr   ra  r   r_   timesleep_zes_sample_interval_msrL  	timestampenergy)r=   r.   re   counter_startrc   rz  counter_enddts           r!   
power_drawr    s      )0L446M		'	'eM6J	KB	U000i
 	
 
U$$$LRDPRSTTJJ&/0224K&&|U;5GH? 
		!8!8	8B!5!55;;r    c           	     :   t               }t        | d      } t        |        t        |    }|j                  |j                  S |j
                  }|j                  }t        d      }t        |j                  |t        |      d      d       |j                  dk(  rt        d       |j                  |j                  z         }t        |j                  |t        |      |      d       d}|D ]  }|j                         }	|j                  |	_        t        |j#                  |t        |	            d       |	j$                  |j&                  k7  rc|!|	j(                  sr|	j*                  |k(  s|} n|	j(                  r|} n |t        d	      ||_        |S )
a  Return the Level Zero Sysman GPU engine group handle for the specified device.

    The result is cached in ``_ZesDeviceInfo.engine_handle`` so that
    repeated calls skip group enumeration.  ``_cached_zes_device_infos``
    is lazily populated on the first call.

    Args:
        device (torch.device, str or int, optional): target device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).
    Tr   Nr   z/Can't get Level Zero Sysman engine group count.zNo Level Zero Sysman engine groups found. The GPU may not support engine monitoring, or try running with elevated privileges (e.g. sudo).z1Can't get Level Zero Sysman engine group handles.z.Can't get Level Zero Sysman engine properties.z-No Level Zero Sysman GPU engine handle found.)rI  r   rP  r5   r/   r(   r)   r   rL  zesDeviceEnumEngineGroupsr   rn   r   zes_engine_handle_tzes_engine_properties_t$ZES_STRUCTURE_TYPE_ENGINE_PROPERTIESrv   zesEngineGetPropertiesr   ZES_ENGINE_GROUP_ALLrX  rY  )
r=   re   r   r(   r)   engine_countengine_handlesr/   
eng_handle	eng_propss
             r!   _get_zes_engine_handler    s    OEv5FV$#F+D%!!!&&M$$L A;L''u\7JDQ9 Q X
 	
 Ee//,2D2DDGN''5.	
 	<	 M$ 
113	DD	((U95EF<	
 >>U777#$$)>)>,)N *(( *!$ JKK&Dr    c                   t        |       }ddl}|j                         }|j                  |t	        |            }||j
                  k(  rt        d      ||j                  k7  rt        d| d      ddl}|j                  t        dz         |j                         }t        |j                  |t	        |            d       |j                  |j                  z
  }|j                  |j                  z
  |z  dz  S )	a  Return the GPU engine utilization as a percentage.

    The value is computed by dividing the active-time delta by the time delta
    between two engine-activity reads separated by a 100ms sampling interval.

    Args:
        device (torch.device, str or int, optional): selected device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).

    .. note:: This function blocks for approximately 100ms per call due to the
        sampling interval required to compute an accurate utilization reading.

    .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU utilization information.
    r   Nz\GPU utilization querying is not available. Try running with elevated privileges (e.g. sudo).z4Can't get Level Zero Sysman GPU engine activity (rc=rN  rw  z0Can't get Level Zero Sysman GPU engine activity.d   )r  re   zes_engine_stats_tzesEngineGetActivityr   ra  r   r_   rz  r{  r|  rL  r}  
activeTime)r=   r/   re   stats_startrc   rz  	stats_endr  s           r!   utilizationr  d  s      +62M**,K		#	#M53E	FB	U000j
 	
 
U$$$B2$bI
 	
 JJ&/0((*I""=%	2BC:
 
		{44	4B  ;#9#99R?#EEr    c           	     :   t               }t        | d      } t        |        t        |    }|j                  |j                  S |j
                  }|j                  }t        d      }t        |j                  |t        |      d      d       |j                  dk(  rt        d       |j                  |j                  z         }t        |j                  |t        |      |      d       d}|D ]  }|j                         }	|j                  |	_        t        |j#                  |t        |	            d       |	j$                  |j&                  k7  rc|!|	j(                  sr|	j*                  |k(  s|} n|	j(                  r|} n |t        d	      ||_        |S )
a  Return the Level Zero Sysman GPU memory module handle for the specified device.

    The result is cached in ``_ZesDeviceInfo.memory_handle`` so that
    repeated calls skip module enumeration.  ``_cached_zes_device_infos``
    is lazily populated on the first call.

    Args:
        device (torch.device, str or int, optional): target device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).
    Tr   Nr   z0Can't get Level Zero Sysman memory module count.z*No Level Zero Sysman memory modules found.z2Can't get Level Zero Sysman memory module handles..Can't get Level Zero Sysman memory properties.z-No Level Zero Sysman GPU memory handle found.)rI  r   rP  r5   r0   r(   r)   r   rL  zesDeviceEnumMemoryModulesr   rn   r   zes_mem_handle_tzes_mem_properties_t!ZES_STRUCTURE_TYPE_MEM_PROPERTIESrv   zesMemoryGetPropertieslocationZES_MEM_LOC_DEVICErX  rY  )
r=   re   r   r(   r)   	mem_countmemory_handlesr0   
mem_handle	mem_propss
             r!   _zes_get_memory_handler    s    OEv5FV$#F+D%!!!&&M$$L I((i8H$O: !GHH>e,,y>AN((5+^	
 	=	 M$ 
..0	AA	((U95EF<	
 !9!99#$$)>)>,)N *(( *!$ JKK&Dr    c                T   t        |       }ddl}|j                         }|j                  |t	        |            }||j
                  k(  rt        d      ||j                  k7  rt        d| d      ddl}|j                  t        dz         |j                         }t        |j                  |t	        |            d       |j                  |j                  z
  }|j                  |j                  z
  }|j                  |j                  z
  }	d||	z   z  |j                  |z  z  d	z  S )
a  Return the GPU memory bandwidth usage as a percentage.

    The value is computed by dividing the byte-transfer delta by the time delta
    between two bandwidth-counter reads separated by a 100ms sampling interval,
    then normalizing by the peak bandwidth reported by the hardware.

    Args:
        device (torch.device, str or int, optional): selected device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).

    .. note:: This function blocks for approximately 100ms per call due to the
        sampling interval required to compute an accurate bandwidth reading.

    .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU memory bandwidth usage information.
    r   NzgGPU memory bandwidth usage querying is not available. Try running with elevated privileges (e.g. sudo).z5Can't get Level Zero Sysman GPU memory bandwidth (rc=rN  rw  z1Can't get Level Zero Sysman GPU memory bandwidth.g    .Ar  )r  re   zes_mem_bandwidth_tzesMemoryGetBandwidthr   ra  r   r_   rz  r{  r|  rL  r}  readCounterwriteCountermaxBandwidth)
r=   r0   re   bandwidth_startrc   rz  bandwidth_endr  
read_deltawrite_deltas
             r!   memory_usager    s,   " +62M//1O		$	$]E/4J	KB	U000u
 	
 
U$$$CB4rJ
 	
 JJ&/0--/M##M53GH; 
	 	 ?#<#<	<B**_-H-HHJ,,/K/KKK*{*+}/I/IB/NORUUUr    c                   t        |       }ddl}|j                         }|j                  |t	        |            }||j
                  k(  rt        d      ||j                  k7  rt        d| d      |j                         }|j                  |_
        t        |j                  |t	        |            d       |j                  dk7  r|j                  n|j                  }||j                  z
  S )av  Return the current GPU used global (device) memory in bytes.

    Args:
        device (torch.device, str or int, optional): selected device. Uses the
            current device, given by :func:`~torch.xpu.current_device`,
            if ``None`` (default).

    .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU memory usage information.
    r   Nz]GPU memory usage querying is not available. Try running with elevated privileges (e.g. sudo).z1Can't get Level Zero Sysman GPU memory state (rc=rN  r  )r  re   zes_mem_state_tzesMemoryGetStater   ra  r   r_   r  r  rv   rL  r  physicalSizesizefree)r=   r0   re   	mem_staterc   r  totals          r!   device_memory_usedr    s     +62M%%'I		 	 i0@	AB	U000k
 	
 
U$$$NrdRTUVV**,I==IO$$]E)4DE8 '0&<&<&AI""y~~E9>>!!r    )change_current_allocatorempty_cacheget_per_process_memory_fractionmax_memory_allocatedmax_memory_reservedmem_get_infomemory_allocatedmemory_reservedmemory_snapshotmemory_statsmemory_stats_as_nested_dictMemPoolreset_accumulated_memory_statsreset_peak_memory_statsset_per_process_memory_fractionuse_mem_poolXPUPluggableAllocator)	get_rng_stateget_rng_state_allinitial_seedmanual_seedmanual_seed_allr   r   set_rng_stateset_rng_state_all_POOL_HANDLE)?r   r   r  r  r   r  r  ro  r  r  r#   r=   r   r   r  r  r2  r  r   r   r8  r  r  r  r+  r   r   r   r  r   r   r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r  r  r  r  r  streamsr.  rc  r  )rj   r*   )r=   rP   rj   rP   )F)rj   	list[int])r}   r  rj   rP   )rj   rP   )T)r   r*   rj   r*   r   )r=   r   rj   r   r   )r=   r   rj   ri   )r=   r   rj   zdict[str, Any])r=   r   rj   r<   )r=   int | str | torch.devicerj   torch.device)r=   r   r  r   rj   r*   )r  r  rj   r  )r  r   rj   r   )r=   r   rj   r   )r*  rP   r=   r   rj   r   )rj   z	list[str])rj   ri   )r=   r  rj   ztorch._C.Generator)r   )r@  rP   r=   r  rj   r   )r=   r  rj   rP   )rc   rP   rd   ri   rj   r   )r=   rP   )r=   r   rj   r   )r=   r   rj   r   )r=   r   rj   rP   )r   
__future__r   dataclassesrK   	threadingr   r`   ctypesr   r   r   r   r   r	   	functoolsr
   typingr   r   r   r8   torch._Ctorch._utilsr   r   collections.abcr   torch.typesr   _utilsr   graphsr   r   r   r   r   r  r   r   r   localr   Lockr   r   r4   r   r9   r   r   r#   r%   	dataclassr'   r5   r|  r;   r<   _xpu_exchangeDevicerC   _xpu_maybeExchangeDevicerF   rY   r   r   r   r   r   r   r   r   r   r   r   r   r=   r   r   r   r  r   r  r	  r  r  r  r"  r  r  r+  r.  r2  r8  r:  rB  rE  rI  rL  rP  r^  rc  ri  ro  ru  r  r  r  r  r  r  memoryr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  randomr  r  r  r  r  r   r   r  r  r   rP   r  __all__r   r    r!   <module>r     s   #  	    E E  . .   6 (" %  # y%y~~'      %(($6F%' 02 - 2#' j ' * * * 24 . 3 
 > 8888xx33"XX>> ''=>NN"Jv r0
22U2
G%P
 
 ( 
(. 4 2 +*+*+*\%
; (3 (3V!&$2
-=	- 5:1	&* /

@F2,^&,^)<XBJ*FZ>B.Vb"F    &
 
 
 ~uS#X7@r    