Ë
    g^(hU§  ã            
       ón  — 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 d dlm	Z	m
Z
 d dlmZmZ d dlmZmZmZmZmZ d dlmZ d dlZd dlZd dlmZmZ d d	lmZ d d
lmZ d dlmZ d dl m!Z! d dl"m#Z#m$Z$ d dl%m&Z& d dl'm(Z(m)Z) d dl*m+Z+m,Z, erd dl-m.Z.  e/ej`                  jc                  dd «      «      d k(  rdndZ2dZ3dgZ4 G d„ de5e
«      Z6 G d„ de5e
«      Z7 G d„ de6«      Z8 G d„ de7«      Z9 G d„ d «      Z: G d!„ d"«      Z;d#e5d$e/fd%„Z<d&e/d'e/d(e/d$ee=e/f   fd)„Z>d*e?ej€                  e?e5e/f   f   d#e5d$dfd+„ZAd*e?ej€                  e?e5e/f   f   d#e5d$dfd,„ZBd-e?e7eCe?ej€                  e?e5e/f   f      f   d#e5d$dfd.„ZDd-e?e7eCe?ej€                  e?e5e/f   f      f   d#e5d$dfd/„ZE G d0„ d1e
«      ZF G d2„ de&«      ZGy)3é    N)Únullcontext)Údeepcopy)ÚautoÚEnum)ÚpartialÚwraps)ÚAnyÚCallableÚOptionalÚTYPE_CHECKINGÚUnion)ÚSelf)ÚnnÚoptim)Úactive_fake_mode)Úget_untyped_storages)Ú
ModTracker)ÚDTensor)Ú!register_optimizer_step_post_hookÚ register_optimizer_step_pre_hook)ÚTorchDispatchMode)Útree_flattenÚtree_map_only)ÚWeakIdKeyDictionaryÚweakref)ÚRemovableHandleÚPYTORCH_NO_CUDA_MEMORY_CACHINGi   é   ÚTotalÚ
MemTrackerc                   ó   — e Zd ZdZy)Ú_RefTypeziBase Class for defining memory reference types, categorizing tensors based on their usage within a model.N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© ó    úb/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/distributed/_tools/mem_tracker.pyr"   r"   )   s   „ Úsr)   r"   c                   ó   — e Zd ZdZy)Ú_Statez;Base Class for defining module state to capture snapshots .Nr#   r(   r)   r*   r,   r,   -   s   „ ÚEr)   r,   c                   ó,   — e Zd ZdZdZdZdZdZdZdZ	dZ
y	)
Ú_MemRefTypea‚  
    An enum to define memory reference types, categorizing tensors based on their usage within a model.

        - PARAM: Tensors registered as nn.Parameter within modules.
        - BUFFER: Tensors registered as nn.Buffer within modules.
        - GRAD: Gradients associated with parameters.
        - ACT: Tensors produced during the forward pass and recomputation in activation checkpointing.
        - TMP: Temporary memory used during the backward pass, including gradients of activations.
        - OPT: Tensors holding optimizer states.
        - OTH: Tensors registered via `track_external` that do not fit the above categories.
    Ú	ParameterÚBufferÚGradientÚ
ActivationÚTempÚOptstateÚOtherN)r$   r%   r&   r'   ÚPARAMÚBUFFERÚGRADÚACTÚTEMPÚOPTÚOTHr(   r)   r*   r.   r.   1   s,   „ ñ
ð €EØ€FØ€DØ
€CØ€DØ
€CØ
�Cr)   r.   c                   ó0   — e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zy
)Ú	_ModStatea¶  
    An enum to define the state of a module.

        - PRE_FW: The module is about to run the forward pass.
        - POST_FW: The module has finished running the forward pass.
        - PEAK_FW: The module has reached the peak memory usage during the forward pass.
        - PRE_BW: The module is about to run the backward pass.
        - PRE_FW_AC: The module is about to run the forward pass with activation checkpointing.
        - POST_FW_AC: The module has finished running the forward pass with activation checkpointing.
        - POST_BW: The module has finished running the backward pass.
        - PEAK_BW: The module has reached the peak memory usage during the backward pass.
    zPre-ForwardzPost-ForwardzPeak-ForwardzPre-BackwardzPre-Forward-ACzPost-Forward-ACzPost-BackwardzPeak-BackwardN)r$   r%   r&   r'   ÚPRE_FWÚPOST_FWÚPEAK_FWÚPRE_BWÚ	PRE_FW_ACÚ
POST_FW_ACÚPOST_BWÚPEAK_BWr(   r)   r*   r>   r>   G   s1   „ ñð €FØ€GØ€GØ€FØ €IØ"€JØ€GØ�Gr)   r>   c                   ó   — e Zd ZdZdefd„Zy)Ú_ModMemStatsaÐ  
    A class to store the memory statistics of a module.

    Args:
        mod_fqn (str): The fully qualified name of the module.
    Attributes:
        mod_fqn (str): The fully qualified name of the module.
        parameter_mem (int): The memory usage of the parameters of the module.
        buffer_mem (int): The memory usage of the buffers of the module.
        input_mem (int): The memory usage of the inputs to the module.
        output_mem (int): The memory usage of the outputs from the module.
        snapshots (Dict[_ModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots
        of the module at different states defined by ``_ModState``.
    Note:
        The memory snapshot is stored as a dictionary - Dict[torch.device, Dict[str, int]], where each key is a device,
         and each value is another dictionary with keys as memory reference types defined by `_MemRefType` and
         values as the memory consumed in bytes.
    Úmod_fqnc                 ó>   — || _         |  |  |  |  i | _        i | _        y ©N)rI   Ú
local_peakÚ	snapshots)ÚselfrI   s     r*   Ú__init__z_ModMemStats.__init__s   s#   € ØˆŒÙÙÙÙØ35ˆŒØTVˆ�r)   N)r$   r%   r&   r'   ÚstrrO   r(   r)   r*   rH   rH   _   s   „ ñð&W ô Wr)   rH   c                   ó  — e Zd ZdZdededej                  deddf
d„Zdefd	„Z	d
ej                  defd„Ze	 dd
ej                  dej                  dedeeeej"                  gef      deeej"                  f   f
d„«       Zy)Ú_WeakRefInfozN
    Manages memory statistics and device attributes for tensor storages.
    ÚsizeÚelement_sizeÚdeviceÚreftypeÚreturnNc                 óf   — || _         || _        || _        || _        | j	                  «       | _        y)a�  
        Initializes the ``_WeakRefInfo`` object with tensor storage properties.

        Args:
            size (int): The number of elements in the tensor storage.
            element_size (int): The size of each element in the tensor storage.
            device (torch.device): The device on which the tensor is allocated.
            reftype (_RefType): The reference type of the tensor.
        N)rS   rT   rV   rU   Ú_calculate_mem_consumedÚmem_consumed)rN   rS   rT   rU   rV   s        r*   rO   z_WeakRefInfo.__init__‚   s2   € ð ˆŒ	Ø(ˆÔØˆŒØˆŒØ ×8Ñ8Ó:ˆÕr)   c                 ó°   — | j                   | j                  z  }| j                  j                  dk(  r#t	        j
                  |t        z  «      t        z  S |S )z¶
        Calculates the memory consumed by the tensor storage, considering device-specific allocation rules.

        Returns:
            int: The memory consumed in bytes.
        Úcuda)rS   rT   rU   ÚtypeÚmathÚceilÚ_PYTORCH_MIN_ALLOCATE)rN   Úmems     r*   rY   z$_WeakRefInfo._calculate_mem_consumed”   sJ   € ð �i‰i˜$×+Ñ+Ñ+ˆØ�;‰;×Ñ˜vÒ%Ü—9‘9˜cÔ%:Ñ:Ó;Ô>SÑSÐSØˆ
r)   Ústc                 ó¨   — |j                  «       | j                   k7  r*|j                  «       | _         | j                  «       | _        | j                  S )a  
        Updates and returns the memory consumed if the storage size has changed.

        Args:
            st (torch.UntypedStorage): The tensor storage to check for size updates.

        Returns:
            int: The updated memory consumed in bytes.
        )rS   rY   rZ   )rN   rb   s     r*   Úupdate_mem_consumedz _WeakRefInfo.update_mem_consumed    s@   € ð �7‰7‹9˜Ÿ	™	Ò!ØŸ™›	ˆDŒIØ $× <Ñ <Ó >ˆDÔØ× Ñ Ð r)   Úcallbackc                 ó    —  | |j                  «       |j                  «       ||«      }t        j                  ||rt	        ||«      nd«      }||fS )a  
        Creates a new ``_WeakRefInfo`` instance and a weak reference to a ``torch.UntypedStorage`` object,
        optionally attaching a callback to the weak reference.

        Args:
            st (torch.UntypedStorage): The storage object for which to create the weak reference info.
            device (torch.device): The device associated with the storage object.
            reftype (_RefType): The type of reference, used to categorize the storage.
            callback (Optional[Callable[[Self, weakref.ref]]]): A callback function that is called when
                the storage object is about to be finalized (garbage collected). The callback function
                should accept two arguments: the ``_WeakRefInfo`` instance and the weak reference to the storage.
        Returns:
            Tuple[Self, weakref.ref]: A tuple containing the newly created ``_WeakRefInfo`` instance and the
            weak reference to the storage object. The weak reference may have an attached callback if provided.
        N)rS   rT   r   Úrefr   )Úclsrb   rU   rV   re   ÚwinfoÚw_sts          r*   Úcreate_winfoz_WeakRefInfo.create_winfo¯   sF   € ñ0 �B—G‘G“I˜rŸ™Ó0°&¸'ÓBˆÜ�{‰{˜2¹8œw x°Ô7ÈÓNˆØ�dˆ{Ðr)   rK   )r$   r%   r&   r'   ÚintÚtorchrU   r"   rO   rY   ÚUntypedStoragerd   Úclassmethodr   r
   r   r   rg   r	   Útuplerk   r(   r)   r*   rR   rR   }   sØ   „ ñð;Øð;Ø'*ð;Ø49·L±Lð;ØKSð;à	ó;ð$
¨ó 
ð! e×&:Ñ&:ð !¸só !ð ð BFñà× Ñ ðð —‘ðð ð	ð
 ˜8 T¨7¯;©;Ð$7¸Ð$<Ñ=Ñ>ðð 
ˆt�W—[‘[Ð Ñ	!òó ñr)   rR   ÚunitsrW   c           	      ó~   — dddddœ}| |v r||    S t        d| › ddj                  |j                  «       «      › �«      ‚)	Nr   i   i   i   @)ÚBÚKiBÚMiBÚGiBzUnsupported unit: z. Supported units are: z, )Ú
ValueErrorÚjoinÚkeys)rq   Ú	unit_dicts     r*   Ú_get_mem_divisorr{   Ì   sR   € Ø ¨e¸EÑB€IØ�	ÑØ˜ÑÐäØ   Ð'>¸t¿y¹yÈÏÉÓIYÓ?ZÐ>[Ð\ó
ð 	
r)   ÚvalueÚdivisorÚ	precisionc                 ó.   — |dk(  r| S t        | |z  |«      S )Nr   )Úround)r|   r}   r~   s      r*   Ú_rounding_fnr�   Ö   s   € Ø˜q’Lˆ5ÐG¤e¨E°G©O¸YÓ&GÐGr)   Úsnapshotc                 ó  ‡‡— t        | «      dk(  rt        d«       y t        ‰«      Š| j                  «       D ]G  \  }}t	        |t
           ‰d«      dk  rŒt        d|› �gˆˆfd„|j                  «       D «       ¢­ddiŽ ŒI y )Nr   úNo memory tracked.é   zDevice: c           	   3   ó°   •K  — | ]M  \  }}t        |t        «      r d |j                  › dt        |‰d«      › d‰› �nd |› dt        |‰d«      › d‰› �–— ŒO y­w)ú	z: r…   ú N)Ú
isinstancer"   r|   r�   )Ú.0ÚkÚvr}   rq   s      €€r*   ú	<genexpr>z"_print_snapshot.<locals>.<genexpr>ä   sr   øè ø€ ò ñ �A�qô ˜a¤Ô*ð �Q—W‘W�I˜R¤¨Q°¸Ó ;Ð<¸A¸e¸WÑEà˜!˜˜Bœ|¨A¨w¸Ó:Ð;¸1¸U¸GÐDóEñùs   ƒAAÚsepú
)ÚlenÚprintr{   Úitemsr�   Ú
_TOTAL_KEY)r‚   rq   ÚdevÚdev_snapr}   s    `  @r*   Ú_print_snapshotr–   Ú   s�   ù€ Ü
ˆ8ƒ}˜ÒÜÐ"Ô#ØÜ˜uÓ%€GØ!Ÿ™Ó)ò 
‰ˆˆXÜ˜¤Ñ,¨g°qÓ9¸QÒ>ØÜØ�s�eÐð		
ôð %ŸN™NÓ,ô	ò		
ð ó		
ñ
r)   c                 ó’  ‡‡— t        | «      dk(  rt        d«       y 	 ddlm} t	        ‰«      Šg }t        t        t        | j                  «       «      «      j                  «       «      }dg|D �cg c]"  }t        |t        «      r|j                  › n|› ‘Œ$ c}z   }| j                  «       D ]c  \  }}	t        |	t           ‰d«      dk  rŒt!        |«      g}
|
j#                  ˆˆfd„|	j                  «       D «       «       |j%                  |
«       Œe t         |||d¬	«      «       y # t        $ r}t        d«      |‚d }~ww xY wc c}w )
Nr   r„   ©Útabulateú3Please install tabulate to use the tabulate option.ÚDevicer…   c              3   óB   •K  — | ]  }t        |‰d «      › d‰› �–— Œ y­w)r…   rˆ   N)r�   )rŠ   rŒ   r}   rq   s     €€r*   r�   z*_print_snapshot_tabular.<locals>.<genexpr>  s&   øè ø€ ÒWÀ”l 1 g¨qÓ1Ð2°!°E°7Ô;ÑWùs   ƒÚrst©ÚheadersÚtablefmt)r�   r‘   r™   ÚImportErrorr{   ÚlistÚnextÚiterÚvaluesry   r‰   r"   r|   r’   r�   r“   rP   ÚextendÚappend)r‚   rq   r™   ÚerrÚ
table_dataÚkey_listÚkeyrŸ   r”   r•   Úrowr}   s    `         @r*   Ú_print_snapshot_tabularr­   î   s2  ù€ ô ˆ8ƒ}˜ÒÜÐ"Ô#ØðÝ%ô
 ˜uÓ%€GØ€JÜ”Dœ˜hŸo™oÓ/Ó0Ó1×6Ñ6Ó8Ó9€HØˆjØMUöØFIœ* S¬(Ô3ˆ3�9‰9‰+¸C¸5ÑAòñ €Gð "Ÿ™Ó)ò ‰ˆˆXÜ˜¤Ñ,¨g°qÓ9¸QÒ>ØÜ�3‹xˆjˆØ�
‰
ÔWÀXÇ_Á_ÓEVÔWÔWØ×Ñ˜#Õðô 
‰(�: w¸Ô
?Õ@øô# ò ÜØAó
àð	ûðüòs   žD' Á0'EÄ'	EÄ0D<Ä<ErM   c                 óÖ   — | j                  «       D ]L  \  }}t        |j                  › «       t        |«      D ]#  \  }}t        d|dz   › d�«       t	        ||«       Œ% ŒN t        «        y )Nz# r   ú:)r’   r‘   r|   Ú	enumerater–   )rM   rq   ÚstateÚsnapshot_listÚir‚   s         r*   Ú_print_state_snapshotsr´   
  sj   € ð !*§¡Ó 1ò -Ñˆˆ}Ü�—‘�ÔÜ$ ]Ó3ò 	-‰KˆAˆxÜ�B�q˜1‘u�g˜Q�-Ô Ü˜H eÕ,ñ	-ð-ô
 
…Gr)   c           
      óV  — 	 ddl m } g }d }t        |«      }| j                  «       D ]Ï  \  }}t	        |«      D ]¼  \  }	}
|j
                  › d|	dz   › �}|
j                  «       D ]�  \  }}t        |t           |d«      dk  rŒ||k7  r|ndt        |«      dœ}|}|j                  «       D ]8  \  }}t        ||d«      › d	|› �|t        |t        «      r|j
                  › n|› <   Œ: |j                  |«       Œ’ Œ¾ ŒÑ t         ||d
d¬«      «       y # t        $ r}t        d«      |‚d }~ww xY w)Nr   r˜   rš   z # r   r…   Ú )zState & Callr›   rˆ   ry   r�   rž   )r™   r¡   r{   r’   r°   r|   r�   r“   rP   r‰   r"   r§   r‘   )rM   rq   r™   r¨   r©   Úlast_state_callr}   r±   r²   r³   r‚   Ú
state_callr”   r•   r¬   r‹   rŒ   s                    r*   Ú_print_state_snapshots_tabularr¹     sX  € ðÝ%ð €JØ€OÜ˜uÓ%€GØ )§¡Ó 1ò 'Ñˆˆ}Ü$ ]Ó3ò 	'‰KˆAˆxØ!ŸK™K˜=¨¨A°©E¨7Ð3ˆJØ!)§¡Ó!1ò '‘��XÜ ¬Ñ 4°g¸qÓAÀQÒFØð '1°OÒ&C™
Èä! #›hñ	�ð #-�Ø$ŸN™NÓ,ò ‘D�A�qä'¨¨7°AÓ6Ð7°q¸¸Ð@ð ¬
°1´hÔ(?˜1Ÿ7™7™)ÈÀsÒLðð ×!Ñ! #Õ&ñ'ñ	'ð'ô$ 
‰(�: v¸Ô
>Õ?øô5 ò ÜØAó
àð	ûðús   ‚D Ä	D(ÄD#Ä#D(c                   óD   — e Zd Z e«       Z e«       Z e«       Z e«       Zy)Ú_UpdateTypeN)r$   r%   r&   r   ÚADDÚDELÚREFÚSIZEr(   r)   r*   r»   r»   7  s    „ ñ ‹&€CÙ
‹&€CÙ
‹&€CÙ‹6�Dr)   r»   c                   ó"  ‡ — e Zd ZdZd3d„Z	 	 d4dededee   dee	   ddf
d	„Z
	 d5d
ej                  de	dedee   fd„Zdedej"                  ddfd„Zd3d„Zd3d„Zdeddfd„Zde	d
ej                  ddfd„Z	 d6dedeej4                  eeef   f   fd„Z	 d7dej:                  dedeeef   fd„Zde defd„Z!dej:                  de ddfd„Z"dej:                  de de ddfd„Z#dej:                  de ddfd „Z$dej:                  de ddfd!„Z%de	d"e&jN                  ddfd#„Z(d3d$„Z)d3d%„Z*d&e+ej:                  e&jN                  ej                  f   ddfd'„Z,	 d8ded(ed)eddfd*„Z-	 d9d+ed(ed)eddfd,„Z.d3d-„Z/d3d.„Z0d3d/„Z1d:ˆ fd0„Z2de ddfˆ fd1„Z3d;d2„Z4ˆ xZ5S )<r    a£
  
    A TorchDispatchMode to track, categorize and attribute the tensor memory created or accessed within its context.

    It categorizes the tracked tensors as parameters, buffers, activations, gradients, temporary memory and optimizer states
    as defined by ``_MemRefType`` within its context. It captures memory `snapshots` for the modules, called within its context,
    at various states defined by ``_ModState``.

    Attributes:
        memory_tracking: A weakref key dictionary to store the memory statistics of each module. Each key
        is a reference to a module, and each value is a ``_ModMemStats`` object that stores the memory
        statistics of the module.

    Note:
        The MemTracker should be used as a context manager. The modules, optimizers, and any other tensors created within
        the context of MemTracker will be tracked by default. Any tensors or stateful objects such as modules, optimizers etc.
        that need to be tracked but are created outside the MemTracker should be registered using the `track_external` method.
        The `track_external` method should be called before the MemTracker is used. Any tensors created outside the ``MemTracker``
        and not supplied to the `track_external` method will not be tracked by the ``MemTracker``.

    Example usage:

        .. code-block:: python

            module = ...
            optimizer = ...
            inp = ...
            mem_tracker = MemTracker()
            mem_tracker.track_external(module, optimizer, inp)
            with mem_tracker as mt:
                loss = module(inp)
                print("After Forward:")
                mt.display_snapshot("current")
                loss.backward()
                optimizer.step()
                optimizer.zero_grad()
            mt.display_snapshot("peak")
            mt.display_modulewise_snapshots(depth=3, units="MiB")

    Known Limitations:
        - The ``MemTracker`` does not track memory for tensors that bypass the ``TorchDispatchMode`` ex. under ``no_dispatch``.
        - Resizing tensor storages directly by using non-Tensor methods other than using ``torch.Untyped_Storage.resize_``
          is not tracked. File a Github issue if you have use-cases for this.
        - If the tensors are not traceable or wrappable subclasses of ``torch.Tensor``, then the tracker does not know how to
            track their storages. File a Github issue if you have use-cases for this.
        - During AC in the backward pass there might be misattribution between activation and temp memory, but the peak memory
          will be tracked accurately. This will be fixed in the next update by hooking intricately with ``torch.uitls.checkpoint``.
    rW   Nc                 ó~  — t        «       | _        i | _        i | _        i | _        t        «       | _        d | _        t        «       | _        t        «       | _	        t        | _        d| _        d| _        d | _        t        j                   j"                  | _        t&        j(                  j*                  | _        d| _        y )NFr   )r   Úmemory_trackingÚ_curr_mem_snapÚ	_peak_memÚ_peak_mem_snapÚ_param_to_grad_hook_handlesÚ_optimizer_hook_handlesÚ_WINFOr   Ú_mod_trackerr.   Ú
_ref_classÚ_in_optÚ_in_acÚ_ac_modrm   rn   Úresize_Ú_orig_resizer   Ú_op_dispatcherÚdispatchÚ_orig_dtensor_dispatchÚ_depth©rN   s    r*   rO   zMemTracker.__init__u  s�   € Ü2Ó4ˆÔØBDˆÔØ24ˆŒØBDˆÔÜ+>Ó+@ˆÔ(ð ð 	Ô$ô *Ó+ˆŒÜ&›LˆÔä*5ˆŒà"ˆŒØ!ˆŒà.2ˆŒÜ!×0Ñ0×8Ñ8ˆÔÜ&-×&<Ñ&<×&EÑ&EˆÔ#Øˆ�r)   Úu_typeri   Úold_mem_consumedÚold_reftypec                 óÜ  — d}| j                   j                  |j                  t        j	                  | j
                  d«      «      }|j                  t        d«       |t        j                  k(  r>||j                  xx   |j                  z  cc<   |t        xx   |j                  z  cc<   �n|t        j                  k(  r?||j                  xx   |j                  z  cc<   |t        xx   |j                  z  cc<   d}n¯|t        j                  k(  r=|€J ‚||xx   |j                  z  cc<   ||j                  xx   |j                  z  cc<   n_|t        j                  k(  r>|€J ‚|j                  |z
  }||j                  xx   |z  cc<   |t        xx   |z  cc<   d}nt        d|› �«      ‚|r<| j                   |j                     t           dk(  r| j                   |j                  = y y y )NFr   TzInvalid update type: )rÃ   Ú
setdefaultrU   ÚdictÚfromkeysrÊ   r“   r»   r¼   rV   rZ   r½   r¾   r¿   rw   )rN   rÕ   ri   rÖ   r×   Ú
maybe_zeror•   Úchanges           r*   Ú_update_snapzMemTracker._update_snapŒ  s±  € ð ˆ
à×&Ñ&×1Ñ1Ø�L‰Lœ$Ÿ-™-¨¯©¸Ó;ó
ˆð 	×ÑœJ¨Ô*à”[—_‘_Ò$à�U—]‘]Ó# u×'9Ñ'9Ñ9Ó#Ø”ZÓ  E×$6Ñ$6Ñ6Õ Ø”{—‘Ò&à�U—]‘]Ó# u×'9Ñ'9Ñ9Ó#Ø”ZÓ  E×$6Ñ$6Ñ6Ó Ø‰JØ”{—‘Ò&ØÐ*Ð*Ð*à�[Ó! U×%7Ñ%7Ñ7Ó!Ø�U—]‘]Ó# u×'9Ñ'9Ñ9Ô#Ø”{×'Ñ'Ò'Ø#Ð/Ð/Ð/à×'Ñ'Ð*:Ñ:ˆFØ�U—]‘]Ó# vÑ-Ó#Ø”ZÓ  FÑ*Ó Ø‰JäÐ4°V°HÐ=Ó>Ð>áØ×"Ñ" 5§<¡<Ñ0´Ñ<ÀÒAà×'Ñ'¨¯©Ñ5ð Bð r)   ÚtrV   Úupdate_existingc                 ó2  — t        |«      }t        «       }|D ]ü  }| j                  j                  |d«      \  }}|�L|j                  }	|	|k7  r)||_        | j                  t        j                  ||	¬«       |j                  |«       Œp|rt        d«      ‚t        j                  ||j                  || j                  «      \  }}
||
f| j                  |<   |j                  dkD  r | j                  t        j                  |«       |j                  |«       Œþ |S )N©NN)r×   zNo existing winfo foundr   )r   ÚsetrÈ   ÚgetrV   rÞ   r»   r¾   ÚaddÚKeyErrorrR   rk   rU   Ú_delete_callbackrZ   r¼   )rN   rß   rV   rà   ÚstsÚwinfosrb   ri   Ú_r×   rj   s              r*   Ú_update_and_maybe_create_winfosz*MemTracker._update_and_maybe_create_winfos¸  sÿ   € ô # 1Ó%ˆÜ“ˆØò 	"ˆBà—{‘{—‘ r¨<Ó8‰HˆE�1ØÐ à#Ÿm™m�Ø 'Ò)à$+�E”MØ×%Ñ%¤k§o¡o°uÈ+Ð%ÔVØ—
‘
˜5Õ!Ù äÐ8Ó9Ð9ô +×7Ñ7Ø˜Ÿ™ '¨4×+@Ñ+@ó‘��tð $)¨$ -�—‘˜B‘à×%Ñ%¨Ò)Ø×%Ñ%¤k§o¡o°uÔ=Ø—
‘
˜5Õ!ð1	"ð2 ˆr)   rj   c                 ód   — |j                   dkD  r!| j                  t        j                  |«       y y ©Nr   )rZ   rÞ   r»   r½   )rN   ri   rj   s      r*   rç   zMemTracker._delete_callbackÛ  s+   € ð ×Ñ Ò!Ø×ÑœkŸo™o¨uÕ5ð "r)   c                 óœ   ‡ — t        ‰ j                  «      dt        j                  dt        dd fˆ fd„«       }|t        j                  _        y )Nrb   rS   rW   c                 ó(  •— ‰j                  | |«       ‰j                  j                  | d«      \  }}|�^|j                  | j                  «       k7  r@|j                  }|j                  | «       ‰j                  t        j                  ||¬«       y y y )Nrâ   ©rÖ   )	rÏ   rÈ   rä   rS   rZ   rd   rÞ   r»   r¿   )rb   rS   ri   rê   rÖ   rN   s        €r*   rÎ   z)MemTracker._track_resize.<locals>.resize_ä  s…   ø€ à×Ñ˜b $Ô'Ø—{‘{—‘ r¨<Ó8‰HˆE�1ØÐ  U§Z¡Z°2·7±7³9Ò%<Ø#(×#5Ñ#5Ð Ø×)Ñ)¨"Ô-Ø×!Ñ!Ü×$Ñ$ eÐ>Nð "õ ð &=Ð r)   )r   rÏ   rm   rn   rl   rÎ   )rN   rÎ   s   ` r*   Ú_track_resizezMemTracker._track_resizeá  sM   ø€ ô 
ˆt× Ñ Ó	!ð	œ×,Ñ,ð 	´Cð 	¸Dô 	ó 
"ð	ð (/Œ×ÑÕ$r)   c                 óB   — | j                   t        j                  _        y rK   )rÏ   rm   rn   rÎ   rÔ   s    r*   Ú_restore_resizezMemTracker._restore_resizeñ  s   € Ø'+×'8Ñ'8Œ×ÑÕ$r)   Ú
peak_statec                 ó~  — | j                   }| j                  j                  «       D ]§  }|j                  | j                  j
                  v sŒ&||j                  v sŒ5|j                  «       D ]`  \  }}|j                  j                  |d«      |t           k  sŒ-|t           |j                  |<   t        |«      |j                  |   d   |<   Œb Œ© |j                  «       D ]Z  \  }}| j                  j                  |d«      |t           k  sŒ-|t           | j                  |<   t        |«      | j                  |<   Œ\ y )Nr   éÿÿÿÿ)rÃ   rÂ   r¥   rI   rÉ   ÚparentsrM   r’   rL   rä   r“   r   rÄ   rÅ   )rN   rô   Ú	curr_snapÚ	mod_statsr”   r•   s         r*   Ú_update_peak_statszMemTracker._update_peak_statsô  s)  € ð ×'Ñ'ˆ	à×-Ñ-×4Ñ4Ó6ò 	ˆIØ× Ñ  D×$5Ñ$5×$=Ñ$=Ò=Ø ×!4Ñ!4Ò4Ø)2¯©Ó):ò ™˜˜XØ$×/Ñ/×3Ñ3°C¸Ó;¸hÄzÑ>RÓRØ8@ÄÑ8L˜I×0Ñ0°Ñ5ÜGOØ (óH˜I×/Ñ/°
Ñ;¸BÑ?ÀÒDñð	ð 'Ÿ_™_Ó.ò 	>‰MˆC�Ø�~‰~×!Ñ! # qÓ)¨H´ZÑ,@Ó@Ø&.¬zÑ&:�—‘˜sÑ#Ü+3°HÓ+=�×#Ñ# CÒ(ñ	>r)   c                 ó  — t        |«      }|D ]ñ  }| j                  j                  |d«      \  }}|�^|j                  |j                  «       k7  r?|j                  }|j                  |«       | j                  t        j                  ||¬«        y t        j                  ||j                  || j                  «      \  }}||f| j                  |<   |j                  dkD  sŒÒ| j                  t        j                  |«       Œó y )Nrâ   rð   r   )r   rÈ   rä   rS   rZ   rd   rÞ   r»   r¿   rR   rk   rU   rç   r¼   )	rN   rV   rß   rè   rb   ri   rê   rÖ   rj   s	            r*   Ú_trackzMemTracker._track  sé   € ô # 1Ó%ˆØò 	>ˆBØ—{‘{—‘ r¨<Ó8‰HˆE�1ØÐ Ø—:‘: §¡£Ò*Ø',×'9Ñ'9Ð$Ø×-Ñ-¨bÔ1Ø×%Ñ%Ü#×(Ñ(¨%ÐBRð &ô ñ ä*×7Ñ7Ø˜Ÿ™ '¨4×+@Ñ+@ó‘��tð $)¨$ -�—‘˜B‘à×%Ñ%¨Ó)Ø×%Ñ%¤k§o¡o°uÕ=ñ#	>r)   r]   c                 ó†   — |dk(  rt        | j                  «      S |dk(  rt        | j                  «      S t        d|› �«      ‚)aE  
        Capture a snapshot of the memory usage breakdown per device, based on the specified type.

        Args:
            type (str): The type of snapshot to capture. Can be "current" for the current memory usage or "peak" for the
                        peak memory usage. Defaults to "current".
        Returns:
            Dict[torch.device, Dict[str, int]]: A dictionary where each key is a torch.device, and each value is another
                                                dictionary. This inner dictionary has keys representing memory reference
                                                types as defined in ``_MemRefType`` and values representing the amount of
                                                memory consumed in bytes.
        Raises:
            ValueError: If an invalid type is specified.
        ÚcurrentÚpeakzInvalid type )r   rÃ   rÅ   rw   )rN   r]   s     r*   Úget_tracker_snapshotzMemTracker.get_tracker_snapshot#  sG   € ð" �9ÒÜ˜D×/Ñ/Ó0Ð0Ø�VŠ^Ü˜D×/Ñ/Ó0Ð0ä˜}¨T¨FÐ3Ó4Ð4r)   ÚmoduleÚinstall_grad_hooksc                 ó†  ‡ ‡
— dt         j                  dd fˆ fd„Š
d}|j                  «       D ]Ã  }‰ j                  |t        j
                  «      }|t        d„ |D «       «      z  }|j                  �*‰ j                  |j                  t        j                  «       ‰ j                  j                  |d «      �Œ‹|sŒŽ|j                  ‰
«      }|j                  ˆ
fd„«      }||f‰ j                  |<   ŒÅ d}|j                  «       D ]7  }	‰ j                  |	t        j                  «      }|t        d„ |D «       «      z  }Œ9 ||fS )NÚgradrW   c                 óF   •— ‰j                  | t        j                  «       y rK   )rë   r.   r8   )r  rN   s    €r*   Ú
_grad_hookz?MemTracker._track_module_params_and_buffers.<locals>._grad_hookC  s   ø€ Ø×0Ñ0ØÜ× Ñ õr)   r   c              3   ó4   K  — | ]  }|j                   –— Œ y ­wrK   ©rZ   ©rŠ   ri   s     r*   r�   z>MemTracker._track_module_params_and_buffers.<locals>.<genexpr>O  s   è ø€ ÒG°u × 2Õ 2ÑGùó   ‚c                 ó(   •—  ‰| j                   «      S rK   )r  )Úpr  s    €r*   ú<lambda>z=MemTracker._track_module_params_and_buffers.<locals>.<lambda>[  s   ø€ ™z¨!¯&©&Ó1€ r)   c              3   ó4   K  — | ]  }|j                   –— Œ y ­wrK   r  r	  s     r*   r�   z>MemTracker._track_module_params_and_buffers.<locals>.<genexpr>g  s   è ø€ Ò H¸ ×!3Õ!3Ñ Hùr
  )rm   ÚTensorÚ
parametersrë   r.   r6   Úsumr  r8   rÆ   rä   Úregister_hookÚ"register_post_accumulate_grad_hookÚbuffersr7   )rN   r  r  Úparam_memoryÚparamré   Úgrad_hook_handleÚpost_acc_grad_hook_handleÚbuffer_memoryÚbufferr  s   `         @r*   Ú _track_module_params_and_buffersz+MemTracker._track_module_params_and_buffers;  sP  ù€ ð	œUŸ\™\ð 	¨dõ 	ð ˆØ×&Ñ&Ó(ò 	ˆEØ×9Ñ9ØÜ×!Ñ!óˆFð œCÑGÀÔGÓGÑGˆLØ�z‰zÐ%Ø×4Ñ4Ø—J‘JÜ×$Ñ$ôð
 ×0Ñ0×4Ñ4°U¸DÓAÑIÚ&à#(×#6Ñ#6°zÓ#BÐ Ø,1×,TÑ,TÛ2ó-Ð)ð %Ø-ð;�×0Ñ0°Ò7ð'	ð. ˆØ—n‘nÓ&ò 	IˆFØ×9Ñ9ØÜ×"Ñ"óˆFð œSÑ HÀÔ HÓHÑH‰Mð	Ið ˜mÐ,Ð,r)   Úargsc                 óv   ‡ ‡— dŠdt         j                  dd fˆˆ fd„}t        t         j                  ||«       ‰S )Nr   rß   rW   c                 óŒ   •— t        | «      }|D ]3  }‰j                  j                  |d«      \  }}|€Œ%‰|j                  z  ŠŒ5 y )Nrâ   )r   rÈ   rä   rZ   )rß   rè   rb   ri   rê   Úinput_or_output_memoryrN   s        €€r*   Úadd_inps_or_outsz=MemTracker._track_inputs_or_outputs.<locals>.add_inps_or_outsn  sM   ø€ ä& qÓ)ˆCØò A�ØŸ;™;Ÿ?™?¨2¨|Ó<‘��qØÑ$Ø*¨e×.@Ñ.@Ñ@Ñ*ñAr)   )rm   r  r   )rN   r  r   r  s   `  @r*   Ú_track_inputs_or_outputsz#MemTracker._track_inputs_or_outputsj  s<   ù€ à!"Ðð	A¤§¡ð 	A°ö 	Aô 	”e—l‘lÐ$4°dÔ;Ø%Ð%r)   Úinputsc                 óz  — | j                   j                  |«      }|€J ‚|| j                  vrgt        |«      }| j	                  |d¬«      \  }}| j                  |«      }||_        ||_        ||_        || j                  |<   t        j                  }ná| j                   j                  rM| j                  |   }t        j                  }| j                  € t        j                  |«      | _        d| _        n~t#        | j                   j$                  «      |hz
  }	t'        |	«      dk(  rd|	v rt)        d«      ‚| j                  |   }t        j                  }| j                  |«      }||_        ||_        | j-                  «       }
|t        j                  k(  ri|
j/                  «       D ��ci c]  \  }}||t0           “Œ c}}|_        |j4                  j7                  t        j8                  g «      j;                  |
«       |j4                  j7                  |g «      j;                  t=        |
«      «       y c c}}w )NT©r  r   ÚGlobalzÑMemTracker does not support memory tracking for multiple iterative calls. Either use ``reset_mod_stats`` to clear module memory stats for the previous iteration or file a github issue if you need this feature.)rÉ   Úget_known_fqnrÂ   rH   r  r!  Úparameter_memÚ
buffer_memÚ	input_memr>   r?   Úis_bwrC   rÍ   r   rg   rÌ   rã   r÷   r�   ÚNotImplementedErrorrI   r   r’   r“   rL   rM   rÙ   rA   r§   r   )rN   r  r"  Úmod_namerù   Ú	param_memr(  r)  r±   r÷   Úmem_snapshotr”   r•   s                r*   Ú_pre_fw_hookzMemTracker._pre_fw_hooky  s  € ð ×$Ñ$×2Ñ2°6Ó:ˆØÐ#Ð#Ð#Ø˜×-Ñ-Ñ-Ü$ XÓ.ˆIØ$(×$IÑ$IØ¨4ð %Jó %Ñ!ˆI�zð ×5Ñ5°fÓ=ˆIØ&/ˆIÔ#Ø#-ˆIÔ Ø"+ˆIÔØ+4ˆD× Ñ  Ñ(Ü×$Ñ$‰Eà×Ñ×$Ò$Ø×,Ñ,¨VÑ4ˆIÜ×'Ñ'ˆEØ�|‰|Ð#Ü&Ÿ{™{¨6Ó2�”Ø"�•ä˜$×+Ñ+×3Ñ3Ó4¸°zÑAˆGÜ�7‹|˜qÒ  X°Ñ%8Ü)ðHóð ð
 ×,Ñ,¨VÑ4ˆIÜ×$Ñ$ˆEØ×5Ñ5°fÓ=ˆIØ (ˆIÔØ"+ˆIÔà×0Ñ0Ó2ˆØ”I×$Ñ$Ò$à?K×?QÑ?QÓ?S÷$Ù.;¨c°8��XœjÑ)Ñ)ó$ˆIÔ ð ×Ñ×*Ñ*¬9×+<Ñ+<¸bÓA×HÑHÈÔVØ×Ñ×&Ñ& u¨bÓ1×8Ñ8¼À,Ó9OÕPùó	$s   Æ,H7Úoutputsc                 óŠ  — | j                   |   }| j                  j                  r=t        j                  }| j
                  �I| j                  «       |u r7d | _        d| _        n(t        j                  }| j                  |«      }||_	        |j                  j                  |g «      j                  | j                  «       «       y ©NF)rÂ   rÉ   r*  r>   rD   rÍ   rÌ   r@   r!  Ú
output_memrM   rÙ   r§   r   )rN   r  r"  r0  rù   r±   r3  s          r*   Ú_post_fw_hookzMemTracker._post_fw_hook±  s    € ð ×(Ñ(¨Ñ0ˆ	Ø×Ñ×"Ò"Ü×(Ñ(ˆEØ�|‰|Ð'¨D¯L©L«N¸fÑ,DØ#�”Ø#�•ä×%Ñ%ˆEØ×6Ñ6°wÓ?ˆJØ#-ˆIÔ Ø×Ñ×&Ñ& u¨bÓ1×8Ñ8¸×9RÑ9RÓ9TÕUr)   c                 óØ  — |€t        j                  dd¬«       y | j                  |   }| j                  «       }|j	                  «       D ��ci c]  \  }}||t
           “Œ c}}|_        |j                  j                  t        j                  g «      j                  |«       |j                  j                  t        j                  g «      j                  t        |«      «       y c c}}w )Nz%Module is None. Skipping PRE_BW hook.r…   ©Ú
stacklevel)ÚwarningsÚwarnrÂ   r   r’   r“   rL   rM   rÙ   r>   rF   r§   rB   r   )rN   r  r  rù   r.  r”   r•   s          r*   Ú_pre_bw_hookzMemTracker._pre_bw_hookÄ  sÅ   € ð ˆ>Ü�M‰MÐAÈaÕPØØ×(Ñ(¨Ñ0ˆ	Ø×0Ñ0Ó2ˆà;G×;MÑ;MÓ;O÷ 
Ù*7¨#¨xˆC�œ*Ñ%Ñ%ó 
ˆ	Ôð 	×Ñ×&Ñ&¤y×'8Ñ'8¸"Ó=×DÑDÀ\ÔRØ×Ñ×&Ñ&¤y×'7Ñ'7¸Ó<×CÑCÜ�\Ó"õ	
ùó	 
s   ÁC&c                 óä   — |€t        j                  dd¬«       y | j                  |   }|j                  j	                  t
        j                  g «      j                  | j                  «       «       y )Nz&Module is None. Skipping POST_BW hook.r…   r6  )	r8  r9  rÂ   rM   rÙ   r>   rE   r§   r   )rN   r  r  rù   s       r*   Ú_post_bw_hookzMemTracker._post_bw_hook×  s^   € ð
 ˆ>Ü�M‰MÐBÈqÕQØØ×(Ñ(¨Ñ0ˆ	Ø×Ñ×&Ñ&¤y×'8Ñ'8¸"Ó=×DÑDØ×%Ñ%Ó'õ	
r)   Ú	optimizerc                 óÆ   — |j                   j                  «       D ]D  }|j                  «       D ]/  }t        |t        j                  «      sŒ| j                  ||«       Œ1 ŒF y rK   )r±   r¥   r‰   rm   r  rë   )rN   rV   r=  ÚstatesÚvals        r*   Ú_track_optimizer_statesz"MemTracker._track_optimizer_statesä  sW   € ð  —o‘o×,Ñ,Ó.ò 	ˆFØ—}‘}“ò �Ü˜c¤5§<¡<Õ0Ø×8Ñ8ØØõññ	r)   c                 óÌ   ‡ — dt         j                  dt        dt        dd fˆ fd„}dt         j                  dt        dt        dd fˆ fd„}t        |«      t	        |«      f‰ _        y )Nr=  r  ÚkwargsrW   c                 ó   •— d‰_         y )NT)rË   ©r=  r  rC  rN   s      €r*   Ú_opt_step_pre_hookzFMemTracker._register_global_optimizer_hook.<locals>._opt_step_pre_hookó  s   ø€ ð  ˆD�Lr)   c                 óT   •— ‰j                  t        j                  | «       d‰_        y r2  )rA  r.   r;   rË   rE  s      €r*   Ú_opt_step_post_hookzGMemTracker._register_global_optimizer_hook.<locals>._opt_step_post_hookø  s    ø€ ð ×(Ñ(¬¯©¸)ÔDØ ˆD�Lr)   )r   Ú	Optimizerr	   r   r   rÇ   )rN   rF  rH  s   `  r*   Ú_register_global_optimizer_hookz*MemTracker._register_global_optimizer_hookï  ss   ø€ ð	 Ü—‘ð	 Ü.1ð	 Ü;>ð	 àõ	 ð
	!Ü—‘ð	!Ü.1ð	!Ü;>ð	!àõ	!ô -Ð-?Ó@Ü-Ð.AÓBð(
ˆÕ$r)   c                 ó&  — | j                   j                  «       D ]%  \  }}|j                  «        |j                  «        Œ' | j                   j                  «        | j                  �)| j                  D ]  }|j                  «        Œ d | _        y y rK   )rÆ   r¥   ÚremoveÚclearrÇ   )rN   r  r  Úhandles       r*   Ú%_deregister_param_and_optimizer_hooksz0MemTracker._deregister_param_and_optimizer_hooks  sŽ   € ð ×-Ñ-×4Ñ4Ó6ò	/ñ 
ØØ%à×#Ñ#Ô%Ø%×,Ñ,Õ.ð	/ð 	×(Ñ(×.Ñ.Ô0à×'Ñ'Ð3Ø×6Ñ6ò  �Ø—‘•ð à+/ˆDÕ(ð 4r)   Úexternalc                 ó¾  — t        |«      \  }}|D ]Ê  }t        |t        j                  «      r!| j	                  |t
        j                  «       Œ>t        |t        j                  j                  «      r| j                  |d¬«       Œvt        |t        j                  «      r!| j                  t
        j                  |«       Œ±|€Œ´t        dt        |«      › d�«      ‚ y)aþ  
        Track tensors and stateful objects like modules, optimizers etc. that are created outside the MemTracker.

        This method should be called before the ``MemTracker`` is used. Any tensors that are not module parameters, buffers,
        gradients activations, or optimizer states will be categorized as ``Other``. If you want them categorized with a
        custom name, please file a GitHub issue. Any tensors created outside the MemTracker and not supplied to this
        method will not be be tracked by ``MemTracker``.

        Args:
            *external (Union[nn.Module, optim.Optimizer, torch.Tensor]): The external modules, optimizers, and
                                                                         tensors to be tracked.
        Fr$  NzObject of type zj is not supported for tracking. Only stateful objects like modules, optimizers, and tensors are supported.)r   r‰   rm   r  rë   r.   r<   r   ÚModuler  r   rI  rA  r;   Ú	TypeErrorr]   )rN   rP  Úflat_externalrê   Úobjs        r*   Útrack_externalzMemTracker.track_external  s½   € ô (¨Ó1Ñˆ�qØ ò 	ˆCÜ˜#œuŸ|™|Ô,Ø×4Ñ4ØÜ—O‘Oõô ˜C¤§¡§¡Ô1Ø×5Ñ5°cÈeÐ5ÕTÜ˜C¤§¡Ô1Ø×,Ñ,¬[¯_©_¸cÕBØ�ØäØ%¤d¨3£i [ð 1að bóð ñ	r)   rq   r™   c                 ó\   — | j                  |«      }|rt        ||«       yt        ||«       y)a'  
        Display the memory usage breakdown snapshot of the tracker based on the specified type and units.

        Keyword args:
            type (str): The type of snapshot to display. Can be "current" for the current memory usage or "peak" for the
                        peak memory usage. Defaults to "current".
            units (str): The units to use for displaying memory usage. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"].
            tabulate (bool): Whether to display the snapshot in a tabular format. Defaults to False.
        N)r   r­   r–   )rN   r]   rq   r™   r‚   s        r*   Údisplay_snapshotzMemTracker.display_snapshot3  s+   € ð ×,Ñ,¨TÓ2ˆÙÜ# H¨eÕ4ä˜H eÕ,r)   Údepthc                 ón  ‡— dt         dt        t        t        t         f      fd„Št	        | j
                  j                  «       ˆfd„¬«      D ]e  }|j                  }|j                  d«      dz   }||kD  rŒ)t        d|› �«       |rt        |j                  |«       ŒPt        |j                  |«       Œg y	)
aZ  
        Print per device memory breakdown snapshot for each module called within MemTracker.

        Snapshots are displayed for the states defined by ``_ModState``.
        The module hierarchy is displayed up to the specified depth.

        Keyword Args:
            depth (int, optional): The depth of the module hierarchy to display. Defaults to 2.
            units (str, optional): The units to use for memory tracking. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"].
            tabulate (bool, optional): Whether to display the snapshot in a tabular format. Defaults to False.
        ÚsrW   c                 ó¦   — t        j                  d| «      D �cg c]-  }|j                  «       rt        |«      n|j	                  «       ‘Œ/ c}S c c}w )Nz([0-9]+))ÚreÚsplitÚisdigitrl   Úlower)r[  Útexts     r*   Únatural_sort_keyzAMemTracker.display_modulewise_snapshots.<locals>.natural_sort_keyT  sF   € ô ŸH™H Z°Ó3öàð "Ÿ\™\œ^”�D”	°·±³Ñ=òð ùò s   ™2Ac                 ó(   •—  ‰| j                   «      S rK   )rI   )Úm_statsrb  s    €r*   r  z9MemTracker.display_modulewise_snapshots.<locals>.<lambda>\  s   ø€ Ñ 0°·±Ó A€ r)   )r«   ú.r   z	Module:  N)rP   r¢   r   rl   ÚsortedrÂ   r¥   rI   Úcountr‘   r¹   rM   r´   )rN   rY  rq   r™   rù   rI   Ú	mod_depthrb  s          @r*   Údisplay_modulewise_snapshotsz'MemTracker.display_modulewise_snapshotsE  s­   ø€ ð	¤ð 	¬¬U´3¼°8©_Ñ(=ó 	ô  Ø× Ñ ×'Ñ'Ó)ÛAô
ò 	CˆIð  ×'Ñ'ˆGØŸ™ cÓ*¨QÑ.ˆIØ˜5Ò ØÜ�I˜g˜YÐ'Ô(ÙÜ.¨y×/BÑ/BÀEÕJä& y×':Ñ':¸EÕBñ	Cr)   c                 ó8   — | j                   j                  «        y)z[
        Reset all the module memory stats. Clears ``memory_tracking`` dictionary.
        N)rÂ   rM  rÔ   s    r*   Úreset_mod_statszMemTracker.reset_mod_statsh  s   € ð 	×Ñ×"Ñ"Õ$r)   c                 óÀ   ‡ — dt         j                  j                  dt        t        df   dt
        t        t        f   dt        fˆ fd„}|t        j                  _	        y )NÚop_callr  .rC  rW   c                 ó¦   •— | t         j                  j                  v r‰n	t        «       5  ‰j	                  | ||«      cd d d «       S # 1 sw Y   y xY wrK   )r   rÐ   Ú_custom_op_handlersr   rÒ   )rm  r  rC  rN   s      €r*   Útrack_dtensor_dispatchzBMemTracker._track_dtensor_dispatch.<locals>.track_dtensor_dispatcho  sP   ø€ ð œg×4Ñ4×HÑHÑHñ ä “]ñJð
 ×2Ñ2°7¸DÀ&ÓI÷J÷ Jò Jús   ªAÁA)
rm   Ú_opsÚ
OpOverloadrp   ÚobjectrÚ   rP   r   rÐ   rÑ   )rN   rp  s   ` r*   Ú_track_dtensor_dispatchz"MemTracker._track_dtensor_dispatchn  s^   ø€ ð
	JÜ—Z‘Z×*Ñ*ð
	Jäœ ˜Ñ$ð
	Jô œœf˜Ñ%ð
	Jô õ	
	Jð +AŒ×ÑÕ'r)   c                 óB   — | j                   t        j                  _        y rK   )rÒ   r   rÐ   rÑ   rÔ   s    r*   Ú_restore_dtensor_dispatchz$MemTracker._restore_dtensor_dispatch}  s   € Ø*.×*EÑ*EŒ×ÑÕ'r)   c                 ó6  •— | j                   dk(  rß| j                  «        | j                  j                  | j                  | j
                  | j                  | j                  «       | j                  «        | j                  «        | j                  «       | _        | j                  j                  «       D ��ci c]  \  }}||t           “Œ c}}| _        | j                  j                  «        t         ‰| �=  «        | xj                   dz  c_         | S c c}}w )Nr   r   )rÓ   rJ  rÉ   Úregister_user_hooksr/  r4  r:  r<  rñ   rt  r   rÅ   r’   r“   rÄ   Ú	__enter__Úsuper)rN   r”   r•   Ú	__class__s      €r*   ry  zMemTracker.__enter__€  sî   ø€ Ø�;‰;˜!ÒØ×0Ñ0Ô2Ø×Ñ×1Ñ1Ø×!Ñ!Ø×"Ñ"Ø×!Ñ!Ø×"Ñ"ô	ð ×ÑÔ Ø×(Ñ(Ô*Ø"&×";Ñ";Ó"=ˆDÔð &*×%8Ñ%8×%>Ñ%>Ó%@÷á!�C˜ð �XœjÑ)Ñ)óˆDŒNð ×Ñ×'Ñ'Ô)Ü‰ÑÔØ�Š�qÑ�Øˆùós   Â9Dc                 ó,  •— | xj                   dz  c_         | j                   dk(  rc| j                  «        | j                  j                  «        | j	                  «        | j                  «         | j                  j                  |Ž  t        ‰| �  |Ž  y )Nr   r   )rÓ   rO  rÉ   Úclear_user_hooksró   rv  Ú__exit__rz  )rN   r  r{  s     €r*   r~  zMemTracker.__exit__•  sv   ø€ Ø�Š�qÑ�Ø�;‰;˜!ÒØ×6Ñ6Ô8Ø×Ñ×.Ñ.Ô0Ø× Ñ Ô"Ø×*Ñ*Ô,Ø&ˆD×Ñ×&Ñ&¨Ñ-Ü‰Ñ˜$Òr)   c                 óL  — |t         j                  j                  j                  j                  k(  rt        «       r|d   }n ||i |xs i ¤Ž}| j                  rt        j                  }nC| j                  j                  r| j                  st        j                  }nt        j                  }t        t         j                  t!        | j"                  |«      |«       | j                  j                  rt$        j&                  nt$        j(                  }| j+                  |«       |S rí   )rm   ÚopsÚ_c10d_functionalÚwait_tensorÚdefaultr   rË   r.   r;   rÉ   r*  rÌ   r:   r9   r   r  r   rü   r>   rF   rA   rú   )rN   ÚfuncÚtypesr  rC  ÚresrV   rô   s           r*   Ú__torch_dispatch__zMemTracker.__torch_dispatch__Ÿ  sÎ   € à”E—I‘I×.Ñ.×:Ñ:×BÑBÒBÜ Ô"ð �q‘'‰Cá˜Ð- ¢¨"Ñ-ˆCð �<Š<Ü!—o‘o‰GØ×Ñ×$Ò$¨T¯[ª[Ü!×&Ñ&‰Gä!—o‘oˆGÜ”e—l‘l¤G¨D¯K©K¸Ó$AÀ3ÔGØ*.×*;Ñ*;×*AÒ*A”Y×&Ò&Äy×GXÑGXˆ
Ø×Ñ 
Ô+Øˆ
r)   )rW   Nrâ   )F)rþ   )T)rþ   rs   F)r…   rs   F)rW   r    )r(   N)6r$   r%   r&   r'   rO   r»   rR   r   rl   r"   rÞ   rm   r  Úboolrã   rë   r   rg   rç   rñ   ró   r,   rú   rü   rP   rÚ   rU   r   r   rR  rp   r  r	   r!  r/  r4  r:  r<  r   rI  rA  rJ  rO  r   rV  rX  ri  rk  rt  rv  ry  r~  r‡  Ú__classcell__)r{  s   @r*   r    r    D  sÉ  ø„ ñ.ó`ð6 +/Ø*.ñ*6àð*6ð ð*6ð # 3™-ð	*6ð
 ˜hÑ'ð*6ð 
ó*6ð` !&ñ	!à�<‰<ð!ð ð!ð ð	!ð
 
ˆ\Ñ	ó!ðF6 lð 6¸'¿+¹+ð 6È$ó 6ó/ó 9ð>¨Vð >¸ó >ð.>˜hð >¨5¯<©<ð >¸Dó >ð2 $ñ5Øð5à	ˆe�l‰l˜D  c ™NÐ*Ñ	+ó5ð2 =Añ--Ø—i‘ið--Ø59ð--à	ˆs�Cˆx‰ó--ð^&¨Sð &°Só &ð6Q 2§9¡9ð 6Q°cð 6Q¸dó 6QðpV B§I¡Ið V°sð VÀSð VÈTó Vð&
 2§9¡9ð 
°Cð 
¸Dó 
ð&
 B§I¡Ið 
°Sð 
¸Tó 
ð	Øð	Ø,1¯O©Oð	à	ó	ó
ó(0ð Ø˜rŸy™y¨%¯/©/¸5¿<¹<ÐGÑHð à	ó ðF INñ-Øð-Ø,/ð-ØAEð-à	ó-ð& BGñ!CØð!CØ%(ð!CØ:>ð!Cà	ó!CóF%óAóFõð* ˜cð   dõ  ÷r)   )Hr^   Úosr]  r8  Ú
contextlibr   Úcopyr   Úenumr   r   Ú	functoolsr   r   Útypingr	   r
   r   r   r   Útyping_extensionsr   rm   Ú)torch.distributed._tools.fake_collectivesr   r   Útorch._guardsr   Ú%torch.distributed._tools.common_utilsr   Ú$torch.distributed._tools.mod_trackerr   Útorch.distributed.tensorr   Útorch.optim.optimizerr   r   Útorch.utils._python_dispatchr   Útorch.utils._pytreer   r   Útorch.utils.weakr   r   Útorch.utils.hooksr   rl   Úenvironrä   r`   r“   Ú__all__rP   r"   r,   r.   r>   rH   rR   r{   Úfloatr�   rÚ   rU   r–   r­   r¢   r´   r¹   r»   r    r(   r)   r*   ú<module>rž     s(  ðÛ Û 	Û 	Û Ý "Ý ß ß $ß @Õ @Ý "ã Û 0ß Ý *Ý FÝ ;Ý ,÷õ ;ß ;ß 9ñ Ý1ñ
 �—
‘
—‘Ð?ÀÓCÓDÈÒI�DÈqð ð €
àˆ.€ôtˆs�Dô tôFˆS�$ô Fô�(ô ô,�ô ÷0Wñ W÷<Lñ Lð^
˜Cð 
 Có 
ðH˜ð H cð H°cð H¸eÀEÈ3ÀJÑ>Oó Hð
˜d 5§<¡<°°c¸3°h±Ð#?Ñ@ð 
Èð 
ÐQUó 
ð(AØ�5—<‘<  c¨3 h¡Ð/Ñ0ðAØ9<ðAà	óAð8Ø�F˜D  e§l¡l°D¸¸c¸±NÐ&BÑ!CÑDÐDÑEðØNQðà	óð@Ø�F˜D  e§l¡l°D¸¸c¸±NÐ&BÑ!CÑDÐDÑEð@ØNQð@à	ó@ôD
�$ô 
ôq	Ð"õ q	r)   