Ë
    g^(h,'  ã                   ón   — d dl Z d dlZd dlmZmZ d dlZd dlmZ d dlm	Z	m
Z
 d dlmZ dgZ G d„ d«      Zy)é    N)ÚCallableÚOptional)Úregister_multi_grad_hook)Úregister_module_forward_hookÚ register_module_forward_pre_hook)Útree_flattenÚ
ModTrackerc            
       ó°   — e Zd ZU dZee   ed<   	 d„ Zd„ Ze	d„ «       Z
d„ Z	 	 	 	 ddee   d	ee   d
ee   dee   fd„Zd„ Zd„ Zd„ Zd„ Zd„ Zd„ Zd„ Zd„ Zy)r	   a>  
    ``ModTracker`` is a context manager that tracks the nn.Module hierarchy during execution
    so that other system can query which Module is currently being executed (or its backward is being
    executed).

    You can access the ``parents`` attribute on this context manager to get the set of all the
    Modules currently being executed via their fqn (fully qualified name, also used as the key within
    the state_dict).
    You can access the ``is_bw`` attribute to know if you are currently running in backward or not.

    Note that ``parents`` is never empty and always contains the "Global" key. The ``is_bw`` flag
    will remain ``True`` after the forward until another Module is executed. If you need it to be
    more accurate, please submit an issue requesting this. Adding a map from fqn to the module instance
    is possible but not done yet, please submit an issue requesting this if you need it.

    Example usage

    .. code-block:: python

        mod = torch.nn.Linear(2, 2)

        with ModTracker() as tracker:
            # Access anything during the forward pass
            def my_linear(m1, m2, bias):
                print(f"Current modules: {tracker.parents}")
                return torch.mm(m1, m2.t()) + bias

            torch.nn.functional.linear = my_linear

            mod(torch.rand(2, 2))

    Úparentsc                 óÚ   — dh| _         i | _        t        j                  «       | _        t        j
                  «       | _        d| _        g | _        d | _	        d | _
        d | _        d | _        y ©NÚGlobalF)r   Ú_active_module_cntÚweakrefÚWeakKeyDictionaryÚ_known_modulesÚWeakSetÚ_seen_modulesÚ_has_callbackÚ_post_bw_callbacks_to_enqueueÚ_user_pre_fw_hookÚ_user_post_fw_hookÚ_user_pre_bw_hookÚ_user_post_bw_hook©Úselfs    úb/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/distributed/_tools/mod_tracker.pyÚ__init__zModTracker.__init__9   sc   € Ø �zˆŒØ"$ˆÔÜ9@×9RÑ9RÓ9TˆÔÜ.5¯o©oÓ.?ˆÔØ"ˆÔØ=?ˆÔ*Ø!%ˆÔØ"&ˆÔØ!%ˆÔØ"&ˆÕó    c                 ól  ‡ — ‰ j                   ry t        ‰ j                  «      D ]5  }t        j                  j
                  j                  j                  |«       Œ7 ‰ j                  j                  «        ˆ fd„}t        j                  j
                  j                  j                  |«       d‰ _         y )Nc                  ó$   •— dh‰ _         d‰ _        y r   )r   r   r   s   €r   Úcallbackz7ModTracker._maybe_set_engine_callback.<locals>.callbackN   s   ø€ Ø$˜:ˆDŒLØ!&ˆDÕr   T)	r   Úreversedr   ÚtorchÚautogradÚVariableÚ_execution_engineÚqueue_callbackÚclear)r   Úpost_bw_callbackr"   s   `  r   Ú_maybe_set_engine_callbackz%ModTracker._maybe_set_engine_callbackE   sŠ   ø€ à×ÒØä (¨×)KÑ)KÓ Lò 	WÐÜ�N‰N×#Ñ#×5Ñ5×DÑDÐEUÕVð	Wà×*Ñ*×0Ñ0Ô2ô	'ô 	�‰×Ñ×1Ñ1×@Ñ@ÀÔJØ!ˆÕr   c                 óD   — t         j                  j                  «       dk7  S )z`
        A boolean marking if this is currently running during the backward pass or not
        éÿÿÿÿ)r$   Ú_CÚ_current_graph_task_idr   s    r   Úis_bwzModTracker.is_bwU   s   € ô
 �x‰x×.Ñ.Ó0°BÑ6Ð6r   c                 ó:   — | j                   j                  |d«      S )zo
        Return the fqn for the given module if it is known to the ``ModTracker``, otherwise ``None``.
        N)r   Úget)r   Úmods     r   Úget_known_fqnzModTracker.get_known_fqn\   s   € ð ×"Ñ"×&Ñ& s¨DÓ1Ð1r   NÚpre_fw_hookÚpost_fw_hookÚpre_bw_hookÚpost_bw_hookc                 óÒ   — d„ } ||| j                   d«      | _          ||| j                  d«      | _         ||| j                  d«      | _         ||| j                  d«      | _        y)aB  
        Registers user-specified hooks to be called before/after the forward/backward pass for each
        module tracked by the ``ModTracker``. One or more can be ``None``.
        Args:
            pre_fw_hook (Callable, optional): A hook to be called before the forward pass for the
                module. It should have the following signature:
                pre_fw_hook (module, input) -> None
            post_fw_hook (Callable, optional): A hook to be called after the forward pass for the
                module. It should have the following signature:
                post_fw_hook (module, input, output) -> None
            pre_bw_hook (Callable, optional): A multi-grad hook to be called on all the outputs of
                the module that require gradients. It should have the following signature:
                pre_bw_hook (module, grad_output) -> None
            post_bw_hook (Callable, optional): A multi-grad hook to be called on all the inputs of
                the module that require gradients. It should have the following signature:
                post_bw_hook (module, grad_input) -> None
        Raises:
            AssertionError: If a new hook is provided when one is already registered.
        Note:
            If the module is not alive during the backward pass, the pre_bw_hook and post_bw_hook will
            will receive None as the module argument.
            The module fqn will be present in the ``parents`` attribute when each of the hooks is called.
            Hooks are intended to be used as markers only not to modify the inputs/outputs.
        c                 ó,   — | �|�t        d|› d�«      ‚| S )Nz	Only one zq can be registered at a time Clear the existing hook by calling ``clear_user_hooks`` before registering a new one)ÚAssertionError)ÚhookÚ	user_hookÚ	hook_names      r   Úset_hookz0ModTracker.register_user_hooks.<locals>.set_hook‚   s4   € ØÐ IÐ$9Ü$Ø 	˜{ð +lð móð ð ˆKr   r5   r6   r7   r8   N©r   r   r   r   )r   r5   r6   r7   r8   r?   s         r   Úregister_user_hookszModTracker.register_user_hooksb   sx   € ò@	ñ "*Ø˜×/Ñ/°ó"
ˆÔñ #+Ø˜$×1Ñ1°>ó#
ˆÔñ "*Ø˜×/Ñ/°ó"
ˆÔñ #+Ø˜$×1Ñ1°>ó#
ˆÕr   c                 ó<   — d| _         d| _        d| _        d| _        y)zY
        Clears the user specified hooks registered with ``register_user_hooks``
        Nr@   r   s    r   Úclear_user_hookszModTracker.clear_user_hooks—   s$   € ð "&ˆÔØ"&ˆÔØ!%ˆÔØ"&ˆÕr   c                 óP  — || j                   vr"t        |«      j                  | j                   |<   | j                   |   }|| j                  vrX|j	                  «       D ]*  \  }}|› d|› �| j                   |<   | j                  |«       Œ, | j                  j                  |«       |S )Nú.)r   ÚtypeÚ__name__r   Únamed_childrenÚ_get_mod_nameÚadd)r   r3   Úmod_nameÚnameÚsubmods        r   rI   zModTracker._get_mod_name    s¨   € Ø�d×)Ñ)Ñ)Ü'+¨C£y×'9Ñ'9ˆD×Ñ Ñ$Ø×&Ñ& sÑ+ˆØ�d×(Ñ(Ñ(Ø #× 2Ñ 2Ó 4ò +‘��fØ19°
¸!¸D¸6Ð.B�×#Ñ# FÑ+Ø×"Ñ" 6Õ*ð+ð ×Ñ×"Ñ" 3Ô'Øˆr   c                 ó   ‡ ‡‡‡— ˆˆˆ ˆfd„}|S )Nc                  ó”  •— ‰r‰j                  «        ‰‰j                  v r0‰j                  s$dd„}|t        _        t        j
                  d«       ‰‰j                  vr+d‰j                  ‰<   ‰j                  j                  ‰«       n‰j                  ‰xx   dz  cc<   ‰j                  �‰r‰j                   ‰«       | «       y y y )Nc                 ó2   — |› d|› d|j                   › d| › d�S )Nú:z: z 
)rG   )ÚmsgÚcategoryÚfilenameÚlinenoÚlines        r   Úcustom_formatwarningzCModTracker._get_append_fn.<locals>.fn.<locals>.custom_formatwarning±   s(   € Ø&˜Z q¨¨°°8×3DÑ3DÐ2EÀRÈÀuÈCÐPÐPr   zbThe module hierarchy tracking maybe be messed up. Please file a bug to PyTorch, if it is the case.é   ©N)	r+   r   r0   ÚwarningsÚformatwarningÚwarnr   rJ   r   )ÚargsrW   r0   rL   r   Úw_mods     €€€€r   Úfnz%ModTracker._get_append_fn.<locals>.fn¬   s´   ø€ ÙØ×/Ñ/Ô1Ø�t—|‘|Ñ#¨D¯JªJóQð *>”Ô&Ü—‘ðHôð ˜4Ÿ<™<Ñ'Ø01�×'Ñ'¨Ñ-Ø—‘× Ñ  Õ&à×'Ñ'¨Ó-°Ñ2Ó-à×%Ñ%Ð1±eØ×&Ñ&¡u£w°Õ5ð 7<Ð1r   © ©r   r^   rL   r0   r_   s   ```` r   Ú_get_append_fnzModTracker._get_append_fn«   s   û€ ÷	6ð, ˆ	r   c                 ó   ‡ ‡‡‡— ˆˆˆ ˆfd„}|S )Nc                  ó&  •— ‰j                   �‰r‰j                   ‰«       | «       ‰‰j                  v rF‰j                  ‰xx   dz  cc<   ‰j                  ‰   dk(  r‰j                  j                  ‰«       y y ‰j                  st        d«      ‚y )NrX   r   z?The Module hierarchy tracking is wrong. Report a bug to PyTorch)r   r   r   Úremover0   ÚRuntimeError)r]   r0   rL   r   r^   s    €€€€r   r_   z"ModTracker._get_pop_fn.<locals>.fnÅ   s�   ø€ Ø×&Ñ&Ð2±uØ×'Ñ'©«°Ô6Ø�t—|‘|Ñ#Ø×'Ñ'¨Ó-°Ñ2Ó-Ø×*Ñ*¨4Ñ0°AÒ5Ø—L‘L×'Ñ'¨Õ-ð 6à—Z’Zô #ØUóð ð  r   r`   ra   s   ```` r   Ú_get_pop_fnzModTracker._get_pop_fnÄ   s   û€ ÷	ð ˆ	r   c                 ó  — | j                  |«      }t        j                  |«      } | j                  ||d«      «        | j                  �| j	                  ||«       t        |«      \  }}|D �cg c],  }t        |t        j                  «      sŒ|j                  sŒ+|‘Œ. }}| j                  sM|rt        || j                  ||d«      «       y | j                  j                  | j                  ||d«      «       y y c c}w )NFT)rI   r   Úrefrb   r   r   Ú
isinstancer$   ÚTensorÚrequires_gradr0   r   rg   r   Úappend)	r   r3   ÚinputrL   r^   r]   Ú_ÚaÚtensorss	            r   Ú_fw_pre_hookzModTracker._fw_pre_hookÕ   sÜ   € Ø×!Ñ! #Ó&ˆÜ—‘˜CÓ ˆØ/ˆ×Ñ˜E 4¨Ó/Ô1Ø×!Ñ!Ð-Ø×"Ñ" 3¨Ô.Ü˜uÓ%‰ˆˆaØ"ÖV˜¤j°´E·L±LÕ&AÀaÇoÃo’1ÐVˆÐVØ�zŠzÙÜ(¨°$×2BÑ2BÀ5È$ÐPTÓ2UÕVà×2Ñ2×9Ñ9Ø×$Ñ$ U¨D°$Ó7õð	 ùò Ws   Á/C<ÂC<ÂC<c                 ó°  — | j                  |«      }t        j                  |«      }| j                  �| j                  |||«        | j	                  ||d«      «        t        |«      \  }}|D �cg c],  }t        |t        j                  «      sŒ|j                  sŒ+|‘Œ. }	}| j                  s#|	r t        |	| j                  ||d«      d¬«       y y y c c}w )NFTÚany)Úmode)rI   r   ri   r   rg   r   rj   r$   rk   rl   r0   r   rb   )
r   r3   rn   ÚoutputrL   r^   r]   ro   rp   rq   s
             r   Ú_fw_post_hookzModTracker._fw_post_hookå   s½   € Ø×!Ñ! #Ó&ˆÜ—‘˜CÓ ˆØ×"Ñ"Ð.Ø×#Ñ# C¨°Ô7Ø,ˆ×Ñ˜  eÓ,Ô.Ü˜vÓ&‰ˆˆaØ"ÖV˜¤j°´E·L±LÕ&AÀaÇoÃo’1ÐVˆÐVØ�zŠz™gÜ$Ø˜×,Ñ,¨U°D¸$Ó?Àeöð &ˆzùò Ws   Á0CÂCÂCc                 ór   — t        | j                  «      | _        t        | j                  d¬«      | _        | S )NT)Úalways_call)r   rr   Ú_fw_pre_handler   rw   Ú_fw_post_handler   s    r   Ú	__enter__zModTracker.__enter__ò   s4   € Ü>¸t×?PÑ?PÓQˆÔÜ;Ø×Ñ¨Dô 
ˆÔð ˆr   c                 ól   — | j                   j                  «        | j                  j                  «        y rY   )rz   re   r{   )r   r]   s     r   Ú__exit__zModTracker.__exit__ù   s&   € Ø×Ñ×"Ñ"Ô$Ø×Ñ×#Ñ#Õ%r   )NNNN)rG   Ú
__module__Ú__qualname__Ú__doc__ÚsetÚstrÚ__annotations__r   r+   Úpropertyr0   r4   r   r   rA   rC   rI   rb   rg   rr   rw   r|   r~   r`   r   r   r	   r	      s²   … ñðB �‰XÓðò
'ò"ð  ñ7ó ð7ò2ð +/Ø+/Ø*.Ø+/ñ3
à˜hÑ'ð3
ð ˜xÑ(ð3
ð ˜hÑ'ð	3
ð
 ˜xÑ(ó3
òj'ò	òò2ò"ò òó&r   )rZ   r   Útypingr   r   r$   Útorch.autograd.graphr   Útorch.nn.modules.moduler   r   Útorch.utils._pytreer   Ú__all__r	   r`   r   r   ú<module>r‹      s3   ðã Û ß %ã Ý 9÷õ -ð ˆ.€÷i&ò i&r   