
    ^j~#                        U d Z ddlZddlmZ  eej                  dd       Zdaej                  j                  ed<   dej                  j                  fdZ	de
fd	Zd d
Zd!de
ez  ej                  z  defdZd!dede
ez  ej                  z  ddfdZde
ddfdZd dZd dZd dZde
fdZde
fdZde
fdZdefdZd ZdefdZd"dZddlmZ ddlm Z  g dZ!y)#ag  
This package enables an interface for accessing MPS (Metal Performance Shaders) backend in Python.
Metal is Apple's API for programming metal GPU (graphics processor unit). Using MPS means that increased
performance can be achieved, by running work on the metal GPU(s).
See https://developer.apple.com/documentation/metalperformanceshaders for more details.
    N)Tensor_mps_is_in_bad_forkc                       y)NF r       ]/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/mps/__init__.py<lambda>r	      s    r   _default_mps_generatorreturnc                  V    t         t        j                  j                         a t         S )N)r
   torch_C_mps_get_default_generatorr   r   r   _get_default_mps_generatorr      s!    %!&!D!D!F!!r   c                      t        t        j                  j                  xr t        j                  j	                               S )z,Returns the number of available MPS devices.)intr   r   _has_mps_mps_is_availabler   r   r   device_countr      s)    uxx  AUXX%?%?%ABBr   c                  >    t         j                  j                         S )zAWaits for all kernels in all streams on a MPS device to complete.)r   r   _mps_deviceSynchronizer   r   r   synchronizer      s    88**,,r   devicec                 2    t               j                         S )zReturns the random number generator state as a ByteTensor.

    Args:
        device (torch.device or int, optional): The device to return the RNG state of.
            Default: ``'mps'`` (i.e., ``torch.device('mps')``, the current MPS device).
    )r   	get_state)r   s    r   get_rng_stater   #   s     &'1133r   	new_statec                 v    | j                  t        j                        }t               j	                  |       y)a  Sets the random number generator state.

    Args:
        new_state (torch.ByteTensor): The desired state
        device (torch.device or int, optional): The device to set the RNG state.
            Default: ``'mps'`` (i.e., ``torch.device('mps')``, the current MPS device).
    )memory_formatN)cloner   contiguous_formatr   	set_state)r   r   new_state_copys      r   set_rng_stater$   -   s+     __53J3J_KN **>:r   seedc                     t         j                  j                  syt        |       } t	               j                  |        y)zbSets the seed for generating random numbers.

    Args:
        seed (int): The desired seed.
    N)r   r   r   r   r   manual_seed)r%   s    r   r'   r'   9   s.     88t9D ,,T2r   c                  4    t               j                          y)z?Sets the seed for generating random numbers to a random number.N)r   r%   r   r   r   r%   r%   I   s     %%'r   c                  @    t         j                  j                          y)zReleases all unoccupied cached memory currently held by the caching
    allocator so that those can be used in other GPU applications.
    N)r   r   _mps_emptyCacher   r   r   empty_cacher+   N   s     
HHr   c                     t        | t              st        d      | dk  s| dkD  rt        d|  d      t        j
                  j                  |        y)a  Set memory fraction for limiting process's memory allocation on MPS device.
    The allowed value equals the fraction multiplied by recommended maximum device memory
    (obtained from Metal API device.recommendedMaxWorkingSetSize).
    If trying to allocate more than the allowed value in a process, it will raise an out of
    memory error in allocator.

    Args:
        fraction(float): Range: 0~2. Allowed memory equals total_memory * fraction.

    .. note::
       Passing 0 to fraction means unlimited allocations
       (may cause system failure if out of memory).
       Passing fraction greater than 1.0 allows limits beyond the value
       returned from device.recommendedMaxWorkingSetSize.
    z3Invalid type for fraction argument, must be `float`r      zInvalid fraction value: z. Allowed range: 0~2N)
isinstancefloat	TypeError
ValueErrorr   r   _mps_setMemoryFraction)fractions    r   set_per_process_memory_fractionr4   U   sO    " h&MNN!|x!|3H:=QRSS	HH##H-r   c                  >    t         j                  j                         S )zReturns the current GPU memory occupied by tensors in bytes.

    .. note::
       The returned size does not include cached allocations in
       memory pools of MPSAllocator.
    )r   r   _mps_currentAllocatedMemoryr   r   r   current_allocated_memoryr7   n   s     88//11r   c                  >    t         j                  j                         S )zReturns total GPU memory allocated by Metal driver for the process in bytes.

    .. note::
       The returned size includes cached allocations in MPSAllocator pools
       as well as allocations from MPS/MPSGraph frameworks.
    )r   r   _mps_driverAllocatedMemoryr   r   r   driver_allocated_memoryr:   x   s     88..00r   c                  >    t         j                  j                         S )zReturns recommended max Working set size for GPU memory in bytes.

    .. note::
       Recommended max working set size for Metal.
       returned from device.recommendedMaxWorkingSetSize.
    )r   r   _mps_recommendedMaxMemoryr   r   r   recommended_max_memoryr=      s     88--//r   sourcec                 T   ddl m} ddlm} t	        t
        j                  d      st        d       || j                  d      D cg c]  }|dz   	 c} |t              j                  j                  dz  gt                     } t
        j                  j                  |       S c c}w )a  Compiles compute shader from source and allows one to invoke kernels
    defined there from the comfort of Python runtime
    Example::

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_MPS)
        >>> lib = torch.mps.compile_shader(
        ... "kernel void full(device float* out, constant float& val, uint idx [[thread_position_in_grid]]) { out[idx] = val; }"
        ...  )
        >>> x = torch.zeros(16, device="mps")
        >>> lib.full(x, 3.14)
    r   )Path)_embed_headers_mps_compileShaderMPS is not available
include)pathlibr@   torch.utils._cpp_embed_headersrA   hasattrr   r   RuntimeErrorsplit__file__parentsetrB   )r>   r@   rA   ls       r   compile_shaderrO      s     =58812122!<<-.aT.	h			%	%		12F
 88&&v..	 	/s   B%c                    ddl }t        | t        t        f      rMt	        t
        j                  d      st        d      t
        j                  j                  t        |             S t        | t        |j                  f      rMt	        t
        j                  d      st        d      t
        j                  j                  t        |             S t        dt        |       j                         )a  Loads a precompiled Metal library (.metallib) and returns a shader
    library object that allows invoking kernels defined in it.

    Args:
        source: Either raw metallib bytes (``bytes``/``bytearray``) or a
            filesystem path (``str``/``os.PathLike``) to a ``.metallib`` file.

    This is useful for loading Metal libraries compiled ahead of time or
    generated by external tools (e.g. Triton, MetalASM).

    Example::

        >>> # xdoctest: +SKIP("requires external .metallib file")
        >>> lib = torch.mps.load_metallib("kernels.metallib")
        >>> x = torch.ones(16, device="mps")
        >>> lib.square(x)
    r   N_mps_loadMetalllibrC   _mps_loadMetallibFromPathzexpected bytes or path, got )osr.   bytes	bytearrayrH   r   r   rI   rQ   strPathLikerR   r0   type__name__)r>   rS   s     r   load_metallibrZ      s    $ &5),-uxx!56566xx**5=99	FS"++.	/uxx!<=566xx11#f+>>6tF|7L7L6MNOOr   c                      t               dkD  S )Nr   )r   r   r   r   is_availabler\      s    >Ar   c                 @    t         j                  j                  |       S )a  Returns a CPU :class:`torch.UntypedStorage` that aliases the
    host-visible contents of the MTLBuffer backing ``storage``.

    The returned storage shares memory with ``storage``: writes through the
    CPU alias land directly in the MPS-allocated MTLBuffer, avoiding a
    CPU->MPS staging copy. This is intended for advanced interop with bulk
    loaders (e.g. safetensors) that already know how to write into CPU
    memory.

    The alias storage retains a reference to the source MPS storage, so the
    host pointer remains valid for the alias's lifetime even if the original
    tensor is freed.

    Raises an exception if ``storage`` is not backed by a shared-storage
    ``id<MTLBuffer>`` allocated by the MPS allocator.

    .. warning::
        Use with caution. This bypasses the cache-coherence guarantees that
        the higher-level PyTorch APIs (:meth:`torch.Tensor.cpu`,
        :meth:`torch.Tensor.to`, ``copy_``) provide for you, and makes the
        caller responsible for ordering CPU and GPU accesses to the same
        memory. You should **always** call :func:`torch.mps.synchronize`
        both **before** issuing host reads/writes through the alias (to
        drain any in-flight GPU work that may still be touching the
        buffer) and **after** (before launching GPU work that depends on
        the host writes). Failure to do so can produce stale reads,
        torn writes, or data corruption.
    )r   r   _mps_host_alias_storage)storages    r   _host_alias_storager`      s    : 88++G44r      )profiler)Event)rO   rZ   r   r   r'   r%   r$   r   r+   r4   r7   r:   rc   rb   r=   r\   )r   N)mps)r_   torch.UntypedStorager   re   )"__doc__r   r   getattrr   _is_in_bad_forkr
   	Generator__annotations__r   r   r   r   rV   r   r   r$   r'   r%   r+   r4   r7   r:   r=   rO   rZ   boolr\   r`    rb   eventrc   __all__r   r   r   <module>ro      s'     %(($9=I-1 ** 1"EHH$6$6 "Cc C
-
4#)ell2 4v 4	;V 	;S3Y-E 	;RV 	;3c 3d 3 (
.22# 21 10 0/3 /4P@d 5@  r   