
    i?                        d Z 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ZddlZddl	m
Z
 ddlmZmZmZmZmZmZ ddl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mZ dd
lm Z!m"Z# erddl$m%Z%  G d de      Z& G d de      Z' G d de      Z( G d de      Z) G d de      Z*g dZ+ e,ej,                  d      s ed      ej,                  jZ                  d<    e,ej,                  d      s ed      ej,                  jZ                  d<    ed      ej,                  jZ                  d<    ed      ej,                  jZ                  d<    ed      ej,                  jZ                  d<    ed      ej,                  jZ                  d<   ddl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 d Z5ejl                  d        Z7didjd"Z8d# Z9dkd$e:d%dfd&Z;dldmd'Z<dld d!d%e=fd(Z>dnd)Z?dld d!d%e@eAef   fd*ZBdld d!d%e@eAef   fd+ZCdldmd,ZDdldmd-ZEd%e@eAef   fd.ZFd%e@eAef   fd/ZGdnd0ZHdnd1ZIdldmd2ZJdldmd3ZKdld d!d%eLfd4ZMdld d!d%eLfd5ZNdld d!d%eLfd6ZOdld d!d%eLfd7ZP ed8eQ9      dld d!d%eLfd:       ZR ed;eQ9      dld d!d%eLfd<       ZSdld=ZTdod d!d?e:d%eAfd@ZUdld d!d%eAfdAZVdld d!d%eWeLeLf   fdBZX	 	 	 	 	 	 	 	 dpdCe:d d!fdDZY	 dqdCeedF      d%dfdGZZdEdEdEej                  dd>d>d>fdCeeA   dHeeA   dIeAdJeLd d!dKe:dLe:dMe:fdNZ\ e
e\      eZ_]        dOe^e&   d%eLfdPZ_dQeAe*z  d%e*fdRZ`dodjdSZadrdTZbdUeAfdVZcd%eAfdWZddsdXZedsdYZf edZeQ9      d[eAfd\       Zgd%eAfd]Zh G d^ d_      Zi G d` daei      Zjdbeid%dfdcZkd%eifddZl G de dfe4      Zmejl                  dldgemd d!fdh       Zny)tzKThis package adds support for device memory management implemented in CUDA.    N)	signature)AnycastLiteralOptionalTYPE_CHECKING	TypedDict)
deprecatedNotRequired)_C)_dummy_type   )_get_amdsmi_device_index_get_device_index_get_nvml_device_index
_lazy_initis_initialized)memorysegments)Devicec                   p    e Zd ZU dZeed<   eed<   eed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   y	)
_Framez1Frame information from memory profiler snapshots.filenamelinename
fx_node_opfx_node_namefx_node_targetfx_original_traceN)__name__
__module____qualname____doc__str__annotations__intr        K/var/www/html/engine/venv/lib/python3.12/site-packages/torch/cuda/memory.pyr   r   #   s@    ;M
I
IC  c""$$"3''r(   r   c                   J    e Zd ZU dZeed<   eed<   eed<   eed<   ee   ed<   y)_BlockzMemory block information.sizerequested_sizeaddressstateframesN)	r    r!   r"   r#   r&   r%   r$   listr   r'   r(   r)   r+   r+   0   s$    #
ILJLr(   r+   c                   ^    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   eed<   ee   ed<   y	)
_SegmentzMemory segment information.r.   
total_sizestreamsegment_typeallocated_sizeactive_sizeblocksN)	r    r!   r"   r#   r&   r%   r$   r1   r+   r'   r(   r)   r3   r3   :   s0    %LOKLr(   r3   c                   `    e Zd ZU dZeed<   ee   ed<   ee	   ed<   eed<   eed<   ee   ed<   y)	_TraceEntryzMemory trace entry information.actionaddrr0   r,   r5   device_freeN)
r    r!   r"   r#   r$   r%   r   r&   r1   r   r'   r(   r)   r;   r;   F   s4    )K
c
L
IKS!!r(   r;   c                   >    e Zd ZU dZee   ed<   eeee         ed<   y)	_SnapshotzMemory snapshot structure.r   device_tracesN)	r    r!   r"   r#   r1   r3   r%   r   r;   r'   r(   r)   r@   r@   Q   s$    $8ntD$5677r(   r@   )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use_mem_pool_cuda_CUDAAllocator_MemPool_cuda_beginAllocateToPool&_cuda_beginAllocateCurrentThreadToPool_cuda_endAllocateToPool_cuda_releasePool)rd   rc   ra   re   rf   rb   c                  R    t                t        j                  j                         S N)r   torchr   _cuda_cudaHostAllocatorr'   r(   r)   _host_allocatorrk      s    L88++--r(   c               #      K   t         j                  j                          	 d  t         j                  j                          y # t         j                  j                          w xY wwrh   )ri   r   _cuda_lock_mutex_cuda_unlock_mutexr'   r(   r)   _free_mutexro      s>     	HH&##%##%s   A(A A( A%%A(devicer   c                    |t         j                  j                         }t        |      }|t         j                  j	                  |      }t        |t         j                  j                  j                        r|j                  }t        |t              st        d      t         j                  j                  |      5  t         j                  j                  | |      cddd       S # 1 sw Y   yxY w)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)ri   cudacurrent_devicer   current_stream
isinstancestreamsStreamcuda_streamr&   	TypeErrorrp   r   $_cuda_cudaCachingAllocator_raw_alloc)r,   rp   r5   s      r)   rB   rB      s    & ~**,v&F~**62&%**,,334##fc"#
 	

 
		6	" Kxx<<T6JK K Ks    C++C4c                 B    t         j                  j                  |        y)a  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)ri   r   %_cuda_cudaCachingAllocator_raw_delete)mem_ptrs    r)   rC   rC      s     
HH227;r(   valuereturnc                 X    t               r t        j                  j                  |        yy)z;Enable or disable the CUDA memory allocator. On by default.N)r   ri   r   !_cuda_cudaCachingAllocator_enable)r~   s    r)   rD   rD      s    2259 r(   c                    t                |t        j                  j                         }t	        |      }t        | t              st        d      | dk  s| dkD  rt        d|  d      t        j                  j                  | |       y)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   ri   rr   rs   r   ru   floatry   
ValueErrorr   _cuda_setMemoryFraction)fractionrp   s     r)   rF   rF      sw     L~**,v&Fh&MNN!|x!|3H:=QRSS	HH$$Xv6r(   c                     t                | t        j                  j                         } t	        |       } t        j
                  j                  |       S )a  Get 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   ri   rr   rs   r   r   _cuda_getMemoryFractionrp   s    r)   rE   rE      s?     L~**,v&F88++F33r(   c                  V    t               rt        j                  j                          yy)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   ri   r   _cuda_emptyCacher'   r(   r)   rG   rG     s     !!# r(   c                     g fdt        |       } d|       j                          t        j                        S )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 June 2025, for size >= 1MB allocations).
    - ``small_pool``: statistics for the small allocation pool
      (as of June 2025, 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                     t        |t              r8t        |       dkD  r| dz  } |j                         D ]  \  }} | |z   |        y j	                  | |f       y Nr   .ru   dictlenitemsappendprefixobjkv_recurse_add_to_resultresults       r)   r   z,memory_stats.<locals>._recurse_add_to_resultt  Z    c4 6{Q#		 61&vz156 MM63-(r(   r    )rI   sortcollectionsOrderedDict)rp   statsr   r   s     @@r)   rH   rH     s@    n F) (v6E2u%
KKM""6**r(   c                 r    t               si S t        | d      } t        j                  j	                  |       S )zMReturn the result of :func:`~torch.cuda.memory_stats` as a nested dictionary.Toptional)r   r   ri   r   _cuda_memoryStatsr   s    r)   rI   rI     s.    	v5F88%%f--r(   c                 Z    t        | d      } t        j                  j                  |       S )a}  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   ri   r   !_cuda_resetAccumulatedMemoryStatsr   s    r)   rJ   rJ     s%      v5F8855f==r(   c                 Z    t        | d      } t        j                  j                  |       S )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   ri   r   _cuda_resetPeakMemoryStatsr   s    r)   rK   rK     s%     v5F88..v66r(   c                      g fdt               }  d|        j                          t        j                        S )aT  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                     t        |t              r8t        |       dkD  r| dz  } |j                         D ]  \  }} | |z   |        y j	                  | |f       y r   r   r   s       r)   r   z1host_memory_stats.<locals>._recurse_add_to_result  r   r(   r   )rO   r   r   r   )r   r   r   s    @@r)   rN   rN     s>    f F) -.E2u%
KKM""6**r(   c                  V    t               si S t        j                  j                         S )zRReturn the result of :func:`~torch.cuda.host_memory_stats` as a nested dictionary.)r   ri   r   _cuda_hostMemoryStatsr'   r(   r)   rO   rO     s     	88))++r(   c                  >    t         j                  j                         S )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.
    )ri   r   %_cuda_resetAccumulatedHostMemoryStatsr'   r(   r)   rP   rP     s     8899;;r(   c                  >    t         j                  j                         S )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.
    )ri   r   _cuda_resetPeakHostMemoryStatsr'   r(   r)   rQ   rQ     s     882244r(   c                 R    t        j                  dt        d       t        |       S )a  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.   
stacklevelr   warningswarnFutureWarningrK   r   s    r)   rL   rL     (    $ MM	0	 #&11r(   c                 R    t        j                  dt        d       t        |       S )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.r   r   r   r   r   s    r)   rM   rM   ,  r   r(   c                 :    t        |       j                  dd      S )a[  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.
    r   zallocated_bytes.all.currentr   rH   getr   s    r)   rR   rR   G  s     v&**+H!LLr(   c                 :    t        |       j                  dd      S )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.
    r   zallocated_bytes.all.peakr   r   r   s    r)   rS   rS   X  s    $ v&**+EqIIr(   c                 :    t        |       j                  dd      S )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.
    r   zreserved_bytes.all.currentr   r   r   s    r)   rT   rT   m  s     v&**+GKKr(   c                 :    t        |       j                  dd      S )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.
    r   zreserved_bytes.all.peakr   r   r   s    r)   rU   rU   |  s    $ v&**+DaHHr(   zK`torch.cuda.memory_cached` has been renamed to `torch.cuda.memory_reserved`)categoryc                     t        |       S )z4Deprecated; see :func:`~torch.cuda.memory_reserved`.r   )rT   r   s    r)   rV   rV     s     &))r(   zS`torch.cuda.max_memory_cached` has been renamed to `torch.cuda.max_memory_reserved`c                     t        |       S )z8Deprecated; see :func:`~torch.cuda.max_memory_reserved`.r   )rU   r   s    r)   rW   rW     s     f--r(   c                 F    t         j                  j                  |       d   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   )ri   r   _cuda_memorySnapshot)
mempool_ids    r)   rX   rX     s     88((4Z@@r(   Fabbreviatedc                    t        | d      } t        |       }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 }|j                  d       |j                  d       |j                  d       |j                  d       |j                  d       |j                  d       |D ]  \  }}}	|j                  d       d|fg}
|s"|
j                  d       |
j                  d       d \  }}}}|
D ]x  \  }}|d!z   |z   d!z   }||d"z      }||d#z      }||d$z      }||d%z      }||}|}|}|}|j                  d&|d'd( |	||       d( |	||       d( |	||       d( |	||       d&       z  d)d*|fd+d,|fg}|D ]z  \  }}}	|j                  d       |d!z   }||d"z      }||d#z      }||d$z      }||d%z      }|j                  d&|d'd( |	||       d( |	||       d( |	||       d( |	||       d&       | |j                  d       d-| d.}|j                         D ]  \  }}|||j	                  d!d/      <    d0 d1j                  |      j                  d3i |z   d2z   S )4a  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   r   c                 ^    g d}|d   }|dd  D ]  }|dk  r n|}| dz  } |dz  } | dd| S )N)zB  KiBMiBGiBTiBPiBr   r   i   i   6d r'   )szpref_szprefixesr   
new_prefixs        r)   _format_sizez$memory_summary.<locals>._format_size  s\    =!"12, 	J#F4KBtOG	 R&""r(   c                 `    g d}|d   }|dd  D ]  }|dk  r n|}| dz  } |dz  } | dd| dS )N)r   KMr   r   iq i  7dr   r'   )cntpref_cntr   r   r   s        r)   _format_countz%memory_summary.<locals>._format_count  s_    "!"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)NNNNr   currentpeak	allocatedfreedr   z<21z | oversize_allocationszOversize allocationsoversize_segmentszOversize GPU segmentsr   )_rp   -|z|
|z|
r'   )r   rH   r   r   replacejoinformat)rp   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_namer   r   r   r   r   fmt_dictr   r   s                            r)   rY   rY     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 *
K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	D 
 !7G	5}E
 /A 
*
KXc!*+Vf_%&;./	fw&'C Igw$?#@IdTXDYCZZ]I./s9UE3J2K1N	

 
LL6*H *1()3$%**U#**6X66>>r(   c                    t         j                  j                  sJ	 ddl}ddlm} 	 |j                          t        |       } |j                  |       }|j                  |      }nF	 ddl
}	 |j                          t        |       } 	 |j                         |    }|j                  |      }g }|j!                  d	|         t#        |      dk(  r|j!                  d
       |D ]u  }t         j                  j                  s|j$                  dz  }|j&                  }	n#	 j)                  ||      }
|
d   d   dz  }|
d   }	|j!                  d|	dd|dd       w dj-                  |      S # t        $ r Y yw xY w# |$ r Y yw xY w# t        $ r Y yw xY w# |j                  $ r Y yw xY w# |j                  $ r Y yw xY w# t*        $ r |}
Y w xY w)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   Nz4pynvml module not found, please install nvidia-ml-py)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
)ri   versionhippynvmlModuleNotFoundErrorr  nvmlInitr   nvmlDeviceGetHandleByIndex$nvmlDeviceGetComputeRunningProcessesamdsmiamdsmi_initAmdSmiExceptionr   amdsmi_get_processor_handlesamdsmi_get_gpu_process_listr   r   usedGpuMemoryr  amdsmi_get_gpu_process_infoAttributeErrorr   )rp   r  r  handleprocsr  r   pmemr  	proc_infos              r)   rZ   rZ   /  s    ==	J 	5	COO (/226:;;FC	D	G  *&1	C88:6BF66v>E E	LL4x!
5zQ/0 L}}  //[1C%%C">>vqI	
 N+J7;GCE"CxDzF|>JKL 99Uc # 	JI	J ) 	CB	C # 	DC	D %% 	GF	G %% 	CB	C "  	sj   E+ E: &F +F $F) F>+	E76E7:FF	FFF&%F&)F;:F;>GGc                     | t         j                  j                         } t        | d      } t         j                  j	                         j                  |       S )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   )ri   rr   rs   r   cudartcudaMemGetInfor   s    r)   r[   r[   q  sE     ~**,v5F::--f55r(   enabledc	           
      <    t        j                  | |||||||       y rh   )r   "_cuda_record_memory_history_legacy)	r!  record_contexttrace_alloc_max_entriestrace_alloc_record_contextrp   record_context_cppclear_historycompile_contextglobal_record_annotationss	            r)   _record_memory_history_legacyr+    s*     ))"!
r(   r   )r/   r   c                 ^    t        | t              rt        | g|i |S t        | g|i |S )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 to 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.

    Buffer behavior
    ---------------

    This will store up to `max_entries` instances of `TraceEntry` when enabled.
    Python trace collection defaults to `sys.maxsize`, meaning long-running
    or indefinitely running jobs should set a reasonable limit to avoid excessive
    memory use. Expect each entry to be several KB.

    Longer running workflows or those with smaller `max_entries` values will only
    store the last accumulated `max_entries` entries, meaning new entries overwrite
    older entries.

    C++ implementation for reference to ring buffer implementation:

    .. code-block:: cpp

        if (record_history) {
          if (alloc_trace->size() < alloc_trace_max_entries_) {
            alloc_trace->emplace_back(te);
          } else {
            (*alloc_trace)[alloc_trace_next++] = te;
            if (alloc_trace_next == alloc_trace_max_entries_) {
              alloc_trace_next = 0;
            }
          }
        }

    Latency impact
    --------------

    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 currently 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.
    )ru   boolr+  _record_memory_history_impl)r!  argskwargss      r)   _record_memory_historyr1    s9    J '4 ,WFtFvFF*7DTDVDDr(   contextstacksmax_entriesr(  r)  r*  c           	      :    t        j                  | ||||||       y rh   )r   _cuda_record_memory_history)r!  r2  r3  r4  rp   r(  r)  r*  s           r)   r.  r.    s'     ""!r(   r0   c                    ddl m} t        j                  t        j                  |       d      }d}| s|S | D ]  }d|v s	d|v s|d   }|d   }|j                  t        j                  j                  |            sGddl	m
} |j                  |      }|a|j                  di       }	|j                  di       }
|j                  d	d      }|	j                  ||z
        }|||
v s|
|   }|j                  d
      }|j                  d      }|j                  d      }|j                  d      }||d<   ||d<   t        |      |d<   |r||d<   |dz  }" |S )z
    Augment a list of frames with FX debug information.

    Args:
        frames: List of frame dictionaries to augment

    Returns:
        The count of frames that were augmented.
    r   )FX_GRAPH_MODULE_FILE_PREFIXz.*\.py$r   r   )_FX_METADATA_REGISTRY
lineno_mapnode_metadataprologue_startstack_traceopr   targetr   r   r   r   r   )torch.fx.graph_moduler8  recompileescapesearchospathbasenametorch.fx.tracebackr9  r   r$   )r0   r8  _FX_GENERATED_PATTERNcountframer   linenor9  metadatar:  r;  r<  node_idx	node_infooriginal_tracenode_op	node_namenode_targets                     r)   _augment_framesrT    s    B JJII1237; E '6U?Z(H6]F )//0@0@0JK A,00:H!lB7J$LL"=M%\\*:A>N "~~f~&=>H#M(A)(3	!*}!=#---%MM&1	'mmH5 '.l#(1n%*-k*:&' "1?E-.
O'R Lr(   snapshotc                    t        | t              r9t        | d      5 }t        t        t        j                  |            }ddd       n| }d}dv r/|d   D ]'  }d|v s|d   D ]  }d|v s|t        |d         z  } ) d|v r8|d   D ]0  }|D ])  }t        |t              sd|v s|t        |d         z  }+ 2 |S # 1 sw Y   |xY w)a  
    Augment a memory snapshot with original source stack traces from FX metadata.

    IMPORTANT: This function reads from a global in-memory registry (_FX_METADATA_REGISTRY)
    that is populated during graph module compilation. It must be called in the same
    Python process where the FX graphs were compiled. It cannot be used to augment
    snapshots loaded from disk in a different process.

    Args:
        snapshot: Either a memory snapshot dict or path to a snapshot pickle file

    Returns:
        The augmented snapshot dictionary with fx_node_op, fx_node_name,
        fx_original_trace, and fx_node_info fields added to frames
    rbNr   r   r9   r0   rA   )	ru   r$   openr   r@   pickleloadrT  r   )rU  fsnapshot_dictaugmented_countr   block
trace_listtrace_entrys           r)   %_augment_memory_snapshot_stack_tracesra  @  s   ( (C (D! 	<Q FKKN;M	< 	< ! O ]"$Z0 	LG7"$X. LE5('?5?+KKL	L -''8 	NJ) Nk40X5L#{87L'MMON	N
 /	< 	<s   $B??Cc                 J    t        j                  d      }|rt        |      }|S )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
            # Optional FX debug fields (present when augment_with_fx_traces=True
            # and the frame corresponds to FX-generated code)
            fx_node_op: str  # FX node operation type (e.g., 'call_function', 'output')
            fx_node_name: str  # FX node name (e.g., 'linear', 'relu_1')
            fx_original_trace: str  # Original model source code stack trace


        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

    Args:
        device: Device to capture snapshot for. If None, captures for current device.
        augment_with_fx_traces: If True, augment stack trace frames with FX debug information
                                that maps generated FX code back to original model source code.
                                This adds fx_node_op, fx_node_name, fx_original_trace, and
                                fx_node_info fields to Frame objects. Default: False.

    Returns:
        The Snapshot dictionary object
    N)r   r   ra  )rp   augment_with_fx_tracesss      r)   	_snapshotre  p  s'    x 	%A1!4Hr(   c                     t        |      }t        | d      5 }t        j                  ||       ddd       y# 1 sw Y   yxY w)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

    Snapshot file sizes scale with `max_entries` and stack trace depth per entry,
    with several KB per entry. These can easily be in the GB range for longer running
    workflows with large `max_entries`.

    Args:
        filename (str, optional): Name of the file to create. Defaults to "dump_snapshot.pickle".
        augment_with_fx_traces (bool, optional): If True, augment the snapshot with FX debug information
                                                  before dumping. This maps generated FX code stack traces
                                                  back to original model source code. Defaults to False.
        verbose (bool, optional): If True and augment_with_fx_traces is True, print verbose debug output
                                  during augmentation. Defaults to False.
    )rc  wbN)re  rX  rY  dump)r   rc  rd  r[  s       r)   _dump_snapshotri    s>    $ 	)?@A	h	 Aq  s	   9ArM  c                 B    t         j                  j                  |        y)a  
    Set custom metadata that will be attached to all subsequent CUDA memory allocations.

    This metadata will be recorded in the memory snapshot for all allocations made
    after this call until the metadata is cleared or changed.

    Args:
        metadata (str): Custom metadata string to attach to allocations.
                       Pass an empty string to clear the metadata.
    N)ri   r   _cuda_setMemoryMetadata)rM  s    r)   _set_memory_metadatarl    s     
HH$$X.r(   c                  >    t         j                  j                         S )z
    Get the current custom metadata that is being attached to CUDA memory allocations.

    Returns:
        str: The current metadata string, or empty string if no metadata is set.
    )ri   r   _cuda_getMemoryMetadatar'   r(   r)   _get_memory_metadataro    s     88++--r(   c                     |
t               }t        | d      5 }|j                  t        |             d d d        y # 1 sw Y   y xY wNw)re  rX  write	_segmentsr   rU  r[  s      r)   _save_segment_usagerv    sA    ;	h	 %		(#$% % %	   =Ac                     |
t               }t        | d      5 }|j                  t        |             d d d        y # 1 sw Y   y xY wrq  )re  rX  rs  _memoryru  s      r)   _save_memory_usagerz    sA    ;	h	 #	!"# # #rw  zitorch.cuda._set_allocator_settings is deprecated. Use torch._C._accelerator_setAllocatorSettings instead.envc                 @    t         j                  j                  |       S rh   )ri   r   !_accelerator_setAllocatorSettings)r{  s    r)   _set_allocator_settingsr~    s     8855c::r(   c                  >    t         j                  j                         S )ad  Return a string describing the active allocator backend as set by
    ``PYTORCH_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.
    )ri   r   _cuda_getAllocatorBackendr'   r(   r)   r\   r\     s     88--//r(   c                   J    e Zd ZdZdej
                  j                  fdZd Zy)_CUDAAllocatorz-Wrapper over internal CUDA memory allocators.	allocatorc                     || _         y rh   
_allocator)selfr  s     r)   __init__z_CUDAAllocator.__init__*  s	    #r(   c                     | j                   S rh   r  )r  s    r)   r  z_CUDAAllocator.allocator-  s    r(   N)	r    r!   r"   r#   ri   r   ra   r  r  r'   r(   r)   r  r  '  s     8$%((">"> $r(   r  c                   $    e Zd ZdZdededefdZy)r]   z,CUDA memory allocator loaded from a so file.path_to_so_filealloc_fn_namefree_fn_namec                 h   t        j                  |      }t        j                  t        ||      t         j                        j
                  }t        j                  t        ||      t         j                        j
                  }|J |J t        j                  j                  ||      | _	        y)a  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CDLLr   getattrc_void_pr~   ri   r   _cuda_customAllocatorr  )r  r  r  r  r  alloc_fnfree_fns          r)   r  zCUDAPluggableAllocator.__init__4  s    * KK0	;;wy-@&//RXX++gi>PVV###"""((887Kr(   N)r    r!   r"   r#   r$   r  r'   r(   r)   r]   r]   1  s#    7L LC Ls Lr(   r]   r  c                 ^    t         j                  j                  | j                                y)ax  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)ri   r   _cuda_changeCurrentAllocatorr  )r  s    r)   r^   r^   Q  s     
HH)))*=*=*?@r(   c                  P    t        t        j                  j                               S )zReturn the allocator being currently used.

    .. note::
        See :ref:`cuda-memory-management` for details on creating and using a custom allocator
    )r  ri   r   _cuda_getAllocatorr'   r(   r)   _get_current_allocatorr  _  s     %((55788r(   c                        e Zd ZdZ	 	 	 ddee   dedef fdZede	e
e
f   f fd       Zedee   f fd       Zde
f fd	Zd
 Z xZS )r_   aO  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.
        use_on_oom(bool): a bool that indicates if this pool can be used
            as a last resort if a memory allocation outside of the pool fails due
            to Out Of Memory. This is False by default.
        no_split(bool): a bool that indicates if this pool should not split a segment.
            This is False by default.
    r  
use_on_oomno_splitc                 *    t         |   |d||       y )NT)superr  )r  r  r  r  	__class__s       r)   r  zMemPool.__init__y  s     	D*h?r(   r   c                     t         |   S )z3Returns the ID of this pool as a tuple of two ints.)r  idr  r  s    r)   r  z
MemPool.id  s     wzr(   c                     t         |   S )z9Returns the allocator this MemPool routes allocations to.)r  r  r  s    r)   r  zMemPool.allocator  s     w  r(   c                      t         |          S )z)Returns the reference count of this pool.)r  	use_countr  s    r)   r  zMemPool.use_count  s    w ""r(   c                 X    t         j                  j                  | j                        }|S )aM  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.
        )ri   rr   rX   r  )r  rU  s     r)   rU  zMemPool.snapshot  s!     ::--dgg6r(   )NFF)r    r!   r"   r#   r   ra   r-  r  propertytupler&   r  r  r  rU  __classcell__)r  s   @r)   r_   r_   h  s    $ 48 	@/0@ @ 	@ E#s(O   !8$78 ! !#3 #r(   r_   poolc              #   R  K   |t         j                  j                         n
t        |      }t	        || j
                         	 d t        || j
                         t        || j
                         y# t        || j
                         t        || j
                         w xY ww)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).

    .. note::
        This context manager makes only current thread's allocations route to
        the given pool. If a new thread is spawned inside the context manager
        (e.g. by calling backward) the allocations in that thread will not
        route to the given pool.
    N)ri   rr   rs   r   rd   r  re   rf   )r  rp   device_indexs      r)   r`   r`     s|     $ (.~

!!#;LV;T  +<A1dgg6,0 	 dgg6,0s   AB'A6 	-B'6.B$$B')NN)rp   r   )Trh   )rp   r   r   N)r   N)NF)Tr   FNFFFF)r   )zdump_snapshot.pickleF)z
output.svgN)or#   r   
contextlibr  rE  rY  rA  sysr   inspectr   typingr   r   r   r   r   r	   typing_extensionsr
   r   ri   r   torch._utilsr   r   r   r   r   r   r   _memory_vizr   ry  r   rt  torch.typesr   r   r+   r3   r;   r@   __all__hasattr__dict__torch._Crd   rc   ra   re   rf   rb   rk   contextmanagerro   rB   rC   r-  rD   rF   r   rE   rG   r   r$   rH   rI   rJ   rK   rN   rO   rP   rQ   rL   rM   r&   rR   rS   rT   rU   r   rV   rW   rX   rY   rZ   r  r[   r+  r1  maxsizer.  __signature__r1   rT  ra  re  ri  rl  ro  rv  rz  r~  r\   r  r]   r^   r  r_   r`   r'   r(   r)   <module>r     s5   R    	  	 
   I I 5   $  B "
(Y 
(Y 	y 	") "8	 8 F uxx.//:;P/QEHH+, uxx$$/
$;EHHj!5@#6EHH12 CN0CEHH>? 4?!4EHH/0 .99L-MEHH)* .
 & &!KH<":D :D :764H 4 4 $f+ f+T#s(^ f+R. .DcN .>(7&B+4S> B+J,$sCx. ,<52626MX M M"J JS J*LH L LI IC I* Q*( *c *	*
 Y.h .# .	.

A|?8 |? |?# |?~?x ?3 ?D6 6U38_ 6* $#
 2 27HEgn-.HE	HEX #"{{!&+c]c]  	
     $* (11L'M  $>DL >S >B-Io--`_D0/3 /.c .%# o; ;	;
	0s 	0 L^ L@A A4 A9 93h 3l 1w 1 1 1r(   