U
    Jc'                     @   sJ  d dl Z d dlZd dlmZmZ d dlmZmZmZm	Z	m
Z
mZmZ d dlZdgZeG dd dZeG dd dZejjedd	d
Zdeeeeejjf eejjjeedf eeef ee ee eejjgejjf ejjdddZeeejjedef eedf eeef edddZe jejjejjee	dddZdS )    N)	dataclassfield)AnyCallableDict	GeneratorListOptionalTupleTracingConfigc                   @   s@   e Zd ZU dZej Zejjed< dZ	e
eeef  ed< dS )r   a  
    Configurations used in ``ParamExecOrderWrapPolicy`` for symbolic tracing of
    a model.

    Args:
        tracer (torch.fx.Tracer): An instance of ``torch.fx.Tracer`` that will
            be used to perform symbolic tracing. ``tracer`` is default to be
            ``torch.fx.Tracer()``, but can also be instance of some child class
            of ``torch.fx.Tracer``. For example, one may want to use
            ``HFTracer`` for models in Transformers: .. _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 forward
            function. ``concrete_args`` allows one to partially specialize the
            forward function, including removing control flow or data
            structures. ``concrete_args`` is also the argument used in
            :meth:`~torch.fx.Tracer.trace`.
    tracerNconcrete_args)__name__
__module____qualname____doc__torchfxTracerr   __annotations__r   r	   r   strr    r   r   J/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/fsdp/_symbolic_trace.pyr      s   
c                	   @   s|   e Zd ZU dZejjed< eejj ed< e	ejjee
ejjee
eejjf  f  f ed< eedZeejj ed< dS )_ExecutionInfoa  
    Contains the execution order information in the model forward pass.

    Attributes:
        current_module: record the module that is currently being traced.

        module_forward_order: a list of modules, where the ordering is based on
            when their forward function is called. ``module_forward_order``
            includes the info of how many times a module is called + used to
            check the forward order in different iterations.

        param_exec_order: a list of parameters ordered based on their execution
        order.

        module_to_execution_infos: a dict that maps each module to a list of
            tuples each containing a module and a list of named parameters.
            ``module_execution_info_dict`` is used as the parameter execution
            order info. For a given module, each tuple: 1. either contains this
            module and part of its ``named_parameters`` that will be executed
            together, 2. or contains one of its child modules and all of the
            child module's ``named_parameters``. The list of tuples is ordered
            based on the parameter execution order.
    current_modulemodule_forward_ordermodule_to_execution_infos)default_factoryparam_exec_orderN)r   r   r   r   r   nnModuler   r   r   r
   r   	Parameterr   listr   r   r   r   r   r   %   s   
"r   )root_modulereturnc                 C   s   t | | g| g idS )z
    Create an instance of _ExecutionInfo with initialization based on
    ``root_module``.

    Args:
        root_module (torch.nn.Module): the module to get the execution
        information via ``tracer.trace()`` inside ``_patch_tracer``.
    )r   r   r   )r   )r#   r   r   r   _init_execution_infoH   s
    	r%   .)create_proxyexecution_infoprefixed_param_name_to_paramkindtargetargskwargsname	type_exprproxy_factory_fnr$   c
                 C   s   | |||||||	}
|j }|dkr|dk	rg }|D ]V}t|tjjr2|jj|kr2||jj }||jj|f |t|j	kr2|j	| q2|r|j
| ||f nT|dkrt| }|r|j
| ||f |D ]"\}}|t|j	kr|j	| q|
S )aH  
    Override of :meth:`~torch.fx.Tracer.create_proxy`. ``Tracer.create_proxy``
    is called in symbolic tracing for each leaf function/method/module. This
    override intercepts the recording of each of these operations to update
    ``execution_info.module_to_execution_infos``.

    Args:
        create_proxy (Callable):
            The ``create_proxy`` function to be patched.
        execution_info (_ExecutionInfo):
            Used to record the execution information.
        prefixed_param_name_to_param (Dict[str, torch.nn.Parameter]):
            A dict that maps each prefixed parameter name to the parameter.
        kind (str):
            The type of the target method. One of 'call_function',
            'call_method', 'get_attr', 'call_module', 'placeholder', or
            'output'. The semantics of these opcodes are described in the
            ``torch.fx.Graph`` docstring. This is the input to ``create_proxy``.
        target (torch.fx.node.Target):
            Contains the string name of the method. This is the input to
            ``create_proxy``.
        args (Tuple[Any, ...]):
            Arguments of the method. This is the input to ``create_proxy``.
        kwargs (Dict[str, Any]):
            Keyword arguments of the method. This is the input to
            ``create_proxy``.
        name (Optional[str]):
            An optional string name for the ``Node`` created in
            ``create_proxy``. This is the input to ``create_proxy``.
        type_expr (Optional[Any]):
            An optional type annotation representing the Python type the output
            of a node will have. This is the input to ``create_proxy``.
        proxy_factory_fn (Callable[[torch.fx.Node], torch.fx.Proxy]):
            An alternative proxy constructor used in ``create_proxy``. This is
            the input to ``create_proxy``.
    )call_functionZcall_methodNcall_module)r   
isinstancer   r   Proxynoder*   appendsetr   r   r"   named_parameters)r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   proxymodulenamed_paramsargparam_pr   r   r   _patched_create_proxyX   s.    0
r?   )r1   r'   r9   forwardr+   r,   r$   c           	      C   sh   |j | t| }|r:|j|j |t| f |j}||_g |j|< | ||||}||_|S )ag  
    Override of :meth:`~torch.fx.Tracer.call_module`. ``Tracer.call_module`` is
    called in symbolic tracing for each non-root module. This override
    intercepts the recording of each operation to update
    ``execution_info.module_forward_order`` and
    ``execution_info.module_to_execution_infos``.

    Args:
        call_module (Callable):
            The ``call_module`` function to be patched.
        execution_info (_ExecutionInfo):
            Used to repord the execution information.
        module (torch.nn.Module):
            The module for which a call is being emitted.
        forward (Callable[..., Any]):
            The ``forward()`` method of the ``torch.nn.Module`` to be invoked.
        args (Tuple[Any, ...]):
            ``args`` of the module callsite.
        kwargs (Dict[str, Any]):
            ``kwargs`` of the module callsite.
    )r   r5   r"   r7   r   r   )	r1   r'   r9   r@   r+   r,   r:   Zprev_current_moduleoutputr   r   r   _patched_call_module   s    
rB   )r   r#   r'   r$   c                 c   sX   | j }| j}tt||| _ t| }tt|||| _z
dV  W 5 || _ || _X dS )a  
    Within the context manager, patches the input tracer so that during
    ``tracer.trace()``, the forward order of all modules and the parameter
    execution information are recorded. The patches of the input tracer will be
    removed after the context manager exits.

    Args:
        tracer (torch.fx.Tracer): the input ``tracer`` whose member functions
            will be patched within the context manager.
        root_module (torch.nn.Module): the top-level module to be traced
            and should not contain any FSDP modules.
        execution_info (_ExecutionInfo): used to record the execution order
            information when performing ``tracer.trace()`` within the context
            manager.
    N)r1   r&   	functoolspartialrB   dictr7   r?   )r   r#   r'   Zoriginal_call_moduleZoriginal_create_proxyr(   r   r   r   _patch_tracer   s$         
rF   )NNN) 
contextlibrC   Zdataclassesr   r   typingr   r   r   r   r   r	   r
   r   __all__r   r   r   r    r%   r   r!   r   r4   ZTargetNoder3   r?   rB   contextmanagerr   rF   r   r   r   r   <module>   sP   $"   

K


.