
    Vh                       d dl mZ d dlZd dlZd dlZd dlZd dlmZmZm	Z	 d dl
Z
d dlZ
d dlmZmZ d dlmZ e	r
d dlmZmZmZ eeef   Z	 ej4                  Z	 eeeeef   f   Z	 eeef   Z	  G d d      Z G d	 d
      Z 	 d	 	 	 	 	 ddZ!ddZ" G d dejF                        Z$ G d de$      Z% G d de$      Z& G d dejN                        Z(y)    )annotationsN)AnyFinalTYPE_CHECKING)_passdiagnostics)_pytree)	GeneratorIteratorSequencec                     e Zd ZU dZded<   ded<   ded<   	 	 	 	 	 	 ddZedd	       Zedd
       Zedd       Z	edd       Z
edd       ZddZddZddZedd       Ze	 	 	 	 dd       Ze	 	 	 	 dd       Ze	 	 	 	 dd       Zy)_ModuleMetaa  Meta information about a module.

    This class is used to represent the module information in a more structured way.
    It parses raw module information from a single item from
    `node.meta["nn_module_stack"].items()`.

    See the uses of `from_raw_meta`, `from_fx_tracer_produced_raw_meta`, and
    `from_dynamo_produced_raw_meta` for how to create an instance.

    Attributes:
        _module_class: The class of the module. E.g. `torch.nn.module.sparse.Embedding`.
        _module_name: The name of the module. E.g. `L__self___h_1_mlp_c_proj`.
        _raw_meta: The raw meta '(module_name, node.meta["nn_module_stack"][module_name])'.
    zFinal[type | str | None]_module_classz
Final[str]_module_namezFinal[tuple[Any, Any]]	_raw_metac                .    || _         || _        || _        y N)r   r   r   )selfmodule_namemodule_classraw_metas       ]/home/dcms/DCMS/lib/python3.12/site-packages/torch/onnx/_internal/fx/passes/modularization.py__init__z_ModuleMeta.__init__3   s     ()!    c                @    | j                   }|j                  d      }|S )zHThe display name of the module.

        E.g. `h_1_mlp_c_proj`.
        
L__self___)r   removeprefix)r   names     r   module_display_namez_ModuleMeta.module_display_name=   s$       .r   c                    | j                   y| j                   }t        |t              r|j                  dz   |j                  z   }|j                  dd      S )z^Qualified name of the module class.

        E.g. `torch_nn_module_sparse_Embedding`.
         ._)r   
isinstancetype
__module____qualname__replace)r   mod_clss     r   qualified_module_class_namez'_ModuleMeta.qualified_module_class_nameH   sT     %$$gt$((3.1E1EEGsC((r   c                    | j                   yt        | j                   t              r| j                   j                  S | j                   S )z=Name of the module class.

        E.g. `Embedding`.
        r!   )r   r$   r%   __name__r   s    r   module_class_namez_ModuleMeta.module_class_nameU   sA     %d(($/%%...!!!r   c                    | j                   S )zFName of the module.

        E.g. `L__self___h_1_mlp_c_proj`.
        )r   r-   s    r   r   z_ModuleMeta.module_namea   s        r   c                    | j                   S )zrReturns the raw module meta data.

        I.e. (module_name, node.meta['nn_module_stack'][module_name]).
        )r   r-   s    r   r   z_ModuleMeta.raw_metai   s     ~~r   c                   t        |t              sy| j                  |j                  k(  xr | j                  |j                  k(  S NF)r$   r   r   r   r   others     r   __eq__z_ModuleMeta.__eq__q   sA    %-!3!33 :""e&9&99	
r   c                D    t        | j                  | j                  f      S r   )hashr   r   r-   s    r   __hash__z_ModuleMeta.__hash__y   s    T&&(:(:;<<r   c                <    d| j                    d| j                   dS )NzModuleMeta(name=z, class=))r   r   r-   s    r   __repr__z_ModuleMeta.__repr__|   s&    !$"3"3!4HT=O=O<PPQRRr   c                    t        ddd      S )z5Create an empty module meta representing root module.r!   N)r!   Nr   )clss    r   create_rootz_ModuleMeta.create_root   s     2tZ00r   c                &    |\  }}t        |||      S )zBCreate a module meta from raw meta produced by FX symbolic tracer.r=   )r>   r   r   r   s       r    from_fx_tracer_produced_raw_metaz,_ModuleMeta.from_fx_tracer_produced_raw_meta   s    
 %-!\;h??r   c                P    |\  }\  }}t        |j                  d      d   ||      S )z@Create a module meta from raw meta produced by FX dynamo tracer.@r   )r   split)r>   r   r   _qualified_namer   s        r   from_dynamo_produced_raw_metaz)_ModuleMeta.from_dynamo_produced_raw_meta   s3    
 8@44o|;,,S1!4lHMMr   c                H   t        |t              r6t        |      dk(  r(t        |d   t              rt        j                  |      S t        |t              r6t        |      dk(  r(t        |d   t              rt        j                  |      S t        dt        |             )N      zIUnknown type of raw meta item from node.meta['nn_module_stack'].items(): )r$   tuplelenr%   r   rA   rF   	TypeError)r>   r   s     r   from_raw_metaz_ModuleMeta.from_raw_meta   s     x'H"8A;- ??IIx'H"8A;. <<XFFWX\]eXfWgh
 	
r   N)r   strr   type | str | Noner   tuple[Any, Any]returnrN   )rR   rP   r4   objectrR   boolrR   intrR   r   )r   _FX_TRACER_NN_MODULE_META_TYPErR   r   )r   _DYNAMO_NN_MODULE_META_TYPErR   r   )r   z<_FX_TRACER_NN_MODULE_META_TYPE | _DYNAMO_NN_MODULE_META_TYPErR   r   )r,   r&   r'   __doc____annotations__r   propertyr   r*   r.   r   r   r5   r8   r;   classmethodr?   rA   rF   rM    r   r   r   r      s:    ,+%%"" (" "	"   
) 
) 	" 	" ! !  
=S 1 1 @5@	@ @ N2N	N N 
N
 

 
r   r   c                      e Zd ZU dZded<   	 d	 	 	 ddZddZddZddZddZ	dd	Z
	 	 	 	 dd
ZddZddZedd       ZddZedd       Zedd       Zedd       Zy) _ModuleStackMetaa  Meta information about the module call stack.

    This class is used to represent the module call stack information in a more
    structured way. It parses raw module stack information from `node.meta["nn_module_stack"]`.

    Example of raw module stack information:

        If produced by dynamo:

            {
                'L__self___h_1': (
                    "L['self'].h[1]",
                    <class 'transformers.models.gpt2.modeling_gpt2.GPT2Block'>
                ),
                'L__self___h_1_attn': (
                    "L['self'].h[1].attn",
                    <class 'transformers.models.gpt2.modeling_gpt2.GPT2Attention'>
                )
            }

        If produced by fx.symbolic_trace:

            {
                'h.1': <class 'transformers.models.gpt2.modeling_gpt2.GPT2Block'>,
                'h.1.attn': <class 'transformers.models.gpt2.modeling_gpt2.GPT2Attention'>
            }
    zFinal[list[_ModuleMeta]]_module_stackc                    g | _         |y t        j                  |      }|j                         D ]+  }|rd}| j                  t        j                  |             - y r2   )rb   copyitemspushr   rM   )r   nn_module_stack_metais_exported_programr   items        r   r   z_ModuleStackMeta.__init__   s_      '9912NN$ 	7D #&+#IIk//56	7r   c                ,    t        | j                        S r   rK   rb   r-   s    r   __len__z_ModuleStackMeta.__len__   s    4%%&&r   c                     | j                   |   S r   rb   )r   indexs     r   __getitem__z_ModuleStackMeta.__getitem__   s    !!%((r   c                ,    t        | j                        S r   )iterrb   r-   s    r   __iter__z_ModuleStackMeta.__iter__   s    D&&''r   c                2    t        | j                        dk(  S Nr   rk   r-   s    r   is_empty_or_rootz!_ModuleStackMeta.is_empty_or_root   s    4%%&!++r   c                h    | j                         rt        j                         S | j                  d   S )zReturns the top module meta in the stack. I.e., the meta for leaf module.

        Example:

            Consider the following module stack:

            stack = [GPT, block1, Attention_1, MLP]

            stack.top() == MLP
        )rv   r   r?   rb   r-   s    r   topz_ModuleStackMeta.top   s0       "**,,!!"%%r   c                    | j                         ry|j                         yt        |       t        |      k  ryt        |      D ]  \  }}| |   |k7  s y y)a  Determines if self is a superset of the provided module stack.

        I.e., If self includes all elements from the provided module stack, plus additional
        elements on top. If self is empty or root, this method always return False.

        Example:

            Consider the following module stack:

            stack_1 = [GPT, block1, Attention_1, MLP]
            stack_2 = [GPT, block1]

            stack_1.is_superset_of(stack_2) == True
            stack_2.is_superset_of(stack_1) == False

            stack_3 = [GPT, block2, Attention_1]

            stack_1.is_superset_of(stack_3) == False
            stack_3.is_superset_of(stack_1) == False
        FT)rv   rK   	enumerate)r   module_stacki
parent_keys       r   is_superset_ofz_ModuleStackMeta.is_superset_of   se    0   "((*2t9L))&|4 	MAzAw*$	 r   c                :    | j                   j                  |       y)z"Pushes a module meta to the stack.N)rb   appendr   module_metas     r   rf   z_ModuleStackMeta.push   s    !!+.r   c               V    t        |t              sy| j                  |j                  k(  S r2   )r$   ra   rb   r3   s     r   r5   z_ModuleStackMeta.__eq__$  s'    %!12!!U%8%888r   c                v    | j                   D ci c]  }|j                  d   |j                  d   ! c}S c c}w )zJReturns the raw module stack meta data, i.e. node.meta['nn_module_stack'].r   rI   )rb   r   r   s     r   r   z_ModuleStackMeta.raw_meta)  sE    
  $11
   #[%9%9!%<<
 	
 
s   $6c                "    d| j                    dS )NzModuleStackMeta(r:   rn   r-   s    r   r;   z_ModuleStackMeta.__repr__1  s    !$"4"4!5Q77r   c                6    | j                         j                  S )z2Returns the module display name of the top module.)ry   r   r-   s    r   r   z$_ModuleStackMeta.module_display_name4  s     xxz---r   c                6    | j                         j                  S )z:Returns the qualified module class name of the top module.)ry   r*   r-   s    r   r*   z,_ModuleStackMeta.qualified_module_class_name9  s     xxz555r   c                6    | j                         j                  S )z+Returns the module class of the top module.)ry   r   r-   s    r   r   z_ModuleStackMeta.module_class>  s     xxz'''r   N)T)rg   zO_FX_TRACER_NN_MODULE_STACK_META_TYPE | _DYNAMO_NN_MODULE_STACK_META_TYPE | Nonerh   rU   rV   )ro   rW   rR   r   )rR   zIterator[_ModuleMeta])rR   rU   rX   )r|   ra   rR   rU   )r   r   rR   NonerS   )rR   z"dict[str, tuple[str, type]] | NonerQ   )rR   rO   )r,   r&   r'   r[   r\   r   rl   rp   rs   rv   ry   r   rf   r5   r]   r   r;   r   r*   r   r_   r   r   ra   ra      s    8 ,+ %)77
 "7&')(,&%&% 
%N/9
 
 
8 . . 6 6 ( (r   ra   c                N    t        | j                  j                  d      |      S )Nnn_module_stackrh   )ra   metaget)noderh   s     r   _module_stack_meta_from_noder   D  s%     		'(>Q r   c                T    | j                  |d       | |xx   dz  cc<   | d| |    S )Nr   rI   r#   )
setdefault)module_namesr   s     r   _get_unique_module_namer   L  s9    K+"]!L5677r   c                  p    e Zd ZdZeej                  dd              Zeej                  dd              Zy)_IRNodear  Base class for IR nodes.

    IR nodes are used for Modularize pass only. They add a layer of abstraction on top of
    torch.fx.Node.

    [NOTE: Modularize Pass Implementation]
    The main job of the pass is to group `fx.Node`s that belong to the same `nn.Module`
    forward call, and then create `call_module` node and sub `fx.GraphModule` from them.
    Each `fx.Node` possesses an `nn_module_stack` meta data that contains information
    about the module call stack. See `_ModuleStackMeta` for examples.

    Analysis step
    -------------

    Each module call is identified by a set of base stack layers. For each module call,
    the pass creates a `_ModuleNode` and groups the sequence of nodes that shares the
    same base stack layers.

    For example,

        stack_of_node_0 = [GPT, block0]
        stack_of_node_1 = [GPT, block1]
        stack_of_node_2 = [GPT, block1, Attention1, MLP]
        stack_of_node_3 = [GPT, block1, Attention1]
        stack_of_node_4 = [GPT, block2]

    All nodes belong to the `GPT` module call, since they share the base stack layers [GPT].
    [node_1, node_2, node_3] are grouped for `GPT.block1`, because they share the base
    stack layers [GPT, block1]. And [node_2, node_3] for `GPT.block1.Attention1`, [node_0]
    for `GPT.block0`, and [node_4] for `GPT.block2` respectfully.

    After the analysis step, a hierarchical representation is generated.

    For above example, the representation is:

        _ModuleNode(GPT)
            _ModuleNode(block0)
                _LeafNode(node_0)
            _ModuleNode(block1)
                _LeafNode(node_1)
                _ModuleNode(Attention1)
                    _ModuleNode(MLP)
                        _LeafNode(node_2)
                _LeafNode(node_3)
            _ModuleNode(block2)
                _LeafNode(node_4)

    Construction step
    -----------------

    The second step is to build the actual `call_module` node and the sub `fx.GraphModule`.
    This is done recursively from the leaf `_ModuleNode` to the root.

    For example, the first submodule to be built is `GPT.block1.Attention1.MLP`. Below pair
    is generated from `_ModuleNode(MLP)`.

        fx.GraphModule(GPT.block1.Attention1.MLP)
            graph:
                node_2

        new_mlp_node = `call_module[GPT.block1.Attention1.MLP](...)`

    Next, the `GPT.block1.Attention1` submodule is built. Below is generated from
    `_ModuleNode(Attention1)`.

        fx.GraphModule(GPT.block1.Attention1)
            graph:
                new_mlp_node
                node_3

        new_attention1_node = `call_module[GPT.block1.Attention1](...)`

    Until every submodule is built, the new modularized `fx.GraphModule` is generated.

    Alternatives
    ------------

    The current algorithm adopts a top down approach. A bottom up approach is similar.
    In contrast to these two, an alternative flat order approach is also possible, where
    each node is traversed and copied to the corresponding submodule.

    The advantage of the current approach lies in the encapsulation of the fx.GraphModule
    construction for each individual submodule within a single `build_module` method, which
    can be called separately once the analysis phase is completed, making debugging more
    convenient.

    Regarding construction step, an alternative implementation is to utilize `fx.Interpreter`
    for traversing all the nodes under the flattened root module and copying the nodes
    into their respective submodule under construction. This approach is not adopted because

        1. It uses the flat order approach discussed above. This means one cannot individually
    construct a submodule and examine it while debugging.

        2. The graph execution functionality of `fx.Interpreter` is not necessary for the
    purpose of this pass. Ignoring that, `fx.Interpreter.run` achieves the same effect
    as a for loop over all the nodes.
    c                     y)z5The module stack meta data associated with this node.Nr_   r-   s    r   
stack_metaz_IRNode.stack_meta       	r   c                     y)z*The stack trace associated with this node.Nr_   r-   s    r   stack_tracez_IRNode.stack_trace  r   r   NrR   ra   rR   z
str | None)	r,   r&   r'   r[   r]   abcabstractmethodr   r   r_   r   r   r   r   R  sM    `D      r   r   c                      e Zd ZdZ	 	 	 	 ddZedd       Zedd       ZddZddZ	ddZ
ddZdd	Zdd
ZddZddZy)_ModuleNodea  Representing a sequence of fx.Nodes to be formed into a fx.GraphModule.

    This class encapsulates metadata and provides building block methods to construct this
    layered abstraction from a sequence of flat fx.Nodes.

    Attributes:
    - _stack_meta: Metadata of the module stack.
    - _nodes: List of IR nodes in the module.
    - _reference_root_module: Reference to the root flat fx.GraphModule instance.
    c                .    || _         g | _        || _        y r   )_stack_meta_nodes_reference_module)r   reference_root_moduler   s      r   r   z_ModuleNode.__init__  s     &%'!6r   c                    | j                   S r   r   r-   s    r   r   z_ModuleNode.stack_meta  s    r   c                P    | j                   sJ | j                   d   j                  S ru   )r   r   r-   s    r   r   z_ModuleNode.stack_trace  s"    {{{{{1~)))r   c                "    d| j                    dS )NzModuleNode(r:   r   r-   s    r   __str__z_ModuleNode.__str__  s    T--.a00r   c                4    | j                   |j                   k(  S )zIDetermines if the provided node pertains to the same module as this node.)r   r   r   s     r   is_same_module_asz_ModuleNode.is_same_module_as  s    $//11r   c                L    |j                   j                  | j                         S )zHDetermines if this node represents a parent module of the provided node.)r   r   r   s     r   is_parent_module_ofz_ModuleNode.is_parent_module_of  s    --doo>>r   c           	     ,   | j                  |      s|j                  dk(  r| j                  j                  |       y|j                  dk(  r| j                  j                  |       y| j	                  |      r| j                  r| j                  d   nd}t        |t              r4|j	                  |      s|j                  |      r|j                  |       yt        j                  | j                        }|j                  |j                  t        | j                                  t        | j                  |      }| j                  j                  |       |j                  |       yt        d| d|j                   d| j                   d      )	zAdds a leaf node to the module.

        The leaf node must belong to the same or a child module. This method will recursively
        construct _ModuleNode instance based on the stack_meta information of the leaf node.
        call_moduleplaceholderrx   NzNode z (z) does not belong to module r"   )r   fx_opr   r   r   r$   r   add_leaf_noderd   deepcopyr   rf   rK   r   AssertionErrorr   )r   	leaf_node	last_noder   s       r   r   z_ModuleNode.add_leaf_node  sM    !!),	=0PKKy)__- KKy)%%i0 ,0;;BDI)[1--i8..y9 ''	2 "]]4??;
	 4 4S5I JK'**	 ""9-''	2 	{"Y%9%9$::V##$A' r   c              #     K   | j                   D ]K  }t        |t              r|j                         E d{    ,t        |t              sJ |j
                   M y7 (w)zEReturns an iterator for the sequence of fx nodes this instance holds.N)r   r$   r   fx_nodes	_LeafNodefx_noder   s     r   r   z_ModuleNode.fx_nodes  sO     KK 	#D$,==?**!$	222ll"	#*s   3A A)A c                J   t        | j                               }t        |      dkD  sJ d       i t        |      dfd}|D ]B  }t	        j
                  ||j                         t	        j
                  ||j                         D t        j                               S )a  Extract module inputs from the sequence of fx nodes this instance holds.

        All node args that are produced by nodes outside of the module are considered module
        inputs. The order of returned module inputs is the same as the their use order.

        ### Known limitations

        The original ordering of module inputs is not preserved. There is no meta information
        to be found from the `fx.GraphModule` that can be used to recover the original ordering.

        Returns:
            Sequence of module inputs.
        r   .Cannot extract module inputs from empty nodes.c                d    t        | t        j                  j                        r| vrd | <   y y y r   )r$   torchfxNode)argmodule_inputsnode_sets    r   #_extract_arg_if_node_outside_modulezF_ModuleNode.module_inputs.<locals>._extract_arg_if_node_outside_module1  s/    #uxx}}-#X2E%)c" 3F-r   )r   r   )	listr   rK   setpytreetree_mapargskwargskeys)r   nodesr   r   r   r   s       @@r   r   z_ModuleNode.module_inputs  s     T]]_%5zA~OOO~35'*5z	*  	NDOO?KOO?M	N M&&())r   c                   t        | j                               }t        |      dkD  sJ d       i }t        |      |D ]&  }t	        fd|j
                  D              s"d||<   ( t        |j                               S )a!  Extract module outputs from the sequence of fx nodes this instance holds.

        All nodes that are used by nodes outside of the module are considered module
        outputs. The order of returned module outputs is the same as the their creation order.

        ### Known limitations

        The original ordering of module outputs is not preserved. There is no meta information
        to be found from the `fx.GraphModule` that can be used to recover the original ordering.

        Returns:
            Sequence of module outputs.
        r   r   c              3  &   K   | ]  }|v 
 y wr   r_   ).0userr   s     r   	<genexpr>z-_ModuleNode.module_outputs.<locals>.<genexpr>O  s     ?D4x'?s   N)r   r   rK   r   anyusersr   )r   r   module_outputsr   r   s       @r   r   z_ModuleNode.module_outputs:  sz     T]]_%5zA~OOO~46'*5z 	,D?DJJ??'+t$	, N'')**r   c                V   | j                   j                  }t        j                  j	                         }i dfd| j                         }|D ]R  }|j                  |j                  |j                        |<   t        j                  |j                        |   _
        T | j                  D ]b  }t        |t              r#|j                  }|j                  |      |<   7t        |t               sJ |j#                  |      }|j                         }	|j%                         }
t'        ||j(                  j*                        }| j,                  j/                  ||       |j1                  |t3        fd|	D                    }t5        |
      dkD  rt3        d |
D              |j                  d<   t7        |
      D ]  \  }}|j9                  t:        j<                  ||f|j                        }t        j                  |j                        |_
        t        j                  |j                  d         |j                  d<   |j                  d   j?                          ||<    n/||
d	   <   t        j                  |
d	   j                        |_
        |j@                  x}||j                  d
<   |j(                  jB                  }|J t        j                  |      |j                  d<   |j                  d   j?                          e |jD                  }tG        tI        tK        |                  jL                  dk7  rT| j%                         }
| j%                         D cg c]  }|   	 }}|jO                  t5        |      dk(  r|d	   n|      }t        j                  jQ                  | j,                  ||      }| j                   jR                  x}?tU        jV                  tT        jX                  j[                  |            |j                  d<   |S c c}w )ag  
        Constructs the fx.GraphModule for this node, registering submodules as necessary.

        Args:
            module_names: A dictionary of module names and their counts. This is used to
                generate unique module names for submodules. This should be an empty
                dictionary when the method is called on a root module.
        c                    |    S r   r_   )r   copy_envs    r   _arg_transformz0_ModuleNode.build_module.<locals>._arg_transform`  s    D>!r   )arg_transformc              3  .   K   | ]  } |        y wr   r_   )r   r   r   s     r   r   z+_ModuleNode.build_module.<locals>.<genexpr>  s     LtnT*Ls   rI   c              3  R   K   | ]  }|j                   j                  d        ! yw)valN)r   r   )r   
ref_outputs     r   r   z+_ModuleNode.build_module.<locals>.<genexpr>  s$      33=JOO''.3s   %'r   )r   	type_exprr   r   r   outputonnx)r   torch.fx.NoderR   r   ).r   r*   r   r   Graphr   r   r   r%   rd   r   r   r$   r   r   	node_copyr   build_moduler   r   r   r   r   add_submoduler   rJ   rK   r{   call_functionoperatorgetitempopitemr   r   r   nextrr   reversedopr   GraphModuler   r   GraphModuleOnnxMetaPackageInfofrom_python_class)r   r   r.   fx_graph
ref_inputsr   ir_noder   	submoduleref_submodule_inputsref_submodule_outputsunique_submodule_namesubmodule_noder}   r   getitem_noder   raw_module_stack_meta	new_nodesnew_outputsgraph_moduler   r   r   s                         @@r   r   z_ModuleNode.build_moduleS  s    !,,HH88>>#79	" '')
 	7D%11$))TYYGHTN"&))DII"6HTN	7 {{ >	=G'9-!//$,$6$6> %7 %! g{333,,\:I#*#8#8#: $+$:$:$<!$;g00DD%! ""001F	R &11%L7KLLN ()A--2 3AV3 .##E* &//D%E 8MAz#+#9#9 ((,a0",// $: $L
 )-		*//(BL% <@99"(9:<L%%&78 !%%&78@@B+7HZ(8" 6D.q12&*ii0Ea0H0M0M&N#  '222?5@##M2$+$6$6$?$?!(44459YY?T5UN 12 12::<}>	=@ NN	 Xi()*--9$($7$7$9!BFBUBUBWXJ8J/XKX??"%k"2a"7A[D xx++""H.?
 !,,999LF(-(A(A!!33LA)Lf%  Ys   0P&N)r   torch.fx.GraphModuler   ra   r   r   rQ   )r   r   rR   rU   )r   r   rR   r   )rR   z$Generator[torch.fx.Node, None, None])rR   zSequence[torch.fx.Node])r   dict[str, int]rR   r  )r,   r&   r'   r[   r   r]   r   r   r   r   r   r   r   r   r   r   r_   r   r   r   r     sn    	7%97GW7     * *12?*X#*8+2fr   r   c                  j    e Zd ZdZd	d
dZedd       Zedd       Zedd       Zedd       Z	ddZ
y)r   zRepresenting a single fx.Node.c                6    || _         t        ||      | _        y )Nr   )_noder   r   )r   r   rh   s      r   r   z_LeafNode.__init__  s    
7&9
r   c                .    | j                   j                  S )z!Syntax sugar for self.fx_node.op.)r  r   r-   s    r   r   z_LeafNode.fx_op  s     zz}}r   c                    | j                   S )z-Returns the fx.Node this instance represents.r  r-   s    r   r   z_LeafNode.fx_node  s     zzr   c                    | j                   S )z=Returns the module stack meta data associated with this node.r   r-   s    r   r   z_LeafNode.stack_meta  s     r   c                L    | j                   j                  j                  d      S )z2Returns the stack trace associated with this node.r   )r   r   r   r-   s    r   r   z_LeafNode.stack_trace  s     ||  $$]33r   c                "    d| j                    dS )Nz	LeafNode(r:   r	  r-   s    r   r   z_LeafNode.__str__  s    4::,a((r   NF)r   r   rh   rU   rQ   )rR   r   r   r   )r,   r&   r'   r[   r   r]   r   r   r   r   r   r_   r   r   r   r     s_    (
         4 4)r   r   c                  :     e Zd ZdZ	 d	 	 	 	 	 d fdZddZ xZS )
ModularizeaK  Transforms a flattened `fx.GraphModule` into a modular structure.

    In the flattened `fx.GraphModule`, each `nn.Module` forward call has been traced as
    a sequence of `fx.Node`s. All these `fx.Node`s are flattened and reside in the same
    `fx.GraphModule`. `fx.GraphModule` could be from `torch.export.ExportedProgram` or
    directly generated by `torch._dynamo.export` with torch.nn.Module.

    This pass generates a new `fx.GraphModule`. It groups the flattened `fx.Node`s that belong
    to the same `nn.Module` forward call into a sub `fx.GraphModule`. It then replaces the
    sequence of flattened `fx.Node`s with a single `call_module` node, which is linked with
    the sub `fx.GraphModule` by `node.target`. The sub `fx.GraphModule` is registered as a
    submodule of the new `fx.GraphModule`.

    The process is done based on information from the `nn_module_stack` metadata of each node, i.e.
    `node.meta["nn_module_stack"]`. For more implementation details, see [NOTE: Modularize Pass Implementation].

    An fx submodule under this context can typically be interpreted in three different ways:

        1. As an embodiment of an nn.Module class, which is considered stateless.
        Its execution path can vary depending on the configuration of module initialization,
        which should also be part of the inputs.

        2. As a representation of an nn.Module instance. It maintains the state initialized in the module.
        The execution path can vary based on actual input data.

        3. As a captured call of an nn.Module instance, where the execution path
        is set.

    The generality decreases along this list. Within the scope of this function, the pass
    creates fx submodules according to the third interpretation.

    The first interpretation is the most general case. It requires complex analysis and additional
    metadata and code information to construct its general form. Consider an example nn.Module
    that generates arbitrary submodules based on an initialization configuration file. It's impractical
    to extract this logic for the generated fx submodule to function with arbitrary configuration.

    The second interpretation demands less analysis and is sturdier than the
    first. In most use cases, it's equivalent to the third. It only differs in exceptional situations
    where a complex nn.Module instance is called multiple times, each with a different set of inputs
    leading to a unique execution branching path.

    The third interpretation is the most specific scenario. It necessitates the minimum
    analysis and creates the most stable representation. The drawback is that it
    generates more redundancy than the other two methods. If needed, a subsequent post-processing
    pass can be applied to consolidate completely identical functions and reduce duplication.

    ### Known constraints
    Two successive calls to the same module instance will be conflated. They are indistinguishable.
    This is due to limitations of the current fx metadata "nn_module_stack".

    [NOTE: Modularize pass ordering]
    This pass groups fx nodes into subgraphs that reside within the `call_module` fx node.
    Other fx passes (including some outside the exporter) might not recognize `call_module`.
    They may assume that all nodes are flattened. Hence it is recommended to invoke this pass
    as the last pre onnx export fx pass. If not for this consideration, this operation could
    potentially be relocated anywhere earlier in the pipeline.

    Example:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ONNX)
        >>> import torch
        >>> from torch.onnx._internal.fx import passes
        >>> from torch.onnx._internal.diagnostics import infra
        >>>
        >>> class CustomModule(torch.nn.Module):
        >>>     def __init__(self) -> None:
        >>>         super().__init__()
        >>>         self.embedding = torch.nn.Embedding(10, 32)
        >>>         self.relu = torch.nn.ReLU()
        >>>
        >>>     def forward(self, x):
        >>>         out = self.embedding(x)
        >>>         out = self.relu(out)
        >>>         return out
        >>>
        >>> class TestModule(torch.nn.Module):
        >>>     def __init__(self) -> None:
        >>>         super().__init__()
        >>>         self.layer = CustomModule()
        >>>         self.linear = torch.nn.Linear(32, 10)
        >>>
        >>>     def forward(self, x):
        >>>         out = self.layer(x)
        >>>         out = self.linear(out)
        >>>         return out
        >>>
        >>> gm, _ = torch._dynamo.export(TestModule(), aten_graph=True)(
        ...     torch.tensor([0, 1, 2])
        ... )
        >>> gm.print_readable()

        >>> gm = passes.Modularize(
        ...     infra.DiagnosticContext("test_context", "1.0"),
        ...     gm,
        ... ).run()
        >>> gm.print_readable()

    c                B    t         |   ||       || _        || _        y r   )superr   modulerh   )r   diagnostic_contextr  rh   	__class__s       r   r   zModularize.__init__A  s$     	+V4#6 r   c                   | j                   j                  j                          t        j                  j                  | j                   | j                   j                        }t        |t        d | j                              }| j                   j                  j                  D ](  }|j                  t        || j                               * |j                  i       S )N)rg   rh   r   )r  grapheliminate_dead_coder   r   r   r   ra   rh   r   r   r   r   )r   reference_moduleroot_module_noder   s       r   _runzModularize._runK  s     	--/ 88//T[[=N=NO&%)t?W?W
 {{((.. 	G**'t7O7OP	  ,,R00r   r  )r  zdiagnostics.DiagnosticContextr  r  rh   rU   )rR   r  )r,   r&   r'   r[   r   r  __classcell__)r  s   @r   r  r    s5    aN %*	797 %7 "	71r   r  r  )r   r   rh   rU   rR   ra   )r   r  r   rN   rR   rN   ))
__future__r   r   collectionsrd   r   typingr   r   r   r   torch.fxtorch.onnx._internal.fxr   r   torch.utilsr	   r   collections.abcr
   r   r   rJ   rN   r%   rY   OrderedDict$_FX_TRACER_NN_MODULE_STACK_META_TYPErZ   dict!_DYNAMO_NN_MODULE_STACK_META_TYPEr   ra   r   r   ABCr   r   r   	Transformr  r_   r   r   <module>r)     s   " 
    , ,   6 ) == "'sDy!1  e'2'>'> $ S#CsDy)9$9:  \$(.I)I$J ! JJ
 J
ZU( U(r 6;
.28mcgg m`w' wt) )B1 1r   