
    [Thܯ                        S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSK	J
r
JrJr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JrJrJrJr  S	SKJrJr   / SQr!\"" \R"                  S5      (       d  \" S5      \R"                  RF                  S'   \"" \R"                  S5      (       d  \" S5      \R"                  RF                  S'   \" S5      \R"                  RF                  S'   \" S5      \R"                  RF                  S'   \" S5      \R"                  RF                  S'   \" S5      \R"                  RF                  S'   SSK$J%r%J&r&J'r'J(r(J)r)J*r*  S r+\RX                  S 5       r-STS\\\.4   4S jjr/S r0SUS\1SS4S jjr2 SVS\\\.4   SS4S jjr3SVS\\\.4   S\44S jjr5SWS jr6SVS\\\.4   S\7\8\
4   4S jjr9SVS\\\.4   S\7\8\
4   4S  jjr:SVS\\\.4   SS4S! jjr;SVS\\\.4   SS4S" jjr<S\7\8\
4   4S# jr=S\7\8\
4   4S$ jr>SWS% jr?SWS& jr@SVS\\\.4   SS4S' jjrASVS\\\.4   SS4S( jjrBSVS\\\.4   S\.4S) jjrCSVS\\\.4   S\.4S* jjrDSVS\\\.4   S\.4S+ jjrESVS\\\.4   S\.4S, jjrF\" S-\GS.9SVS\\\.4   S\.4S/ jj5       rH\" S0\GS.9SVS\\\.4   S\.4S1 jj5       rIS2 rJSXS\\\.4   S3\1S\84S4 jjrKSVS\\\.4   S\84S5 jjrLSVS\\\.4   S\M\.\.4   4S6 jjrN     SYS7\1S\\\.4   4S8 jjrO SZS7\S:   SS4S; jjrPS9S9S9\R                  S4S7\\8   S<\\8   S=\8S>\.S\\\.4   4
S? jjrR\" \R5      \PlS        SVS\\\.4   4S@ jjrTS[SA jrUS\SB jrVS\SC jrWSD\84SE jrXS\84SF jrY " SG SH5      rZ " SI SJ\Z5      r[SK\ZSS4SL jr\S\Z4SM jr] " SN SO\*5      r^ " SP SQ\)5      r_\RX                  SVSR\_S\\\.4   4SS jj5       r`g)]zKThis package adds support for device memory management implemented in CUDA.    N)	signature)AnyLiteralOptionalUnion)
deprecated)_C)_dummy_type)Device   )_get_amdsmi_device_index_get_device_index_get_nvml_device_index
_lazy_initis_initialized)memorysegments) caching_allocator_alloccaching_allocator_deletecaching_allocator_enableget_per_process_memory_fractionset_per_process_memory_fractionempty_cachememory_statsmemory_stats_as_nested_dictreset_accumulated_memory_statsreset_peak_memory_statsreset_max_memory_allocatedreset_max_memory_cachedhost_memory_stats host_memory_stats_as_nested_dict#reset_accumulated_host_memory_statsreset_peak_host_memory_statsmemory_allocatedmax_memory_allocatedmemory_reservedmax_memory_reservedmemory_cachedmax_memory_cachedmemory_snapshotmemory_summarylist_gpu_processesmem_get_infoget_allocator_backendCUDAPluggableAllocatorchange_current_allocatorMemPoolMemPoolContextuse_mem_pool_cuda_CUDAAllocator_MemPool_MemPoolContext_cuda_beginAllocateToPool$_cuda_endAllocateCurrentStreamToPool_cuda_releasePool)r7   r4   r8   r9   r5   r6   c                  R    [        5         [        R                  R                  5       $ N)r   torchr	   _cuda_cudaHostAllocator     I/var/www/auris/envauris/lib/python3.13/site-packages/torch/cuda/memory.py_host_allocatorrA   \   s    L88++--r?   c               #      #    [         R                  R                  5          S v   [         R                  R                  5         g ! [         R                  R                  5         f = f7fr;   )r<   r	   _cuda_lock_mutex_cuda_unlock_mutexr>   r?   r@   _free_mutexrE   a   s=     	HH&##%##%s   A(A A( A%%A(devicec                    Uc  [         R                  R                  5       n[        U5      nUc  [         R                  R	                  U5      n[        U[         R                  R                  R                  5      (       a  UR                  n[        U[        5      (       d  [        S5      e[         R                  R                  U5         [         R                  R                  X5      sSSS5        $ ! , (       d  f       g= f)a  Perform a memory allocation using the CUDA memory allocator.

Memory is allocated for a given device and a stream, this
function is intended to be used for interoperability with other
frameworks. Allocated memory is released through
:func:`~torch.cuda.caching_allocator_delete`.

Args:
    size (int): number of bytes to be allocated.
    device (torch.device or int, optional): selected device. If it is
        ``None`` the default CUDA device is used.
    stream (torch.cuda.Stream or int, optional): selected stream. If is ``None`` then
        the default stream for the selected device is used.

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
NzrInvalid type for stream argument, must be `torch.cuda.Stream` or `int` representing a pointer to a existing stream)r<   cudacurrent_devicer   current_stream
isinstancestreamsStreamcuda_streamint	TypeErrorrF   r	   $_cuda_cudaCachingAllocator_raw_alloc)sizerF   streams      r@   r   r   j   s    & ~**,v&F~**62&%**,,3344##fc""#
 	

 
		6	"xx<<TJ 
#	"	"s   C66
Dc                 B    [         R                  R                  U 5        g)ay  Delete memory allocated using the CUDA memory allocator.

Memory allocated with :func:`~torch.cuda.caching_allocator_alloc`.
is freed here. The associated device and stream are tracked inside
the allocator.

Args:
    mem_ptr (int): memory address to be freed by the allocator.

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
N)r<   r	   %_cuda_cudaCachingAllocator_raw_delete)mem_ptrs    r@   r   r      s     
HH227;r?   valuereturnc                 b    [        5       (       a   [        R                  R                  U 5        gg)z;Enable or disable the CUDA memory allocator. On by default.N)r   r<   r	   !_cuda_cudaCachingAllocator_enable)rW   s    r@   r   r      s"    2259 r?   c                 $   [        5         Uc  [        R                  R                  5       n[	        U5      n[        U [        5      (       d  [        S5      eU S:  d  U S:  a  [        SU  S35      e[        R                  R                  X5        g)a^  Set memory fraction for a process.

The fraction is used to limit an caching allocator to allocated memory on a CUDA device.
The allowed value equals the total visible memory multiplied fraction.
If trying to allocate more than the allowed value in a process, will raise an out of
memory error in allocator.

Args:
    fraction(float): Range: 0~1. Allowed memory equals total_memory * fraction.
    device (torch.device or int, optional): selected device. If it is
        ``None`` the default CUDA device is used.
.. note::
    In general, the total available free memory is less than the total capacity.
Nz3Invalid type for fraction argument, must be `float`r   r   zInvalid fraction value: z. Allowed range: 0~1)r   r<   rH   rI   r   rK   floatrP   
ValueErrorr	   _cuda_setMemoryFraction)fractionrF   s     r@   r   r      sx    " L~**,v&Fh&&MNN!|x!|3H:=QRSS	HH$$X6r?   c                     [        5         U c  [        R                  R                  5       n [	        U 5      n [        R
                  R                  U 5      $ )zGet memory fraction for a process.

Args:
    device (torch.device or int, optional): selected device. If it is
        ``None`` the default CUDA device is used.
Returns:
    memory fraction, in range 0~1. Allowed memory equals total_memory * fraction.
)r   r<   rH   rI   r   r	   _cuda_getMemoryFractionrF   s    r@   r   r      s?     L~**,v&F88++F33r?   c                  `    [        5       (       a  [        R                  R                  5         gg)a  Release all unoccupied cached memory currently held by the caching
allocator so that those can be used in other GPU application and visible in
`nvidia-smi`.

.. note::
    :func:`~torch.cuda.empty_cache` doesn't increase the amount of GPU
    memory available for PyTorch. However, it may help reduce fragmentation
    of GPU memory in certain cases. See :ref:`cuda-memory-management` for
    more details about GPU memory management.
N)r   r<   r	   _cuda_emptyCacher>   r?   r@   r   r      s"     !!# r?   c                    ^^ / mUU4S jm[        U S9nT" SU5        TR                  5         [        R                  " T5      $ )a  Return a dictionary of CUDA memory allocator statistics for a given device.

The return value of this function is a dictionary of statistics, each of
which is a non-negative integer.

Core statistics:

- ``"allocated.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  number of allocation requests received by the memory allocator.
- ``"allocated_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  amount of allocated memory.
- ``"segment.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  number of reserved segments from ``cudaMalloc()``.
- ``"reserved_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  amount of reserved memory.
- ``"active.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  number of active memory blocks.
- ``"active_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  amount of active memory.
- ``"inactive_split.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  number of inactive, non-releasable memory blocks.
- ``"inactive_split_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  amount of inactive, non-releasable memory.

For these core statistics, values are broken down as follows.

Pool type:

- ``all``: combined statistics across all memory pools.
- ``large_pool``: statistics for the large allocation pool
  (as of October 2019, for size >= 1MB allocations).
- ``small_pool``: statistics for the small allocation pool
  (as of October 2019, for size < 1MB allocations).

Metric type:

- ``current``: current value of this metric.
- ``peak``: maximum value of this metric.
- ``allocated``: historical total increase in this metric.
- ``freed``: historical total decrease in this metric.

In addition to the core statistics, we also provide some simple event
counters:

- ``"num_alloc_retries"``: number of failed ``cudaMalloc`` calls that
  result in a cache flush and retry.
- ``"num_ooms"``: number of out-of-memory errors thrown.
- ``"num_sync_all_streams"``: number of ``synchronize_and_free_events`` calls.
- ``"num_device_alloc"``: number of CUDA allocation calls. This includes both
  cuMemMap and cudaMalloc.
- ``"num_device_free"``: number of CUDA free calls. This includes both cuMemUnmap
  and cudaFree.

The caching allocator can be configured via ENV to not split blocks larger than a
defined size (see Memory Management section of the Cuda Semantics documentation).
This helps avoid memory fragmentation but may have a performance
penalty. Additional outputs to assist with tuning and evaluating impact:

- ``"max_split_size"``: blocks above this size will not be split.
- ``"oversize_allocations.{current,peak,allocated,freed}"``:
  number of over-size allocation requests received by the memory allocator.
- ``"oversize_segments.{current,peak,allocated,freed}"``:
  number of over-size reserved segments from ``cudaMalloc()``.

The caching allocator can be configured via ENV to round memory allocations in order
to reduce fragmentation. Sometimes the overhead from rounding can be higher than
the fragmentation it helps reduce. The following stat can be used to check if
rounding adds too much overhead:

- ``"requested_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
  memory requested by client code, compare this with allocated_bytes to check if
  allocation rounding adds too much overhead.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistics for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.

.. note::
    With :ref:`backend:cudaMallocAsync<cuda-memory-envvars>`, some stats are not
    meaningful, and are always reported as zero.
c                    > [        U[        5      (       a9  [        U 5      S:  a  U S-  n UR                  5        H  u  p#T" X-   U5        M     g TR	                  X45        g Nr   .rK   dictlenitemsappendprefixobjkv_recurse_add_to_resultresults       r@   rs   ,memory_stats.<locals>._recurse_add_to_result:  R    c4  6{Q#		&vz15 $ MM6-(r?   rb    )r   sortcollectionsOrderedDict)rF   statsrs   rt   s     @@r@   r   r      s@    n F) (v6E2u%
KKM""6**r?   c                 v    [        5       (       d  0 $ [        U SS9n [        R                  R	                  U 5      $ )zMReturn the result of :func:`~torch.cuda.memory_stats` as a nested dictionary.Toptional)r   r   r<   r	   _cuda_memoryStatsrb   s    r@   r   r   J  s1    	v5F88%%f--r?   c                 T    [        U SS9n [        R                  R                  U 5      $ )aQ  Reset the "accumulated" (historical) stats tracked by the CUDA memory allocator.

See :func:`~torch.cuda.memory_stats` for details. Accumulated stats correspond to
the `"allocated"` and `"freed"` keys in each individual stat dict, as well as
`"num_alloc_retries"` and `"num_ooms"`.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
Tr}   )r   r<   r	   !_cuda_resetAccumulatedMemoryStatsrb   s    r@   r   r   R  s%      v5F8855f==r?   c                 T    [        U SS9n [        R                  R                  U 5      $ )a  Reset the "peak" stats tracked by the CUDA memory allocator.

See :func:`~torch.cuda.memory_stats` for details. Peak stats correspond to the
`"peak"` key in each individual stat dict.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
Tr}   )r   r<   r	   _cuda_resetPeakMemoryStatsrb   s    r@   r   r   f  s%     v5F88..v66r?   c                     ^^ / mUU4S jm[        5       n T" SU 5        TR                  5         [        R                  " T5      $ )a  Return a dictionary of CUDA memory allocator statistics for a given device.

 The return value of this function is a dictionary of statistics, each of
 which is a non-negative integer.

 Core statistics:

 - ``"allocated.{current,peak,allocated,freed}"``:
   number of allocation requests received by the memory allocator.
 - ``"allocated_bytes.{current,peak,allocated,freed}"``:
   amount of allocated memory.
 - ``"segment.{current,peak,allocated,freed}"``:
   number of reserved segments from ``cudaMalloc()``.
 - ``"reserved_bytes.{current,peak,allocated,freed}"``:
   amount of reserved memory.

 For these core statistics, values are broken down as follows.

 Metric type:

 - ``current``: current value of this metric.
 - ``peak``: maximum value of this metric.
 - ``allocated``: historical total increase in this metric.
 - ``freed``: historical total decrease in this metric.

 In addition to the core statistics, we also provide some simple event
 counters:

 - ``"num_host_alloc"``: number of CUDA allocation calls. This includes both
   cudaHostAlloc and cudaHostRegister.
 - ``"num_host_free"``: number of CUDA free calls. This includes both cudaHostFree
   and cudaHostUnregister.

 Finally, we also provide some simple timing counters:

 - ``"host_alloc_time.{total,max,min,count,avg}"``:
   timing of allocation requests going through CUDA calls.
 - ``"host_free_time.{total,max,min,count,avg}"``:
   timing of free requests going through CUDA calls.

For these timing statistics, values are broken down as follows.

 Metric type:

 - ``total``: total time spent.
 - ``max``: maximum value per call.
 - ``min``: minimum value per call.
 - ``count``: number of times it was called.
 - ``avg``: average time per call.
c                    > [        U[        5      (       a9  [        U 5      S:  a  U S-  n UR                  5        H  u  p#T" X-   U5        M     g TR	                  X45        g rg   ri   rn   s       r@   rs   1host_memory_stats.<locals>._recurse_add_to_result  rv   r?   rw   )r!   rx   ry   rz   )r{   rs   rt   s    @@r@   r    r    y  s>    f F) -.E2u%
KKM""6**r?   c                  `    [        5       (       d  0 $ [        R                  R                  5       $ )zRReturn the result of :func:`~torch.cuda.host_memory_stats` as a nested dictionary.)r   r<   r	   _cuda_hostMemoryStatsr>   r?   r@   r!   r!     s#    	88))++r?   c                  >    [         R                  R                  5       $ )zReset the "accumulated" (historical) stats tracked by the host memory allocator.

See :func:`~torch.cuda.host_memory_stats` for details. Accumulated stats correspond to
the `"allocated"` and `"freed"` keys in each individual stat dict.
)r<   r	   %_cuda_resetAccumulatedHostMemoryStatsr>   r?   r@   r"   r"     s     8899;;r?   c                  >    [         R                  R                  5       $ )zReset the "peak" stats tracked by the host memory allocator.

See :func:`~torch.cuda.host_memory_stats` for details. Peak stats correspond to the
`"peak"` key in each individual stat dict.
)r<   r	   _cuda_resetPeakHostMemoryStatsr>   r?   r@   r#   r#     s     882244r?   c                 J    [         R                  " S[        5        [        U S9$ )aS  Reset the starting point in tracking maximum GPU memory occupied by tensors for a given device.

See :func:`~torch.cuda.max_memory_allocated` for details.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. warning::
    This function now calls :func:`~torch.cuda.reset_peak_memory_stats`, which resets
    /all/ peak memory stats.

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
zytorch.cuda.reset_max_memory_allocated now calls torch.cuda.reset_peak_memory_stats, which resets /all/ peak memory stats.rb   warningswarnFutureWarningr   rb   s    r@   r   r     %    $ MM	0
 #&11r?   c                 J    [         R                  " S[        5        [        U S9$ )a]  Reset the starting point in tracking maximum GPU memory managed by the caching allocator for a given device.

See :func:`~torch.cuda.max_memory_cached` for details.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. warning::
    This function now calls :func:`~torch.cuda.reset_peak_memory_stats`, which resets
    /all/ peak memory stats.

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
zvtorch.cuda.reset_max_memory_cached now calls torch.cuda.reset_peak_memory_stats, which resets /all/ peak memory stats.rb   r   rb   s    r@   r   r     r   r?   c                 4    [        U S9R                  SS5      $ )a3  Return the current GPU memory occupied by tensors in bytes for a given device.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    This is likely less than the amount shown in `nvidia-smi` since some
    unused memory can be held by the caching allocator and some context
    needs to be created on GPU. See :ref:`cuda-memory-management` for more
    details about GPU memory management.
rb   zallocated_bytes.all.currentr   r   getrb   s    r@   r$   r$     s     v&**+H!LLr?   c                 4    [        U S9R                  SS5      $ )a  Return the maximum GPU memory occupied by tensors in bytes for a given device.

By default, this returns the peak allocated memory since the beginning of
this program. :func:`~torch.cuda.reset_peak_memory_stats` can be used to
reset the starting point in tracking this metric. For example, these two
functions can measure the peak allocated memory usage of each iteration in a
training loop.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
rb   zallocated_bytes.all.peakr   r   rb   s    r@   r%   r%     s    $ v&**+EqIIr?   c                 4    [        U S9R                  SS5      $ )a  Return the current GPU memory managed by the caching allocator in bytes for a given device.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
rb   zreserved_bytes.all.currentr   r   rb   s    r@   r&   r&   1  s     v&**+GKKr?   c                 4    [        U S9R                  SS5      $ )a  Return the maximum GPU memory managed by the caching allocator in bytes for a given device.

By default, this returns the peak cached memory since the beginning of this
program. :func:`~torch.cuda.reset_peak_memory_stats` can be used to reset
the starting point in tracking this metric. For example, these two functions
can measure the peak cached memory amount of each iteration in a training
loop.

Args:
    device (torch.device or int, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
rb   zreserved_bytes.all.peakr   r   rb   s    r@   r'   r'   @  s    $ v&**+DaHHr?   zK`torch.cuda.memory_cached` has been renamed to `torch.cuda.memory_reserved`)categoryc                     [        U S9$ )z4Deprecated; see :func:`~torch.cuda.memory_reserved`.rb   )r&   rb   s    r@   r(   r(   U  s     &))r?   zS`torch.cuda.max_memory_cached` has been renamed to `torch.cuda.max_memory_reserved`c                     [        U S9$ )z8Deprecated; see :func:`~torch.cuda.max_memory_reserved`.rb   )r'   rb   s    r@   r)   r)   ^  s     f--r?   c                  D    [         R                  R                  5       S   $ )a  Return a snapshot of the CUDA memory allocator state across all devices.

Interpreting the output of this function requires familiarity with the
memory allocator internals.

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
r   )r<   r	   _cuda_memorySnapshotr>   r?   r@   r*   r*   g  s     88((*:66r?   abbreviatedc                    [        U SS9n [        U S9nS nS nSSU4SS	U4S
SU4SSU4SSU4SSU4SSU4SSU4SSU4/	n/ nUR                  S5        UR                  S5        UR                  S5        UR                  S5        UR                  S5        UR                  S5        U H  u  pxn	UR                  S5        SU4/n
U(       d"  U
R                  S5        U
R                  S5        S u  ppU
 Hz  u  nnUS!-   U-   S!-   nUUS"-      nUUS#-      nUUS$-      nUUS%-      nUc  UnUnUnUnUR                  S&US' S(U	" UU5       S(U	" UU5       S(U	" UU5       S(U	" UU5       S&35        M|     M     S)S*U4S+S,U4/nU Hz  u  pxn	UR                  S5        US!-   nUUS"-      nUUS#-      nUUS$-      nUUS%-      nUR                  S&US' S(U	" UU5       S(U	" UU5       S(U	" UU5       S(U	" UU5       S&35        M|     UR                  S5        S-U S..nUR                  5        H  u  nnUUUR	                  S!S/5      '   M     S0S1R                  U5      R                  " S30 UD6-   S2-   $ )4ac  Return a human-readable printout of the current memory allocator statistics for a given device.

This can be useful to display periodically during training, or when
handling out-of-memory exceptions.

Args:
    device (torch.device or int, optional): selected device. Returns
        printout for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).
    abbreviated (bool, optional): whether to return an abbreviated summary
        (default: False).

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
Tr}   rb   c                 d    / SQnUS   nUSS   H  nUS:  a    OUnU S-  n US-  nM     U S SU 3$ )N)zB  KiBMiBGiBTiBPiBr   r   i   i   6d r>   )szpref_szprefixesro   
new_prefixs        r@   _format_size$memory_summary.<locals>._format_size  sW    =!"12,J#F4KBtOG ' R&""r?   c                 f    / SQnUS   nUSS   H  nUS:  a    OUnU S-  n US-  nM     U S SU S3$ )N)r   KMr   r   iq i  7dr   r>   )cntpref_cntr   ro   r   s        r@   _format_count%memory_summary.<locals>._format_count  sZ    "!"12,J*$FDLCH ' b6(!$$r?   allocated_byteszAllocated memoryactive_byteszActive memoryrequested_byteszRequested memoryreserved_byteszGPU reserved memoryinactive_split_byteszNon-releasable memory
allocationAllocationsactivezActive allocssegmentzGPU reserved segmentsinactive_splitzNon-releasable allocszK===========================================================================z= {_:16} PyTorch CUDA memory summary, device ID {device:<17d} zK---------------------------------------------------------------------------zX  {_:9} CUDA OOMs: {num_ooms:<12d} | {_:6} cudaMalloc retries: {num_alloc_retries:<8d}  zK        Metric         | Cur Usage  | Peak Usage | Tot Alloc  | Tot Freed  all)
large_poolz      from large pool)
small_poolz      from small pool)NNNNrh   currentpeak	allocatedfreedr   z<21z | oversize_allocationszOversize allocationsoversize_segmentszOversize GPU segmentsrw   )_rF   -|z|
|z|
r>   )r   r   rm   rl   replacejoinformat)rF   r   r{   r   r   metrics_to_displaylines
metric_keymetric_name	formatter
submetricscurrent_prefvalpeak_prefvalallocated_prefvalfreed_prefvalsubmetric_keysubmetric_namero   r   r   r   r   fmt_dictrq   rr   s                            r@   r+   r+   t  s`   " v5F'E	#	% 
.=	,7	.=	0,?	!8,G	}m4	?M2	+];	2MB
 E	LL	LLPQ	LL	LLb 
LL	LLU /A*
Xk*+
EFEFK
G'8 .8)M>#%5;FFY./G&)Df{23I&7*+E&")#$-! %LLN3's9Wo+N*OsS\]acoSpRqqtY(9:;3yP]?^>__`b .8 /AD 
 !7G	5}E
 /A*
Xc!*+Vf_%&;./	fw&'C Igw$?#@IdTXDYCZZ]I./s9UE3J2K1N	
 /A 
LL6*H1()3$% U#**6X66>>r?   c                    [         R                  R                  (       dJ   SSKnSSKJn   UR                  5         [        U 5      n UR                  U 5      nUR                  U5      nOF SSK
n UR                  5         [        U 5      n  UR                  5       U    nUR                  U5      n/ nUR!                  S	U  35        [#        U5      S:X  a  UR!                  S
5        U Hz  n[         R                  R                  (       d  UR$                  S-  nUR&                  n	O" WR)                  X75      n
U
S   S   S-  nU
S   n	UR!                  SU	S SUS S35        M|     SR-                  U5      $ ! [         a     gf = f! U a     gf = f! [         a     gf = f! UR                   a     gf = f! UR                   a     gf = f! [*         a    Un
 Nf = f)a  Return a human-readable printout of the running processes and their GPU memory use for a given device.

This can be useful to display periodically during training, or when
handling out-of-memory exceptions.

Args:
    device (torch.device or int, optional): selected device. Returns
        printout for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).
r   Nz.pynvml module not found, please install pynvml)NVMLError_DriverNotLoadedz-cuda driver can't be loaded, is cuda enabled?z.amdsmi module not found, please install amdsmiz1amdsmi driver can't be loaded, is ROCm installed?z-amdsmi cannot list processes from other userszGPU:zno processes are runningi   memory_usagevram_mempidzprocess z>10dz uses z>12.3fz MB GPU memory
)r<   versionhippynvmlModuleNotFoundErrorr   nvmlInitr   nvmlDeviceGetHandleByIndex$nvmlDeviceGetComputeRunningProcessesamdsmiamdsmi_initAmdSmiExceptionr   amdsmi_get_processor_handlesamdsmi_get_gpu_process_listrm   rk   usedGpuMemoryr   amdsmi_get_gpu_process_infoAttributeErrorr   )rF   r   r   handleprocsr   r   pmemr   	proc_infos              r@   r,   r,     s    ==	D 	5	COO (/226:;;FC	D	G  *&1	C88:6BF66v>E E	LL4x!
5zQ/0}}  //[1C%%C">>vI	
 N+J7;GCE"CxDzF|>JK  99Ua # 	DC	D ) 	CB	C # 	DC	D %% 	GF	G %% 	CB	C "  	sj   E7 F +F 0F# $F9 'G7
FFFF
F F #F65F69GGGGc                     U c  [         R                  R                  5       n [        U SS9n [         R                  R	                  5       R                  U 5      $ )a  Return the global free and total GPU memory for a given device using cudaMemGetInfo.

Args:
    device (torch.device or int or str, optional): selected device. Returns
        statistic for the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default) or if the device index is not specified.

.. note::
    See :ref:`cuda-memory-management` for more
    details about GPU memory management.
Tr}   )r<   rH   rI   r   cudartcudaMemGetInforb   s    r@   r-   r-   4  sE     ~**,v5F::--f55r?   enabledc                 8    [         R                  " U UUUU5        g r;   )r	   "_cuda_record_memory_history_legacy)r   record_contexttrace_alloc_max_entriestrace_alloc_record_contextrF   record_context_cpps         r@   _record_memory_history_legacyr  G  s!     ))"r?   r   )Nstater   c                 h    [        U [        5      (       a  [        U /UQ70 UD6$ [        U /UQ70 UD6$ )a  Enable recording of stack traces associated with memory
allocations, so you can tell what allocated any piece of memory in
:func:`torch.cuda.memory._snapshot()`.

In addition too keeping stack traces with each current allocation and free,
this will also enable recording of a history of all alloc/free events.

Use :func:`torch.cuda.memory._snapshot()` to retrieve this information,
and the tools in `_memory_viz.py` to visualize snapshots.

The Python trace collection is fast (2us per trace), so you may consider
enabling this on production jobs if you anticipate ever having to debug
memory issues.

C++ trace collection is also fast (~50ns/frame), which for many typical programs
works out to ~2us per trace, but can vary depending on stack depth.

Args:
    enabled (Literal[None, "state", "all"], optional):
        `None`, disable recording memory history.
        `"state"`, keep information for currenly allocated memory.
        `"all"`, additionally keep a history of all alloc/free calls.
        Defaults to "all".
    context (Literal[None, "state", "alloc", "all"], optional):
        `None`, Do not record any tracebacks.
        `"state"`, Record tracebacks for currently allocated memory.
        `"alloc"`, additionally keep tracebacks for alloc calls.
        `"all"`, additionally keep tracebacks for free calls.
        Defaults to "all".
    stacks (Literal["python", "all"], optional):
        `"python"`, include Python, TorchScript, and inductor frames in tracebacks
        `"all"`, additionally include C++ frames
        Defaults to "all".
    max_entries (int, optional): Keep a maximum of `max_entries`
        alloc/free events in the recorded history recorded.
)rK   boolr  _record_memory_history_impl)r   argskwargss      r@   _record_memory_historyr  X  s<    N '4  ,WFtFvFF*7DTDVDDr?   contextstacksmax_entriesc                 2    [         R                  " XX#5        g r;   )r	   _cuda_record_memory_history)r   r	  r
  r  rF   s        r@   r  r    s     ""7VIr?   c                 ,    [         R                  " 5       $ )a  Save a snapshot of CUDA memory state at the time it was called.

The state is represented as a dictionary with the following structure.

.. code-block:: python

    class Snapshot(TypedDict):
        segments : List[Segment]
        device_traces: List[List[TraceEntry]]

    class Segment(TypedDict):
        # Segments are memory returned from a cudaMalloc call.
        # The size of reserved memory is the sum of all Segments.
        # Segments are cached and reused for future allocations.
        # If the reuse is smaller than the segment, the segment
        # is split into more then one Block.
        # empty_cache() frees Segments that are entirely inactive.
        address: int
        total_size: int #  cudaMalloc'd size of segment
        stream: int
        segment_type: Literal['small', 'large'] # 'large' (>1MB)
        allocated_size: int # size of memory in use
        active_size: int # size of memory in use or in active_awaiting_free state
        blocks : List[Block]

    class Block(TypedDict):
        # A piece of memory returned from the allocator, or
        # current cached but inactive.
        size: int
        requested_size: int # size requested during malloc, may be smaller than
                            # size due to rounding
        address: int
        state: Literal['active_allocated', # used by a tensor
                    'active_awaiting_free', # waiting for another stream to finish using
                                            # this, then it will become free
                    'inactive',] # free for reuse
        frames: List[Frame] # stack trace from where the allocation occurred

    class Frame(TypedDict):
            filename: str
            line: int
            name: str

    class TraceEntry(TypedDict):
        # When `torch.cuda.memory._record_memory_history()` is enabled,
        # the snapshot will contain TraceEntry objects that record each
        # action the allocator took.
        action: Literal[
        'alloc'  # memory allocated
        'free_requested', # the allocated received a call to free memory
        'free_completed', # the memory that was requested to be freed is now
                        # able to be used in future allocation calls
        'segment_alloc', # the caching allocator ask cudaMalloc for more memory
                        # and added it as a segment in its cache
        'segment_free',  # the caching allocator called cudaFree to return memory
                        # to cuda possibly trying free up memory to
                        # allocate more segments or because empty_caches was called
        'oom',          # the allocator threw an OOM exception. 'size' is
                        # the requested number of bytes that did not succeed
        'snapshot'      # the allocator generated a memory snapshot
                        # useful to coorelate a previously taken
                        # snapshot with this trace
        ]
        addr: int # not present for OOM
        frames: List[Frame]
        size: int
        stream: int
        device_free: int # only present for OOM, the amount of
                        # memory cuda still reports to be free

Returns:
    The Snapshot dictionary object
)r	   r   rb   s    r@   	_snapshotr    s    T ""$$r?   c                     [        5       n[        U S5       n[        R                  " X5        SSS5        g! , (       d  f       g= f)a  
Save a pickled version of the `torch.memory._snapshot()` dictionary to a file.

This file can be opened by the interactive snapshot viewer at pytorch.org/memory_viz

Args:
    filename (str, optional): Name of the file to create. Defaults to "dump_snapshot.pickle".
wbN)r  openpickledump)filenamesfs      r@   _dump_snapshotr    s/     	A	h	A 
		s	   7
Ac                     Uc
  [        5       n[        U S5       nUR                  [        U5      5        S S S 5        g ! , (       d  f       g = fNw)r  r  write	_segmentsr  snapshotr  s      r@   _save_segment_usager     s8    ;	h			(#$ 
			   >
Ac                     Uc
  [        5       n[        U S5       nUR                  [        U5      5        S S S 5        g ! , (       d  f       g = fr  )r  r  r  _memoryr  s      r@   _save_memory_usager$    s8    ;	h		!" 
		r!  envc                 @    [         R                  R                  U 5      $ r;   )r<   r	   1_cuda_cudaCachingAllocator_set_allocator_settings)r%  s    r@   _set_allocator_settingsr(    s    88EEcJJr?   c                  >    [         R                  R                  5       $ )aQ  Return a string describing the active allocator backend as set by
``PYTORCH_CUDA_ALLOC_CONF``. Currently available backends are
``native`` (PyTorch's native caching allocator) and `cudaMallocAsync``
(CUDA's built-in asynchronous allocator).

.. note::
    See :ref:`cuda-memory-management` for details on choosing the allocator backend.
)r<   r	   _cuda_getAllocatorBackendr>   r?   r@   r.   r.     s     88--//r?   c                   T    \ rS rSrSrS\R                  R                  4S jrS r	Sr
g)_CUDAAllocatori  z-Wrapper over internal CUDA memory allocators.	allocatorc                     Xl         g r;   
_allocator)selfr-  s     r@   __init___CUDAAllocator.__init__  s    #r?   c                     U R                   $ r;   r/  )r1  s    r@   r-  _CUDAAllocator.allocator  s    r?   r/  N)__name__
__module____qualname____firstlineno____doc__r<   r	   r4   r2  r-  __static_attributes__r>   r?   r@   r,  r,    s     8$%((">"> $r?   r,  c                   .    \ rS rSrSrS\S\S\4S jrSrg)	r/   i  z,CUDA memory allocator loaded from a so file.path_to_so_filealloc_fn_namefree_fn_namec                 l   [         R                  " U5      n[         R                  " [        XB5      [         R                  5      R
                  n[         R                  " [        XC5      [         R                  5      R
                  nUc   eUc   e[        R                  R                  XV5      U l	        g)aZ  Memory allocators are compiled in .so files and loaded dynamically using ctypes.

To change the active allocator use the :func:`torch.memory.cuda.change_current_allocator` function.

Args:
    path_to_so_file(str): Path in the filesystem to the `.so` file containing
        the allocator functions
    alloc_fn_name(str): Name of the function to perform the memory allocation
        in the so file. The signature must be:
        void* alloc_fn_name(ssize_t size, int device, cudaStream_t stream);
    free_fn_name(str): Name of the function to perform the memory release
        in the so file. The signature must be:
        void free_fn_name(void* ptr, size_t size, cudaStream_t stream);

.. warning::
    This is currently supported only in unix OSs

.. note::
    See :ref:`cuda-memory-management` for details on creating and using a custom allocator
N)
ctypesCDLLcastgetattrc_void_prW   r<   r	   _cuda_customAllocatorr0  )r1  r=  r>  r?  r-  alloc_fnfree_fns          r@   r2  CUDAPluggableAllocator.__init__  s~    * KK0	;;wy@&//RXX++gi>PVV###"""((88Kr?   r/  N)r6  r7  r8  r9  r:  strr2  r;  r>   r?   r@   r/   r/     s#    7L LC Ls Lr?   r/   r-  c                 ^    [         R                  R                  U R                  5       5        g)a`  Change the currently used memory allocator to be the one provided.

If the current allocator has already been used/initialized, this function will error.


Args:
    allocator (torch.cuda.memory._CUDAAllocator): allocator to be set as the active one.
.. note::
    See :ref:`cuda-memory-management` for details on creating and using a custom allocator
N)r<   r	   _cuda_changeCurrentAllocatorr-  )r-  s    r@   r0   r0   5  s     
HH)))*=*=*?@r?   c                  P    [        [        R                  R                  5       5      $ )zReturn the allocator being currently used.

.. note::
    See :ref:`cuda-memory-management` for details on creating and using a custom allocator
)r,  r<   r	   _cuda_getAllocatorr>   r?   r@   _get_current_allocatorrO  C  s     %((55788r?   c                   R   ^  \ rS rSrSrS\4U 4S jjr\S\\   4S j5       r	Sr
U =r$ )r2   iL  zMemPoolContext holds the currently active pool and stashes the previous
pool. On deletion it makes the previous pool active.

Args:
    pool(torch.cuda.MemPool): a MemPool object to be made active so that
    allocations route to this pool.

poolc                 $   > [         TU ]  U5        g r;   superr2  )r1  rQ  	__class__s     r@   r2  MemPoolContext.__init__V  s    r?   rX   c                  ,    [         R                  " 5       $ )zReturns the active MemPool)r6   active_poolr>   r?   r@   rX  MemPoolContext.active_poolY  s     **,,r?   r>   )r6  r7  r8  r9  r:  r5   r2  staticmethodr   rX  r;  __classcell__rU  s   @r@   r2   r2   L  s4    X  -(+ - -r?   r2   c                      ^  \ rS rSrSrSS\\   4U 4S jjjr\S\	\
\
4   4U 4S jj5       r\S\\   4U 4S jj5       rS\
4U 4S jjrS	 rS
rU =r$ )r1   i_  a  MemPool represents a pool of memory in a caching allocator. Currently,
it's just the ID of the pool object maintained in the CUDACachingAllocator.

Args:
    allocator(torch._C._cuda_CUDAAllocator, optional): a
        torch._C._cuda_CUDAAllocator object that can be used to
        define how memory gets allocated in the pool. If :attr:`allocator`
        is ``None`` (default), memory allocation follows the default/
        current configuration of the CUDACachingAllocator.

r-  c                 &   > [         TU ]  US5        g )NTrS  )r1  r-  rU  s     r@   r2  MemPool.__init__l  s    D)r?   rX   c                    > [         TU ]  $ )z3Returns the ID of this pool as a tuple of two ints.)rT  idr1  rU  s    r@   ra  
MemPool.ido  s     wzr?   c                    > [         TU ]  $ )z9Returns the allocator this MemPool routes allocations to.)rT  r-  rb  s    r@   r-  MemPool.allocatort  s     w  r?   c                     > [         TU ]  5       $ )z)Returns the reference count of this pool.)rT  	use_countrb  s    r@   rg  MemPool.use_county  s    w ""r?   c                 h     [        U 5      n[        R                  R                  5       nAU$ ! Af = f)a  Return a snapshot of the CUDA memory allocator pool state across all
devices.

Interpreting the output of this function requires familiarity with the
memory allocator internals.

.. note::
    See :ref:`cuda-memory-management` for more details about GPU memory
    management.
)r2   r<   rH   r*   )r1  ctxr  s      r@   r  MemPool.snapshot}  s2    	 &Czz113H s   ). 1r>   r;   )r6  r7  r8  r9  r:  r   r4   r2  propertytuplerO   ra  r-  rg  r  r;  r[  r\  s   @r@   r1   r1   _  sy    
*(+>"? * * E#s(O   !8$78 ! !#3 # r?   r1   rQ  c              #   d  #    [        U 5      nUc  [        R                  R                  5       O
[	        U5      n[        X0R                  5         Sv   [        X0R                  5        [        X0R                  5        Ag! [        X0R                  5        [        X0R                  5        Af = f7f)a{  A context manager that routes allocations to a given pool.

Args:
    pool(torch.cuda.MemPool): a MemPool object to be made active so that
        allocations route to this pool.
    device (torch.device or int, optional): selected device. Uses MemPool on
        the current device, given by :func:`~torch.cuda.current_device`,
        if :attr:`device` is ``None`` (default).

N)	r2   r<   rH   rI   r   r7   ra  r8   r9   )rQ  rF   rj  device_indexs       r@   r3   r3     s      
C'-~

!!#;LV;T  lGG4,\77C,0 	-\77C,0s   AB0B  ,B0 -B--B0)NN)Tr;   )rX   N)NF)Tr   FNF)r   )zdump_snapshot.pickle)z
output.svgN)ar:  ry   
contextlibrA  r  sysr   inspectr   typingr   r   r   r   typing_extensionsr   r<   r	   torch._utilsr
   torch.typesr   rw   r   r   r   r   r   _memory_vizr   r#  r   r  __all__hasattr__dict__torch._Cr7   r4   r8   r9   r5   r6   rA   contextmanagerrE   rO   r   r   r  r   r   r\   r   r   rj   rJ  r   r   r   r   r    r!   r"   r#   r   r   r$   r%   r&   r'   r   r(   r)   r*   r+   r,   rm  r-   r  r  maxsizer  __signature__r  r  r   r$  r(  r.   r,  r/   r0   rO  r2   r1   r3   r>   r?   r@   <module>r     s   R     
   0 0 (   $   B!H uxx.///:;P/QEHH+, uxx$$$/
$;EHHj!+67H+IEHH'(5@#6EHH12 AL.AEHH<= .99L-MEHH)* .
 & &!K%*< !KH<":D :D : ,07FCK(7	7:4E&#+,> 4% 4 $f+vs{+ f+tCH~ f+R.fck(: .d3PS8n .>5+= > >(7E&#+$6 7$ 7&B+4S> B+J,$sCx. ,<52uVS['9 2T 242E&#+$6 2$ 24MU63;/ M3 M"Jvs{!3 Js J*LE&#+. L# LIfck 2 Ic I* Q*%, * *	*
 Y.eFCK0 .C .	.

7|?5- |?4 |?TW |?~>uVS[1 >S >B6vs{+ 6uS#X 6* $!%
 &#+$ .3*E)**E	*E\ #"{{!%Jc]Jc]J J 	J
 &#+J (11L'M  $J%eFCK( J%Z%#K K	0s 	0 L^ L@A A4 A9 9-_ -&.h .b w fck(:  r?   