U
    9%e                     @   s  d dl 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 d dlm	Z	m
Z
mZmZmZ d dlZd dlmZ d dlmZ ddlmZmZmZmZ ddlmZmZ dd	lmZ d
dddddddddddddddddddddd gZeejd!sed!ejj d!< d"d# Z!ej"d$d% Z#d^eee$f d&d'd
Z%d(d Z&d_eee$f dd)d*dZ'dd+d,dZ(d`eee$f e
e)e	f d)d-dZ*daeee$f e
e)e	f d)d.dZ+dbeee$f dd)d/dZ,dceee$f dd)d0dZ-ddeee$f dd)d1dZ.deeee$f dd)d2dZ/dfeee$f e$d)d3dZ0dgeee$f e$d)d4dZ1dheee$f e$d)d5dZ2dieee$f e$d)d6dZ3djeee$f e$d)d7dZ4dkeee$f e$d)d8dZ5d9d Z6dleee$f e7e)d;d<dZ8dmeee$f e)d)d=dZ9dneee$f ee$e$f d)d>dZ:doe7eee$f d@dAdBZ;dpdDdEZ<dCdCdCej=dfee) ee) e)e$eee$f dFdGdHZ>ee>e<_?dqeee$f d&dIdJZ@drdLdMZAdsdOdPZBdtdQdRZCe)dSdTdUZDe)d+dVdZEG dWdX dXZFG dYd deFZGeFddZd[d ZHeFd+d\d]ZIdS )u    N)	signature)AnyDictOptionalTupleUnion)_C)Device   )_get_device_index_get_nvml_device_index
_lazy_initis_initialized)memorysegments)_dummy_typecaching_allocator_alloccaching_allocator_delete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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_cuda_CUDAAllocatorc                   C   s   t   tj S N)r   torchr   Z_cuda_cudaHostAllocator r,   r,   P/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/cuda/memory.py_host_allocator4   s    r.   c                   c   s&   t j  z
d V  W 5 t j  X d S r*   )r+   r   Z_cuda_lock_mutexZ_cuda_unlock_mutexr,   r,   r,   r-   _free_mutex9   s    

r/   devicec              
   C   s   |dkrt j }t|}|dkr.t j|}t|t jjjrD|j}t|t	sVt
dt j| t j| |W  5 Q R  S Q R X 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`.

    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   Zcurrent_stream
isinstancestreamsZStreamZcuda_streamint	TypeErrorr1   r   Z$_cuda_cudaCachingAllocator_raw_alloc)sizer1   streamr,   r,   r-   r   B   s    

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.

    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   Z%_cuda_cudaCachingAllocator_raw_delete)Zmem_ptrr,   r,   r-   r   f   s    )r1   returnc                 C   sd   t   |dkrtj }t|}t| ts2td| dk sB| dkrRtd|  dtj	
| | dS )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+   r2   r3   r   r4   floatr7   
ValueErrorr   Z_cuda_setMemoryFraction)fractionr1   r,   r,   r-   r   w   s    

)r:   c                   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-   r      s    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.

    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                    sR   t |tr@t| dkr| d7 } | D ]\}} | | | q&n| |f d S )Nr   .)r4   dictlenitemsappend)prefixobjkv_recurse_add_to_resultresultr,   r-   rH      s    
z,memory_stats.<locals>._recurse_add_to_resultr0    )r   sortcollectionsOrderedDict)r1   statsr,   rG   r-   r      s    S	

c                 C   s"   t  s
i 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+   r   Z_cuda_memoryStatsr0   r,   r,   r-   r     s    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"`.

    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.
    TrO   )r   r+   r   Z!_cuda_resetAccumulatedMemoryStatsr0   r,   r,   r-   r     s    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.

    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.
    TrO   )r   r+   r   Z_cuda_resetPeakMemoryStatsr0   r,   r,   r-   r   #  s    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.

    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.r0   warningswarnFutureWarningr   r0   r,   r,   r-   r   6  s
    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.

    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.r0   rQ   r0   r,   r,   r-   r   Q  s
    c                 C   s   t | dddS )a`  Returns 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.
    r0   zallocated_bytes.all.currentr   r   getr0   r,   r,   r-   r   l  s    c                 C   s   t | d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_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.
    r0   zallocated_bytes.all.peakr   rU   r0   r,   r,   r-   r   ~  s    c                 C   s   t | dddS )a  Returns 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.
    r0   zreserved_bytes.all.currentr   rU   r0   r,   r,   r-   r     s    c                 C   s   t | d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_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.
    r0   zreserved_bytes.all.peakr   rU   r0   r,   r,   r-   r     s    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_reservedr0   )rR   rS   rT   r   r0   r,   r,   r-   r      s
    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_reservedr0   )rR   rS   rT   r   r0   r,   r,   r-   r!     s
    c                   C   s   t j d 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+   r   _cuda_memorySnapshotr,   r,   r,   r-   r"     s    
F)r1   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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(kr^|}|}|}|}|d)||	|||	|||	|||	|| qqd*d+|fd,d-|fg}|D ]~\}}}	|d |d# }||d$  }||d%  }||d&  }||d'  }|d)||	|||	|||	|||	|| q|d d.| d/}| D ]\}}|||d#d0< qFd1d2|jf | d3 S )4a  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.

    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.
    TrO   r0   c                 S   sZ   ddddddg}|d }|dd  D ]$}|d	k r4 qJ|}| d
 } |d
 }q$| dd| S )NzB  KiBMiBGiBTiBPiBr   r
   i   i   Z6d r,   )szZpref_szprefixesrC   
new_prefixr,   r,   r-   _format_size  s    
z$memory_summary.<locals>._format_sizec                 S   sV   dddg}|d }|dd  D ]$}|dk r. qD|}| d } |d }q| dd| dS )	Nr^   KMr   r
   iq i  Z7dr,   )ZcntZpref_cntr`   rC   ra   r,   r,   r-   _format_count  s    

z%memory_summary.<locals>._format_countZallocated_byteszAllocated memoryZactive_byteszActive memoryZrequested_byteszRequested 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} | {} | {} | {} | {} Zoversize_allocationszOversize allocationsZoversize_segmentszOversize GPU segmentsrJ   )_r1   -|z|
|z|
)r   r   rB   formatrA   replacejoin)r1   rX   rN   rb   re   Zmetrics_to_displaylinesZ
metric_keyZmetric_name	formatterZ
submetricsZcurrent_prefvalZpeak_prefvalZallocated_prefvalZfreed_prefvalZsubmetric_keyZsubmetric_namerC   ri   rj   rk   rl   Zfmt_dictrE   rF   r,   r,   r-   r#     s    













c                 C   s   zddl }W n tk
r"   Y dS X ddl m} z|  W n |k
rR   Y dS X t| } || }||}g }|d|   t|dkr|d |D ],}|j	d }|d	|j
d
d|dd qd|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.

    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GPU:zno processes are runningi   zprocess z>10dz uses z>12.3fz MB GPU memory
)pynvmlModuleNotFoundErrorru   ZnvmlInitr   ZnvmlDeviceGetHandleByIndexZ$nvmlDeviceGetComputeRunningProcessesrB   r@   ZusedGpuMemorypidrr   )r1   rw   ru   handleZprocsrs   pZmemr,   r,   r-   r$   c  s(    



 c                 C   s*   | dkrt j } t| } t j | S )a  Returns the global free and total GPU memory for a given
    device using cudaMemGetInfo.

    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.
    N)r+   r2   r3   r   ZcudartZcudaMemGetInfor0   r,   r,   r-   r%     s    
T)enabledr1   c                 C   s   t | |||| d S r*   )r   Z"_cuda_record_memory_history_legacy)r|   Zrecord_contextZtrace_alloc_max_entriesZtrace_alloc_record_contextr1   Zrecord_context_cppr,   r,   r-   _record_memory_history_legacy  s    r}   rh   c                 O   s.   t | trt| f||S t| f||S dS )a  
    Enables 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.
    N)r4   boolr}   _record_memory_history_impl)r|   argskwargsr,   r,   r-   _record_memory_history  s    '
r   r|   contextstacksZmax_entriesr1   c                 C   s   t | ||| d S r*   )r   Z_cuda_record_memory_historyr   r,   r,   r-   r     s    r   c                 C   s   t  S )a  Saves 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   rW   r0   r,   r,   r-   	_snapshot  s    Ir   dump_snapshot.picklec              	   C   s,   t  }t| d}t|| W 5 Q R X dS )a  
    Saves 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fr,   r,   r-   _dump_snapshot1  s    r   
output.svgc              	   C   s6   |d krt  }t| d}|t| W 5 Q R X d S Nw)r   r   write	_segmentsr   Zsnapshotr   r,   r,   r-   _save_segment_usage>  s    r   c              	   C   s6   |d krt  }t| d}|t| W 5 Q R X d S r   )r   r   r   _memoryr   r,   r,   r-   _save_memory_usageE  s    r   envc                 C   s   t j| S r*   )r+   r   Z1_cuda_cudaCachingAllocator_set_allocator_settingsr   r,   r,   r-   _set_allocator_settingsL  s    r   c                   C   s
   t j S )aj  Returns 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   Z_cuda_getAllocatorBackendr,   r,   r,   r-   r&   P  s    	c                   @   s*   e Zd ZdZejjdddZdd ZdS )_CUDAAllocatorz-Wrapper over internal CUDA memory allocators.	allocatorc                 C   s
   || _ d S r*   
_allocator)selfr   r,   r,   r-   __init___  s    z_CUDAAllocator.__init__c                 C   s   | j S r*   r   )r   r,   r,   r-   r   b  s    z_CUDAAllocator.allocatorN)	__name__
__module____qualname____doc__r+   r   r)   r   r   r,   r,   r,   r-   r   \  s   r   c                   @   s"   e Zd ZdZeeedddZdS )r'   a  CUDA memory allocator loaded from a so file.

    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
    )path_to_so_filealloc_fn_namefree_fn_namec                 C   sb   t |}t t||t jj}t t||t jj}|d k	sBt|d k	sNttj	||| _
d S r*   )ctypesCDLLcastgetattrZc_void_pvalueAssertionErrorr+   r   Z_cuda_customAllocatorr   )r   r   r   r   r   Zalloc_fnZfree_fnr,   r,   r-   r   ~  s    
zCUDAPluggableAllocator.__init__N)r   r   r   r   strr   r,   r,   r,   r-   r'   f  s   )r   r:   c                 C   s   t j|   dS )ax  Changes 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   Z_cuda_changeCurrentAllocatorr   r   r,   r,   r-   r(     s    
c                   C   s   t tj S )zReturns the allocator being currently used.

    .. note::
        See :ref:`cuda-memory-management` for details on creating and using a custom allocator
    )r   r+   r   Z_cuda_getAllocatorr,   r,   r,   r-   _get_current_allocator  s    r   )NN)N)N)N)N)N)N)N)N)N)N)N)N)N)NF)N)N)Tr
   FNF)rh   )N)r   )r   N)r   N)JrL   
contextlibr   r   sysrR   inspectr   typingr   r   r   r   r   r+   r   Ztorch.typesr	   rJ   r   r   r   r   Z_memory_vizr   r   r   r   _utilsr   __all__hasattr__dict__r.   contextmanagerr/   r6   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r~   r#   r$   r%   r}   r   maxsizer   __signature__r   r   r   r   r   r&   r   r'   r(   r   r,   r,   r,   r-   <module>   s   
$ 
"e"		 $"     

.


L



!