a
    ÞñhRK  ã                   @   s"  d dl Z d dlZd dlZd dlmZmZmZ d dlZddlm	Z	m
Z
mZ d dlmZ dd„ Zejdd	„ ƒZd3eeef d
œdd„Zdd„ Zddœdd„Zd4eeef eeef dœdd„Zd5eeef eeef dœdd„Zd6eeef ddœdd„Zd7eeef ddœdd„Zd8eeef ddœdd„Zd9eeef ddœdd„Zd:eeef edœdd „Zd;eeef edœd!d"„Zd<eeef edœd#d$„Zd=eeef edœd%d&„Zd>eeef edœd'd(„Z d?eeef edœd)d*„Z!d+d,„ Z"d@eeef e#ed.œd/d0„Z$dAeeef edœd1d2„Z%dS )Bé    N)ÚAnyÚDictÚUnioné   )Úis_initializedÚ_get_device_indexÚ
_lazy_init)ÚDevicec                   C   s   t ƒ  tj ¡ S ©N)r   ÚtorchÚ_CZ_cuda_cudaHostAllocator© r   r   úQ/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/cuda/memory.pyÚ_host_allocator
   s    r   c                   c   s0   t j ¡  zd V  W t j ¡  nt j ¡  0 d S r
   )r   r   Z_cuda_lock_mutexZ_cuda_unlock_mutexr   r   r   r   Ú_free_mutex   s    
r   ©Údevicec                 C   s”   |du rt j ¡ }t|ƒ}|du r.t j |¡}t|t jjjƒrD|j}t|t	ƒsVt
dƒ‚t j |¡� t j | |¡W  d  ƒ S 1 s†0    Y  dS )aú  Performs 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`.

    Arguments:
        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.
    NzsInvalid type for stream argument, must be `torch.cuda.Stream` or `int` representing a pointer to a exisiting stream)r   ZcudaZcurrent_devicer   Zcurrent_streamÚ
isinstanceZstreamsZStreamZcuda_streamÚintÚ	TypeErrorr   r   Z$_cuda_cudaCachingAllocator_raw_alloc)Úsizer   Ústreamr   r   r   Úcaching_allocator_alloc   s    

r   c                 C   s   t j | ¡ dS )a£  Deletes 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.

    Arguments:
        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   Z%_cuda_cudaCachingAllocator_raw_delete)Zmem_ptrr   r   r   Úcaching_allocator_delete:   s    r   )Úreturnc                   C   s   t ƒ rtj ¡  dS )aÔ  Releases 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   Z_cuda_emptyCacher   r   r   r   Úempty_cacheK   s    r   )r   r   c                    s8   g ‰‡ ‡fdd„‰ t | d�}ˆ d|ƒ ˆ ¡  t ˆ¡S )aÆ	  Returns 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.

    Arguments:
        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.
    c                    sR   t |tƒr@t| ƒdkr| d7 } | ¡ D ]\}}ˆ | | |ƒ q&nˆ | |f¡ d S )Nr   Ú.)r   ÚdictÚlenÚitemsÚappend)ÚprefixÚobjÚkÚv©Ú_recurse_add_to_resultÚresultr   r   r&   —   s    
z,memory_stats.<locals>._recurse_add_to_resultr   Ú )Úmemory_stats_as_nested_dictÚsortÚcollectionsÚOrderedDict)r   Ústatsr   r%   r   Úmemory_statsZ   s    ;	

r.   c                 C   s   t | dd�} tj | ¡S )zNReturns the result of :func:`~torch.cuda.memory_stats` as a nested dictionary.T©Úoptional)r   r   r   Z_cuda_memoryStatsr   r   r   r   r)   §   s    r)   c                 C   s   t | dd�} tj | ¡S )aƒ  Resets 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"`.

    Arguments:
        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   Z!_cuda_resetAccumulatedMemoryStatsr   r   r   r   Úreset_accumulated_memory_stats­   s    r1   c                 C   s   t | dd�} tj | ¡S )a  Resets 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.

    Arguments:
        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   Z_cuda_resetPeakMemoryStatsr   r   r   r   Úreset_peak_memory_statsÁ   s    r2   c                 C   s   t  dt¡ t| d�S )a�  Resets the starting point in tracking maximum GPU memory occupied by
    tensors for a given device.

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

    Arguments:
        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.r   ©ÚwarningsÚwarnÚFutureWarningr2   r   r   r   r   Úreset_max_memory_allocatedÔ   s
    ýr7   c                 C   s   t  dt¡ t| d�S )a—  Resets 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.

    Arguments:
        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.r   r3   r   r   r   r   Úreset_max_memory_cachedî   s
    ýr8   c                 C   s   t | d�d S )ae  Returns the current GPU memory occupied by tensors in bytes for a given
    device.

    Arguments:
        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.
    r   zallocated_bytes.all.current©r.   r   r   r   r   Úmemory_allocated  s    r:   c                 C   s   t | d�d S )aö  Returns 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_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.

    Arguments:
        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.
    r   zallocated_bytes.all.peakr9   r   r   r   r   Úmax_memory_allocated  s    r;   c                 C   s   t | d�d S )a½  Returns the current GPU memory managed by the caching allocator in bytes
    for a given device.

    Arguments:
        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.
    r   zreserved_bytes.all.currentr9   r   r   r   r   Úmemory_reserved0  s    r<   c                 C   s   t | d�d S )aþ  Returns 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_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.

    Arguments:
        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.
    r   zreserved_bytes.all.peakr9   r   r   r   r   Úmax_memory_reserved@  s    r=   c                 C   s   t  dt¡ t| d�S )z4Deprecated; see :func:`~torch.cuda.memory_reserved`.zGtorch.cuda.memory_cached has been renamed to torch.cuda.memory_reservedr   )r4   r5   r6   r<   r   r   r   r   Úmemory_cachedV  s
    þr>   c                 C   s   t  dt¡ t| d�S )z8Deprecated; see :func:`~torch.cuda.max_memory_reserved`.zOtorch.cuda.max_memory_cached has been renamed to torch.cuda.max_memory_reservedr   )r4   r5   r6   r=   r   r   r   r   Úmax_memory_cached^  s
    þr?   c                   C   s
   t j ¡ S )a)  Returns 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   Z_cuda_memorySnapshotr   r   r   r   Úmemory_snapshotf  s    
r@   F)r   Úabbreviatedr   c                 C   sà  t | dd�} t| d�}dd„ }dd„ }dd	|fd
d|fdd|fdd|fdd|fdd|fdd|fdd|fg}g }| d¡ | d¡ | d¡ | d¡ | d¡ | d¡ |D ]Ú\}}}	| d¡ d|fg}
|sä|
 d¡ |
 d¡ d \}}}}|
D ]’\}}|d! | d! }||d"  }||d#  }||d$  }||d%  }|d&u �rV|}|}|}|}| d' ||	||ƒ|	||ƒ|	||ƒ|	||ƒ¡¡ qôq®| d¡ d(| d)œ}| ¡ D ]\}}||| d!d*¡< �q¦d+d, |¡jf i |¤Ž d- S ).a�  Returns 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.

    Arguments:
        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/   r   c                 S   sN   g d¢}|d }|dd … D ]$}|dk r, qB|}| d } |d }qd  | |¡S )N)zB ZKBZMBZGBZTBZPBr   r   i   i   z{:7d} {}©Úformat)ÚszZpref_szÚprefixesr!   Ú
new_prefixr   r   r   Ú_format_sizeˆ  s    
z$memory_summary.<locals>._format_sizec                 S   sN   g d¢}|d }|dd … D ]$}|dk r, qB|}| d } |d }qd  | |¡S )N)ú ÚKÚMr   r   i°q iè  z	{:7d} {} rB   )ZcntZpref_cntrE   r!   rF   r   r   r   Ú_format_count“  s    
z%memory_summary.<locals>._format_countZallocated_byteszAllocated memoryZactive_byteszActive memoryZreserved_byteszGPU reserved memoryZinactive_split_byteszNon-releasable memoryZ
allocationZAllocationsÚactivezActive allocsÚsegmentzGPU reserved segmentsZ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)Z
large_poolz      from large pool)Z
small_poolz      from small pool)NNNNr   ÚcurrentÚpeakÚ	allocatedÚfreedNz {:<21} | {} | {} | {} | {} r(   )Ú_r   ú-ú|z|
|z|
)r   r.   r    rC   r   ÚreplaceÚjoin)r   rA   r-   rG   rK   Zmetrics_to_displayÚlinesZ
metric_keyZmetric_nameÚ	formatterZ
submetricsZcurrent_prefvalZpeak_prefvalZallocated_prefvalZfreed_prefvalZsubmetric_keyZsubmetric_namer!   rO   rP   rQ   rR   Zfmt_dictr#   r$   r   r   r   Úmemory_summarys  sd    
ø










û


rZ   c                 C   sÖ   zddl }W n ty    Y dS 0 ddl m} z| ¡  W n |yN   Y dS 0 t| dd�} | | ¡}| |¡}g }| d| › �¡ t|ƒdkrš| d	¡ |D ],}|j	d
 }| d|j
d›d|d›d�¡ qžd |¡S )aÈ  Returns 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.

    Arguments:
        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?Tr/   zGPU:zno processes are runningi   zprocess z>10dz uses z>12.3fz MB GPU memoryÚ
)ÚpynvmlÚModuleNotFoundErrorr[   ZnvmlInitr   ZnvmlDeviceGetHandleByIndexZ$nvmlDeviceGetComputeRunningProcessesr    r   ZusedGpuMemoryÚpidrW   )r   r]   r[   ÚhandleZprocsrX   ÚpZmemr   r   r   Úlist_gpu_processesØ  s(    



 rb   )NN)N)N)N)N)N)N)N)N)N)N)N)N)NF)N)&r+   Ú
contextlibr4   Útypingr   r   r   r   r(   r   r   r   Ztorch.typesr	   r   Úcontextmanagerr   r   r   r   r   Ústrr.   r)   r1   r2   r7   r8   r:   r;   r<   r=   r>   r?   r@   ÚboolrZ   rb   r   r   r   r   Ú<module>   s6   
""M"e