
    sh *                         S SK r S SKJr  S SKJrJr  S SKJrJrJ	r	J
r
  S SKrS SKJr  \ " S S5      5       r " S S\	5      r " S	 S
5      r " S S5      rg)    N)contextmanager)	dataclassfield)AnyCallable
NamedTupleOptionalc                       \ rS rSr% Sr\" \R                  R                  S9r	\R                  R                  \
S'   Sr\\\\4      \
S'   Srg)TracingConfig   au  
This represents a symbolic tracing configuration.

Args:
    tracer (torch.fx.Tracer): An instance of :class:`torch.fx.Tracer` to
        use for symbolic tracing. The default value is the native
        :class:`torch.fx.Tracer` constructed with default arguments.
        However, the user may want to pass a different value such as the
        ``HFTracer`` for models in the HuggingFace Transformers_ library.
        .. _Transformers: https://huggingface.co/docs/transformers/index
    concrete_args (Optional[Dict[str, Any]]): Concrete arguments that
        should not be treated as ``torch.fx.Proxy`` when tracing the
        module ``forward()``. Passing ``concrete_args`` allows partially
        specializing the forward, e.g. to remove control flow or data
        structures. This ``concrete_args`` here is the same argument used
        in :meth:`~torch.fx.Tracer.trace`.
)default_factorytracerNconcrete_args )__name__
__module____qualname____firstlineno____doc__r   torchfxTracerr   __annotations__r   r	   dictstrr   __static_attributes__r       w/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/distributed/fsdp/_trace_utils.pyr   r      s?    $ $EHHOODFEHHOOD.2M8DcN+2r   r   c                   f    \ rS rSr% Sr\R                  \S'   \\	\
\R                  4      \S'   Srg)_ParamUsageInfo#   a  
This is used for ``_ExecutionInfo.module_to_param_usage_infos`` to record
execution information. The ``dict`` maps modules to a list of these
``_ParamUsageInfo`` instances, where each instance represents a group of
parameters used together.

Specifically, for each module key in the ``dict``, each instance of this
class represents either:
(1) the module and some sublist of its ``named_parameters()`` used
together in execution (see ``_patched_create_proxy()``), or
(2) a submodule and all of ``submodule.named_parameters()`` (see
``_patched_call_module()``).

Type (1) corresponds to directly using parameters in ops without calling
``forward()``, and type (2) corresponds to calling ``forward()``. The
mapped-to lists in the ``dict`` follow the execution order.
modulenamed_paramsr   N)r   r   r   r   r   nnModuler   listtupler   	Parameterr   r   r   r   r    r    #   s,    $ IIuS",,./00r   r    c                   >    \ rS rSrSrS\R                  SS4S jrSrg)_ExecutionInfo:   a  
This represents the execution order information from the forward pass.

Attributes:
    curr_module (nn.Module): Current module being traced.
    module_forward_order (List[nn.Module]): The modules in (pre-)forward
        order, i.e. the order in which their ``forward()`` methods are
        called. Each call to a module's ``forward()`` corresponds to one
        element in the list.
    module_to_param_usage_infos (Dict[nn.Module, List[_ParamUsageInfo]]):
        Maps a module to a list of module execution infos. See
        :class:`_ParamUsageInfo` for details.
    param_forward_order (List[nn.Parameter]): The parameters in forward
        execution order, where only a parameter's first participation is
        included.
    visited_params (Set[nn.Parameter]): The parameters visited so far
        during the trace. This is only used during tracing for fast
        membership check. Invariant: The parameters in
        ``param_forward_order`` are exactly those in ``visited_params``.
root_modulereturnNc                 ^    Xl         U/U l        U/ 0U l        / U l        [	        5       U l        g N)curr_modulemodule_forward_ordermodule_to_param_usage_infosparam_forward_ordersetvisited_params)selfr,   s     r   __init___ExecutionInfo.__init__P   s6    &16A]!T
( 8: 14r   )r0   r1   r2   r3   r5   )	r   r   r   r   r   r$   r%   r7   r   r   r   r   r*   r*   :   s    *7BII 7$ 7r   r*   c                      \ rS rSrSS jr\S\R                  R                  S\	R                  4S j5       rS\S	\S
\	R                  S\S\\S4   S\\\4   S\4S jr   SS\S	\S\\\	R&                  4   S\S\R                  R(                  R*                  S\\S4   S\\\4   S\\   S\\   S\\\R                  R.                  /\R                  R0                  4      S\R                  R0                  4S jjrSrg)_ExecOrderTracerZ   r-   Nc                     S U l         g r/   	exec_info)r6   s    r   r7   _ExecOrderTracer.__init__[   s	    37r   r   r,   c              #     #    [        U5      U l        UR                  nUR                  n[        R
                  " U R                  X0R                  5      Ul        [        UR                  5       5      n[        R
                  " U R                  UU R                  U5      Ul         S v   X1l        XAl        g ! X1l        XAl        f = f7fr/   )
r*   r>   call_modulecreate_proxy	functoolspartial_patched_call_moduler   named_parameters_patched_create_proxy)r6   r   r,   orig_call_moduleorig_create_proxyfqn_to_params         r   patch_tracer_ExecOrderTracer.patch_tracer^   s     '4!--"//&..%%'7
 K88:;'//&&NN	
	4!1"3 "2"3s   B$C	'B8 +C	8CC	rA   r>   r"   forwardargs.kwargsc                 n   UR                   R                  U5        [        UR                  5       5      nUR                  nU(       aG  XR
                  ;   d   S5       eUR
                  UR                     R                  [        X75      5        Un	X2l        / UR
                  U'   U" X4XV5      n
Xl        U
$ )a  
Overrides ``call_module`` to save execution information to
``exec_info``. Note that ``call_module`` is called during symbolic
tracing for each non-root module.

Args:
    call_module (Callable): Original ``call_module`` to override.
    exec_info (_ExecutionInfo): Used to record execution information.
    module (nn.Module): Module corresponding to this ``call_module``.
    forward (Callable): ``forward()`` method of ``module`` to be called
        for this ``call_module``.
    args (Tuple[Any, ...]): Positional arguments for ``forward``.
    kwargs (Dict[str, Any]): Keyword arguments for ``forward``.

Returns:
    Same return value as ``call_module``.
zPThe current module should have already been processed by a patched `call_module`)r1   appendr&   rF   r0   r2   r    )r6   rA   r>   r"   rM   rN   rO   r#   r0   prev_curr_moduleoutputs              r   rE   %_ExecOrderTracer._patched_call_modules   s    6 	&&--f5F3356++"G"GG bG 11)2G2GHOO5 ' &8:	--f5Vd; 0r   rB   rJ   kindtargetname	type_exprproxy_factory_fnc           	         U" XEXgXU
5      nUR                   nUS;   Ga  UGb  / nU H  n[        U[        R                  R                  5      (       d  M.  UR
                  R                  U;   d  MJ  X>R
                  R                     nUR                  UR
                  R                  U45        XR                  ;  d  M  UR                  R                  U5        UR                  R                  U5        M     U(       a'  UR                  U   R                  [        X5      5        U$ US:X  a  [        UR                  5       5      nU(       a'  UR                  U   R                  [        X5      5        U HM  u  nnXR                  ;  d  M  UR                  R                  U5        UR                  R                  U5        MO     U$ )a  
Overrides ``create_proxy`` to save execution information to
``exec_info``. Note that ``create_proxy`` is called during symbolic
tracing for each leaf function/method/module.

Args:
    create_proxy (Callable): Original ``create_proxy`` to override.
    exec_info (_ExecutionInfo): Used to record execution information.
    fqn_to_param (Dict[str, nn.Parameter]): ``dict`` version of the
        root module's ``named_parameters()`` with FQN as key and
        parameter as value.
    kind (str): Kind of the target method ('call_function',
        'call_method', 'get_attr', 'call_module', 'placeholder', or
        'output'). See :class:`torch.fx.Graph` for details. This is
        passed to ``create_proxy``.
    target (torch.fx.node.Target): Contains the string name of the
        function/method/module. This is passed to ``create_proxy``.
    args (Tuple[Any, ...]): Positional arguments for the function/
        method/module. This is passed to ``create_proxy``.
    kwargs (Dict[str, Any]): Keyword arguments for the function/method/
        module. This is passed to ``create_proxy``
    name (Optional[str]): An optional string name for the ``Node``
        created in ``create_proxy``. This is passed to
        ``create_proxy``.
    type_expr (Optional[Any]): An optional type annotation representing
        the Python type that the output of the node has. This is passed
        to ``create_proxy``.
    proxy_factory_fn (Callable[[torch.fx.Node], torch.fx.Proxy]):
        An alternative proxy constructor used in ``create_proxy``. This
        is passed to ``create_proxy``.

Returns:
    torch.fx.Proxy: Created ``Node`` wrapped in a ``Proxy`` object.
)call_functioncall_methodrA   )r0   
isinstancer   r   ProxynoderV   rQ   r5   addr3   r2   r    r&   rF   )r6   rB   r>   rJ   rU   rV   rN   rO   rW   rX   rY   proxyr0   r#   argparam_s                    r   rG   &_ExecOrderTracer._patched_create_proxy   s   ` $9I
  ++33?AC"377HHOO|; ,XX__ =$++SXX__e,DE (@(@@%4488?%99@@G    99+FMM'B  ]" < < >?L55kBII#K> )5 8 88,,0071188? ) r   r=   )r-   N)NNN)r   r   r   r   r7   r   r   r   r   r$   r%   rK   r   r*   r'   r   r   r   rE   r(   r_   Targetr	   Noder^   rG   r   r   r   r   r:   r:   Z   s~   8 4588?? 4 4 4(** "*
 		* * CHo* S#X* 
*l ##'PTOO "O 3,-	O O $$O CHoO S#XO smO C=O #8UXX]]OUXX^^,K#LMO 
O Or   r:   )rC   
contextlibr   dataclassesr   r   typingr   r   r   r	   r   torch.nnr$   r   r    r*   r:   r   r   r   <module>rl      sV     % ( 6 6   3 3 3.1j 1.7 7@T Tr   