
    Ǆg 6                     b   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	 ddl
Z
ddlmZ dd	lmZmZmZmZmZmZmZmZmZ ddlZerd d
lmZ g dZ e	d       G d de             Z e	d      e G d d                    Zdedej:                  j<                  ddfdZ e	d      dedeeef   deeef   dee   fd       Z  e	d      	 	 ddedeeeef   deeeef   deeedeege!f         de!dee   fd       Z"	 	 ddedeeeef   deeeef   deeedeege!f         de!dee   fdZ#y)   )GraphModule)Graph)Node)symbolic_trace)compatibility    N)	dataclass)	AnyCallableDictList
NamedTupleOptionalSetUnionTYPE_CHECKING)InternalMatch)Matchreplace_patternreplace_pattern_with_filtersReplacedPatternsT)is_backward_compatiblec                   ,    e Zd ZU eed<   eeef   ed<   y)r   anchor	nodes_mapN)__name__
__module____qualname__r   __annotations__r        b/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/fx/subgraph_rewriter.pyr   r      s     LD$Jr!   r   Fc                   <    e Zd ZU eed<   eeef   ed<   ee   ed<   y)r   r   r   replacementsN)r   r   r   r   r   r   r   r    r!   r"   r   r      s"     LD$Jt*r!   r   gmreplacementreturnc                    | j                          t        |t              r|j                  j	                          dt
        j                  j                  dt        dt        t           fd}| j                  j                  D ]  }|j                  dk(  s|j                  dk(  s" || |j                        } |||j                        }|K|nt        j                  |      }t        |t
        j                  j                        r| j!                  |j                  |       t#        | |j                  |       t%        d|j                  d|j                   d	       | j                  j	                          y )
Nr%   targetr'   c                     |j                  d      \  }}}	 | j                  |      }t        ||d       }|S # t        $ r Y y w xY w)N.)
rpartitionget_submoduleAttributeErrorgetattr)r%   r)   module_path_	attr_namemodattrs          r"   try_get_attrz)_replace_attributes.<locals>.try_get_attr(   sW    $*$5$5c$:!Q		#%#3#3K#@C sIt,  		s   7 	AAcall_moduleget_attrzAttempted to create a "z-" node during subgraph rewriting with target zL, but the referenced attribute does not exist in the replacement GraphModule)delete_all_unused_submodules
isinstancer   graphlinttorchnnModulestrr   r
   nodesopr)   copydeepcopyadd_submodulesetattrRuntimeError)r%   r&   r5   nodegm_attrreplacement_attrnew_attrs          r"   _replace_attributesrK   "   s?   ##%+{+  # (3-   K77m#tww*'<"2t{{3G+KE
 " "-==)9:.@$$T[[(;BX6
 ##<dgg$226++ ?J$JK K1K< HHMMOr!   patternc                     t        | ||      }|D cg c]#  }t        |j                  |j                        % c}S c c}w )a  
    Matches all possible non-overlapping sets of operators and their
    data dependencies (``pattern``) in the Graph of a GraphModule
    (``gm``), then replaces each of these matched subgraphs with another
    subgraph (``replacement``).

    Args:
        ``gm``: The GraphModule that wraps the Graph to operate on
        ``pattern``: The subgraph to match in ``gm`` for replacement
        ``replacement``: The subgraph to replace ``pattern`` with

    Returns:
        List[Match]: A list of ``Match`` objects representing the places
        in the original graph that ``pattern`` was matched to. The list
        is empty if there are no matches. ``Match`` is defined as:

        .. code-block:: python

            class Match(NamedTuple):
                # Node from which the match was found
                anchor: Node
                # Maps nodes in the pattern subgraph to nodes in the larger graph
                nodes_map: Dict[Node, Node]

    Examples:

    .. code-block:: python

        import torch
        from torch.fx import symbolic_trace, subgraph_rewriter

        class M(torch.nn.Module):
            def __init__(self) -> None:
                super().__init__()

            def forward(self, x, w1, w2):
                m1 = torch.cat([w1, w2]).sum()
                m2 = torch.cat([w1, w2]).sum()
                return x + torch.max(m1) + torch.max(m2)

        def pattern(w1, w2):
            return torch.cat([w1, w2]).sum()

        def replacement(w1, w2):
            return torch.stack([w1, w2])

        traced_module = symbolic_trace(M())

        subgraph_rewriter.replace_pattern(traced_module, pattern, replacement)

    The above code will first match ``pattern`` in the ``forward``
    method of ``traced_module``. Pattern-matching is done based on
    use-def relationships, not node names. For example, if you had
    ``p = torch.cat([a, b])`` in ``pattern``, you could match
    ``m = torch.cat([a, b])`` in the original ``forward`` function,
    despite the variable names being different (``p`` vs ``m``).

    The ``return`` statement in ``pattern`` is matched based on its
    value only; it may or may not match to the ``return`` statement in
    the larger graph. In other words, the pattern doesn't have to extend
    to the end of the larger graph.

    When the pattern is matched, it will be removed from the larger
    function and replaced by ``replacement``. If there are multiple
    matches for ``pattern`` in the larger function, each non-overlapping
    match will be replaced. In the case of a match overlap, the first
    found match in the set of overlapping matches will be replaced.
    ("First" here being defined as the first in a topological ordering
    of the Nodes' use-def relationships. In most cases, the first Node
    is the parameter that appears directly after ``self``, while the
    last Node is whatever the function returns.)

    One important thing to note is that the parameters of the
    ``pattern`` Callable must be used in the Callable itself,
    and the parameters of the ``replacement`` Callable must match
    the pattern. The first rule is why, in the above code block, the
    ``forward`` function has parameters ``x, w1, w2``, but the
    ``pattern`` function only has parameters ``w1, w2``. ``pattern``
    doesn't use ``x``, so it shouldn't specify ``x`` as a parameter.
    As an example of the second rule, consider replacing

    .. code-block:: python

        def pattern(x, y):
            return torch.neg(x) + torch.relu(y)

    with

    .. code-block:: python

        def replacement(x, y):
            return torch.relu(x)

    In this case, ``replacement`` needs the same number of parameters
    as ``pattern`` (both ``x`` and ``y``), even though the parameter
    ``y`` isn't used in ``replacement``.

    After calling ``subgraph_rewriter.replace_pattern``, the generated
    Python code looks like this:

    .. code-block:: python

        def forward(self, x, w1, w2):
            stack_1 = torch.stack([w1, w2])
            sum_1 = stack_1.sum()
            stack_2 = torch.stack([w1, w2])
            sum_2 = stack_2.sum()
            max_1 = torch.max(sum_1)
            add_1 = x + max_1
            max_2 = torch.max(sum_2)
            add_2 = add_1 + max_2
            return add_2
    )r   r   )_replace_patternr   r   r   )r%   rL   r&   match_and_replacementsms        r"   r   r   R   s7    n .b';GCYZaEQ[[9ZZZs   (=match_filtersr   ignore_literalsc                      t        | ||||      S )a  
    See replace_pattern for documentation. This function is an overload with an additional match_filter argument.

    Args:
        ``match_filters``: A list of functions that take in
            (match: InternalMatch, original_graph: Graph, pattern_graph: Graph) and return a boolean indicating
            whether the match satisfies the condition.
            See matcher_utils.py for definition of InternalMatch.
    )rN   )r%   rL   r&   rQ   rR   s        r"   r   r      s    $ Bm_UUr!   c                   
 ddl m}m} |g }| j                  t	        |t
              r|j                  n(t	        |t              r|nt        |      j                  t	        |t
              r|j                  }n(t	        |t              r|}nt        |      j                  } |ddd|      }|j                        }	|	D 

cg c]  
t        
fd|D              r
 }	}
|j                  D cg c]  }|j                  dk(  s| }}i }g }|	D ]  }t        |j                        t        |      k(  sJ i }t        ||j                        D ]  \  }}t	        |t              r|j!                  ||      ||<   |||   k7  s4|j                  j#                  |      }||   |j                  |<   t%        |j&                  j)                               t%        |j&                  j+                               j#                  |         }||   |j&                  |<   |||<    t-               }|j.                  D ]  }|j1                  |j2                          |sJ d       t        |      d	k(  rt5        t7        |            }nj                  D ]
  }||v s|} n j9                        5  j;                  ||      }d d d        t	        t              r|f}|j+                         D cg c]  }||j                  vs| }}t        |j.                        t        |      k(  sJ t        |j.                  |      D ]  \  }}|j=                  |       |||<    t?        j                        D ]L  }|j                  dk7  s|j                  d
k7  s#|j&                  |   }| j                  jA                  |       N |jC                  tE        |jF                  d   |j&                  |              | jI                          t	        |tJ        jL                  jN                        rtQ        | |       |S c c}
w c c}w # 1 sw Y   xY wc c}w )Nr   )SubgraphMatcherr   FT)match_outputmatch_placeholderremove_overlapping_matchesrR   c              3   2   K   | ]  } |        y w)Nr    ).0match_filterrP   original_graphpattern_graphs     r"   	<genexpr>z#_replace_pattern.<locals>.<genexpr>  s"      2 A~}= 2s   placeholderz6The returning_nodes should have at least one user noder   output)r   r   r$   ))#torch.fx.passes.utils.matcher_utilsrU   r   r:   r9   r   r   r   matchallr@   rA   lenplaceholder_nodeszipr   getindexlistr   keysvaluessetreturning_nodesupdateusersnextiterinserting_before
graph_copyreplace_all_uses_withreversed
erase_nodeappendr   anchors	recompiler<   r=   r>   rK   )r%   rL   r&   rQ   rR   rU   r   replacement_graphmatcher_matchesrP   nreplacement_placeholdersmatch_changed_noderO   rb   val_maprngngn_indmap_key
user_nodesfirst_user_nodecopied_returning_nodesvreplacement_nodescopied_noderG   r\   r]   s             `                 @@r"   rN   rN      s6    S HHN';'	GU	#&w/55+{+'--	K	''*;7==m%SX9=`G$+MM.$AH  2#02 2 	
H  ,=+B+B\aaddmF[\\ ,. ?
 5**+s3K/LLLL$&2E4K4KL 
	!FB"d#044R<$"44::2>F6H6LE++F3"5??#7#7#9:4@V@V@X;Y;_;_`b;cdG/A"/EEOOG, 
	! !$
&& 	'Aagg&	'SSSzz?a"4
#34O $)) 
?&'O
 ,,_= 	[%3%>%>?PRY%Z"	[ ,d3&<%?" 5<NN4D(iqQVQhQhHh(i(i 5(()S1G-HHHH"5#8#8:PQ 	1OB$$[1%0r"	1 ]001 	(Dww-'DGGx,?__T*##B'	(
 	%%}}Q'//.	
s?
F LLN +uxx/B,!!m  ]T	[ 	[ )js*   	Q8QQ5Q5Q	QQ	)NF)$graph_moduler   r:   r   rG   r   _symbolic_tracer   _compatibilityr   rB   dataclassesr	   typingr
   r   r   r   r   r   r   r   r   r<   -passes.utils.matcher_with_name_node_map_utilsr   __all__r   r   r=   r>   rK   r   boolr   rN   r    r!   r"   <module>r      s   %   + )  ! ] ] ] L
Zd+ J   ,  e,
   --K -ehhoo -$ -` d+w[w[8[()w[ x,-w[ 
%[	w[ ,w[v e,
 VZ!VV8UK/0V x34V D?E5*I4*O!PQR	V
 V 

V -V0 VZ!y"y"8UK/0y" x34y" D?E5*I4*O!PQR	y"
 y" 

y"r!   