
     Ti                    @   % S r SSKJr  SSKrSSKrSSKrSSKJrJrJ	r	  SSK
rSSKJs  Jr  SSKJs  Jr  SSKJs  Jr  SSKJs  Jr  SSKJs  Jr  SSKJr  SSKJrJr  \	" S5      r\R:                  rSr\R@                   " S	 S
5      5       r!S S jr" " S S5      r# " S S5      r$    S!S jr% " S S\#5      r& " S S\RN                  5      r( " S S\(5      r)      S"S jr*S#S jr+\RX                  " \\RZ                  05      r.S\/S'   Sr0S\/S'    " S S5      r1g)$zRewrite rules for ONNX models.    )annotationsN)CallableSequenceTypeVar)ir)_tapeconvenienceTz!pkg.onnxscript.rewriter.rule_namec                  L    \ rS rSr% SrS\S'   S\S'   S\S'   S\S	'   S
\S'   Srg)ReplacementSubgraph#   z1A subgraph that will replace the matched pattern._basics.MatchResultmatchSequence[ir.Value]new_outputsSequence[ir.Node]	new_nodesnew_initializersz_tape.UsedOpsetsused_opsets N)__name__
__module____qualname____firstlineno____doc____annotations____static_attributes__r       `/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/onnxscript/rewriter/_rewrite_rule.pyr   r   #   s#    ;##  ((!!r   r   boolc                     g)zxA condition function that always returns True.

This is used when no condition function is provided for a rewrite rule.
Tr   )argskwargss     r   always_truer$   .   s    
 r   c                  ~    \ rS rSrSr    S
           SS jjrSS jrSSSS.             SS jjrS	rg)Pattern6   zA pattern that can be matched against nodes in an ONNX graph.

This class encapsulates pattern matching functionality, providing the ability to
match patterns against nodes without requiring replacement functionality.
Nc                   [        U[        R                  5      (       d  [        R                  " U5      nXl        U=(       d    [
        U l        [        U[        R                  5      (       a  X0l        O@Uc&  [        R                  " U R                  5      U l        OU" U R                  5      U l        X@l
        XPl        g)aQ  Create a pattern matcher.

Args:
    target_pattern: The _pattern_ir.GraphPattern that will be matched against the IR.
        If a callable is provided, it will be converted to a _pattern_ir.GraphPattern.
    condition_function: The condition function that will be used to check if
        the pattern match found should be rewritten.
    matcher: The pattern matcher that will be used to match the pattern.
        If not provided, a default matcher will be used.
    verbose: The verbosity level of the rule.
    name: An optional name for the pattern that will show up in verbose logging.
N)
isinstance_pattern_irGraphPattern_to_graph_pattern_target_patternr$   _condition_function_matcherPatternMatcherSimplePatternMatcher_verbosename)selftarget_patterncondition_functionmatcherverboser3   s         r   __init__Pattern.__init__=   s    , .+*B*BCC(::>JN-#5#D gx6677#M_$99$:N:NODM#D$8$89DM	r   c                @    U R                   (       a  U R                   $ S$ )NzAnonymous Patternr3   r4   s    r   __str__Pattern.__str__a   s     IItyy>+>>r   Tr8   check_nodes_are_removabletracerc                 ^ ^^^^ U(       a  US:  a  [        ST  35        Ub  UOT R                  nT R                  R                  UTTUUS9mT(       Ga  [        R
                  " UTTT5      nT R                  R                   HJ  nUR                  c  M  UR                  TR                  ;  d  M.  TR                  UR                  S5        ML     S
UUUU U4S jjn	S n
TR                  R                  5        HB  u  pUR                  c  M  U
" UR                  5      " X|5      nU(       a  M5  U	" USU 3U5      s  $    TR                  R                  5        HB  u  pUR                  c  M  U
" UR                  5      " X5      nU(       a  M5  U	" USU 3U5      s  $    U
" T R                  5      " U40 TR                  D6nU(       d	  U	" US	5      $ T(       a-  TR!                  T TTT[        R"                  R$                  5        T$ T(       a-  TR!                  T TTT[        R"                  R&                  5        T$ )  Check if the node matches the pattern and return the match result.

Args:
    model: The model containing the graph or function.
    graph_or_function: The graph or function to match against.
    node: The node to try to match the pattern against.
    verbose: The verbosity level of messages.
    check_nodes_are_removable: If True, validate that matched nodes can be safely removed.
    tracer: The tracer for debugging.

Returns:
    MatchResult if the pattern matches successfully and passes the condition function,
    None otherwise.
   z[match] N)r8   remove_nodesc                  > [        U [        R                  5      (       a'  TR                  U R                  U R
                  5        OTR                  X5        T(       a-  TR                  TTTT[        R                  R                  5        g)z4Local utility to handle check failures consistently.N)	r)   _basicsMatchResultfailreasonfailure_nodes_and_valueslogMatchStatusCONDITION_FAILED)check_resultdefault_messagefailure_objectgraph_or_functionr   noder4   rB   s      r   rJ   Pattern.match.<locals>.fail   sq    lG,?,?@@JJ$++$==
 JJ?JJ)++<< r   c                   ^  U 4S jnU$ )z4Encapsulates try-except pattern for check functions.c                    >  T" U 0 UD6$ ! [         R                   aP  n[         R                  " 5       nUR                  UR                  [        UR                  5      5        Us S nA$ S nAff = fN)rH   MatchFailureErrorrI   rJ   rK   listfailure_sources)r"   r#   eresultfs       r   wrapped0Pattern.match.<locals>.wrap_try.<locals>.wrapped   s^    & $1&11"44 &!(!4!4!6AHHd13D3D.EF%&s    A/AA*$A/*A/r   )r^   r_   s   ` r   wrap_tryPattern.match.<locals>.wrap_try   s    & r   z)Node-level check failed for pattern node z+Value-level check failed for pattern value zCondition function check failedrX   )printr2   r/   r   rH   MatchContextr-   inputsr3   bindingsbindnode_bindingsitemscheck_methodvalue_bindingsr.   rM   rN   SUCCESSNO_MATCH)r4   modelrS   rT   r8   rA   rB   contextvarrJ   ra   pattern_nodeir_noderP   pattern_valueir_valuecheck_match_resultr   s   ` ``  `          @r   r   Pattern.matchd   s   0 w{HTF#$$0'dmm##2 $ 
 **52CT5QG++2288'xxu~~5

388T2 3 & */)<)<)B)B)D%,,8#+L,E,E#Fw#XL'<#(G~V#  	 *E ,1+?+?+E+E+G' --9#+M,F,F#G#ZL'<#(I-Y$  	 ,H "*$*B*B!CG!^u~~!^%.0QRR

4!2D%ATATA\A\]LJJt.eW=P=P=Y=YZr   )r.   r/   r-   r2   r3   )NNr   N)r5   #_pattern_ir.GraphPattern | Callabler6   Callable | Noner7   ^_matcher.PatternMatcher | Callable[[_pattern_ir.GraphPattern], _matcher.PatternMatcher] | Noner8   intr3   
str | NonereturnNoner|   strrn   ir.ModelrS   ir.Graph | ir.FunctionrT   ir.Noder8   
int | NonerA   r    rB   _basics.MatchingTracer | Noner|   z_basics.MatchResult | None)	r   r   r   r   r   r9   r>   r   r   r   r   r   r&   r&   6   s     /3 ";" ,"	" " " 
"H? #*.04ii 2i 	i i $(i .i 
$i ir   r&   c                  ,    \ rS rSrSrSS jrSS jrSrg)	ReplacementPatternFunction   zThe replacement pattern that will replace the targeted pattern.

Attributes:
    function (Callable): The replacement function that will be used to replace the matched pattern.
c                    Xl         g rX   	_function)r4   functions     r   r9   #ReplacementPatternFunction.__init__   s    !r   c                    [        5       nU R                  " U40 UR                  D6nUc  g [        U[        5      (       d  U/n[        XUR                  UR                  UR                  5      $ rX   )	RewriterContextr   rf   r)   r   r   nodesinitializersr   )r4   r   ro   r   s       r   get_replacement*ReplacementPatternFunction.get_replacement   sd    !#nnW??+x00&-K"w/C/CWEXEX
 	
r   r   N)r|   r}   )r   r   r|   ReplacementSubgraph | None)r   r   r   r   r   r9   r   r   r   r   r   r   r      s    "	
r   r   c           
         U R                   nUR                   H9  u  p4X2;  a  Ub  UOSX#'   M  Uc  M  XBU   :w  d  M$  [        SU SX#    SU S35      e   g )N   zMultiple versions of opset z used. Expected version 
, but got .)opset_importsr   
ValueError)rS   deltaimportsdomainversions        r   _update_opset_importsr      ss      --G ,, )0)<g!GO W%?-fX 6$$+O#4JwiqJ  -r   c                     ^  \ rS rSr        S                     SU 4S jjjrSS jrSSS.           SS jjrSSSS.       SS	 jjrSS
 jrSr	U =r
$ )RewriteRule   NFc                   > U
(       a  U(       d  [        S5      e[        TU ]	  XXEU5        [        U[        5      (       d  [	        U5      nX l        Xpl        Xl        Xl        Xl	        g)aV  Create a rewrite rule.

Args:
    target_pattern: The _pattern_ir.GraphPattern that will be matched against the IR.
        If a callable is provided, it will be converted to a _pattern_ir.GraphPattern.
    replacement_pattern: The ReplacementPatternFunction that will be used to
        replace the matched pattern. If a callable is provided, it will be
        converted to a ReplacementPatternFunction.
    condition_function: The condition function that will be used to check if
        the pattern match found should be rewritten.
    matcher: The pattern matcher that will be used to match the pattern.
        If not provided, a default matcher will be used.
    verbose: The verbosity level of the rule.
    name: An optional name for the pattern that will show up in verbose logging.
    remove_nodes: If True, the matched nodes will be removed from the graph.
    graph_pre_visitor: A function that will be called before applying the
        rewriting to the top-level graph or a function.
    graph_post_visitor: A function that will be called after the rewriting
        is complete for a graph or function.
    as_function: If True, the matched nodes will be extracted into a model
        local function. This is only supported when remove_nodes=True and
        when the replacement subgraph has a single node, representing the
        function call.
z:as_function=True is only supported when remove_nodes=True.N)
r   superr9   r)   r   _replacement_patternrF   graph_pre_visitorgraph_post_visitoras_function)r4   r5   replacement_patternr6   r7   r8   r3   rF   r   r   r   	__class__s              r   r9   RewriteRule.__init__   sc    N |YZZ 	WtT-/IJJ"<=P"Q$7!(!2"4&r   c                @    U R                   (       a  U R                   $ S$ )NzAnonymous Ruler<   r=   s    r   r>   RewriteRule.__str__+  s     IItyy;+;;r   r8   rB   c          	        U R                  UUUUU R                  US9nU(       d  gU R                  R                  U5      nUc5  U(       a-  UR	                  U UUU[
        R                  R                  5        g[        UR                  5      U R                  R                  :w  a9  [        SU R                  R                   S[        UR                  5       S35      e[        X'5        [        UR                  U5        U$ )zTIf the node matches the pattern, then replace the node with the replacement pattern.r@   NzsNumber of outputs from replacement function does not match the number of outputs from the target pattern. Expected r   r   )r   rF   r   r   rM   rH   rN   REPLACEMENT_FAILEDlenr   r-   num_outputsr   r   graph)r4   rn   rS   rT   r8   rB   r   replacement_subgraphs           r   try_rewriteRewriteRule.try_rewrite.  s    

&*&7&7  
 #88HHO'

%'':: #//0D4H4H4T4TT 00<<=ZL`LlLlHmGnnoq 
 	/Fekk+?@##r   )commuter8   rB   c               4    [        U /US9R                  XUS9$ )Nr   r   )RewriteRuleSetapply_to_model)r4   rn   r   r8   rB   s        r   r   RewriteRule.apply_to_modelY  s+     tfg6EE6 F 
 	
r   c                z   ^  U 4S jnT R                   R                  5        Vs/ s H
  o!" U5      PM     sn$ s  snf )Nc                  > [        TR                  5      n[        U TR                  TR                  U" U 5      TR
                  TR                  TR                  TR                  TR                  TR                  5
      $ )zHReturn a shallow copy of self with node_pattern replaced by new_pattern.)typer/   r   r   r.   r2   r3   rF   r   r   r   )new_patternmatcher_classr4   s     r   replace_pattern,RewriteRule.commute.<locals>.replace_patternh  so     !/M))((k*		!!&&''   r   )r-   r   )r4   r   ps   `  r   r   RewriteRule.commuteg  s8    	" -1,@,@,H,H,JK,Jq",JKKKs   8)r   r   r   r   rF   )NNr   NTNNF)r5   rw   r   z%ReplacementPatternFunction | Callabler6   rx   r7   ry   r8   rz   r3   r{   rF   r    r   Callable[[], None] | Noner   r   r   r    r|   r}   r~   )rn   r   rS   r   rT   r   r8   r   rB   r   r|   r   )rn   r   r   r    r8   r   rB   r   )r|   Sequence[RewriteRule])r   r   r   r   r9   r>   r   r   r   r   __classcell__r   s   @r   r   r      s&   
 /3 !7;8<!3';3' C3' ,	3'
3' 3' 3' 3' 53' 63' 3' 
3' 3'j< #04)$)$ 2)$ 	)$ )$ .)$ 
$)$^ "04

 	

 
 .
L Lr   r   c                      \ rS rSrSrSSS jjr\R                  S 5       rSS jr	SSSS.             SS	 jjr
S
rg)PatternBasei|  ak  Base class for implementing pattern matching as a class.

This class encapsulates the pattern definition and condition checking
without the replacement functionality.

Example::

    class TransposePattern(PatternBase):
        def pattern(cls, op, x, perm):
            return op.Transpose(x, perm=perm)

        def check(cls, context, x: ir.Value, perm: ir.Attr) -> bool:
            if perm.is_ref():
                return False
            if perm.type == ir.AttributeType.INTS:
                if list(perm.as_ints()) == list(range(len(perm.as_ints()))):
                    return True
            return False
Nc                f    U=(       d    U R                   R                  U l        S U l        X l        g rX   )r   r   r3   _compiled_pattern_pattern_kwargs)r4   r3   r#   s      r   r9   PatternBase.__init__  s&    3DNN33	15%r   c                    [        S5      e)Nz6Method 'pattern' must be implemented by derived class.NotImplementedErrorr4   opr"   r#   s       r   patternPatternBase.pattern      !"Z[[r   c                ,    [         R                  " 5       $ )zaDefault check function that returns a _basics.MatchResult object with success always set to True.)rH   rI   r   s       r   checkPatternBase.check  s    ""$$r   Tr@   c          	         U R                   c<  [        U R                  U R                  4SU R                  0U R
                  D6U l         U R                   R                  UUUUUUS9$ )rD   r3   r@   )r   r&   r   r   r3   r   r   )r4   rn   rS   rT   r8   rA   rB   s          r   r   PatternBase.match  sv    2 !!)%,djj&/3yy&<@<P<P&D" %%++&? , 
 	
r   )r   r   r3   rX   )r3   r{   r|   r}   )r|   r   r   )r   r   r   r   r   r9   abcabstractmethodr   r   r   r   r   r   r   r   r   |  s    (& 	\ \% #*.04$
$
 2$
 	$
 $
 $($
 .$
 
$$
 $
r   r   c                     ^  \ rS rSrSr\S 5       r S	       S
U 4S jjjr\R                  S 5       r
S rS rSrU =r$ )RewriteRuleClassBasei  a  Base class for implementing rewrite rules as a class.

Example::

    class TransposeIdentity(RewriteRuleClassBase):
        def pattern(cls, op, x, perm):
            return op.Transpose(x, perm=perm)

        def check(cls, context, x: ir.Value, perm: ir.Attr) -> bool:
            if perm.is_ref():
                return False
            if perm.type == ir.AttributeType.INTS:
                if list(perm.as_ints()) == list(range(len(perm.as_ints()))):
                    return True
            return False

        def rewrite(cls, op, x: ir.Value, perm: ir.Attr | None = None):
            return op.Identity(x)

    # Then use
    # TransposeIdentity.rule()
    # to create a RewriteRule object.

c                    U " U0 UD6n[        UR                  UR                  UR                  UR                  UR
                  UR                  UR                  UR                  S9$ )N)r3   rF   r   r   r   )	r   r   rewriter   r3   rF   setupcleanupr   )clsr"   r#   instances       r   ruleRewriteRuleClassBase.rule  s`    ''NN!..&nn'// ,,	
 		
r   c                <   > [         TU ]  U5        X l        X0l        g rX   )r   r9   rF   r   )r4   r3   rF   r   r   s       r   r9   RewriteRuleClassBase.__init__  s     	(&r   c                    [        S5      e)Nz6Method 'rewrite' must be implemented by derived class.r   r   s       r   r   RewriteRuleClassBase.rewrite  r   r   c                    g)zrOptional setup function that can be overridden by derived classes.

Used to do per model/function initialization.
Nr   r=   s    r   r   RewriteRuleClassBase.setup      
 	r   c                    g)zmOptional cleanup function that can be overridden by derived classes.

Used to do per model/function cleanup.
Nr   r=   s    r   r   RewriteRuleClassBase.cleanup   r   r   )r   rF   )NTF)r3   r{   rF   r    r   r    r|   r}   )r   r   r   r   r   classmethodr   r9   r   r   r   r   r   r   r   r   s   @r   r   r     sx    2 
 
 W\''59'OS'	' ' 	\ \ r   r   c                  ^^^^ 0 m/ n/ mU  Hw  nU(       a?  [         R                  " UR                  UR                  UR                  UR
                  S9O[         R                  " 5       nUb  UTU'   UR                  U5        My     SUU4S jjmSS jmSUUU4S jjnU Vs/ s H
  ov" U5      PM     nnU V	s/ s H  n	T" U	5      PM     n
n	UTU-   U
4$ s  snf s  sn	f )z9Utility function to extract a subgraph out as a function.)r3   shaper   
doc_stringc                  > U c  g U T;  av  U R                   nUbX  [        R                  " SU5      n[        R                  " SS/ U/5      nTR	                  U5        UR
                  S   =TU '   nU$ [        SU  S35      eTU    $ )Nvalue Constantr   zValue z not found in value_map.)const_valuer   
AttrTensorNodeappendoutputsr   )r   r   
value_attr
const_noder]   constant_nodes	value_maps        r   
copy_value&_copy_for_function.<locals>.copy_value  s    =	!++K&]]7K@
WWRR*F
%%j1,6,>,>q,AA	% 6veW,DEFFr   c                    U R                  5       (       a  [        S5      eU R                  [        R                  R
                  [        R                  R                  1;   a  [        S5      eU $ )NzRefAttr not supported.zGraph attributes not supported.)is_refr   r   r   AttributeTypeGRAPHGRAPHS)attrs    r   copy_attr_value+_copy_for_function.<locals>.copy_attr_value.  sW    ;;== &&>??99))//1A1A1H1HII &&GHHr   c                Z  > U R                    Vs/ s H  nT	" U5      PM     nnU R                  R                  5        Vs/ s H  nT" U5      PM     nn[        R                  " U R
                  U R                  UUU R                  [        U R                  5      S U R                  U R                  U R                  R                  5       S9
nUR                  n[        U R                  5       H.  u  pgXV   T
U'   UR                  c  M  UR                  XV   l
        M0     U$ s  snf s  snf )N)overloadr   r   r3   r   metadata_props)re   
attributesvaluesr   r   r   op_typer  r   r   r3   r   r  copy	enumerate)rT   v
new_inputsnew_attributesnew_noder   ioutputr  r  r  s           r   	copy_node%_copy_for_function.<locals>.copy_node:  s    -1[[9[jm[
96:oo6L6L6NO6N/!,6NO77KKLL]]DLL)..335
 &&"4<<0IA +If{{&&,kk# 1 ' :Os   D# D()r   ir.Value | Noner|   r  )r
  ir.Attrr|   r  )rT   r   r|   r   )r   Valuer3   r   r   r   r   )re   r   r   function_inputsinput	new_valuer  rT   function_nodesr  function_outputsr  r  r  r  s              @@@@r   _copy_for_functionr%    s     +-I&(O$&N  HHZZkkZZ ++	  	 (Iey)     
 , 388%$io%N8/67w!
1w7^n<>NOO 97s   $C;Cc                X    U R                   nSn [        U5      nXU4U;  a  U$ US-  nM  )zGet a new overload for the given domain and name.

Args:
    model: The model to which the new overload will be added.
    domain: The domain of the new overload.
    name: The opname of the new overload.

Returns:
    The new overload name.
r   )	functionsr   )rn   r   r3   existing_functionsr  overload_names         r   _get_new_overloadr*  U  sA     H
H-(0BB  A	 r   zmetadata_merger.MetadataMerger_default_metadata_mergerTmerge_metadatac                  |    \ rS rSrSS.SS jjrSS jrSS.         SS jjrSSS	.       SS
 jjrS rSr	g)r   is  Fr   c          	        U(       d  [        S5      eU(       aF  [        [        R                  R	                  U Vs/ s H  o3R                  5       PM     sn5      5      nXl        [        S U 5       5      U l        g s  snf )Nz$rules must contain at least one rulec              3  B   #    U  H  oR                   (       + v   M     g 7frX   )rF   ).0r   s     r   	<genexpr>*RewriteRuleSet.__init__.<locals>.<genexpr>|  s     &O+<+<'<'<s   )	r   rZ   	itertoolschainfrom_iterabler   rulesanyremove_unused_nodes)r4   r6  r   r   s       r   r9   RewriteRuleSet.__init__t  sc    CDD66SX7YSX4SX7YZ[E
 $'&O&O#O 	 8Zs   A>c                N    U R                   R                   SU R                   S3$ )N())r   r   r6  r=   s    r   __repr__RewriteRuleSet.__repr__~  s$    ..))*!DJJ<q99r   N)rB   c               
   SnU R                    H&  nUR                  (       d  M  UR                  5         M(     U GH  nU R                    GH  nUR                  XXsUS9nUb  Ub  M  [        U[        5      (       d   eUR
                  (       a  [        U[        R                  5      (       a  U(       a  [        SU 35        M{  UR                  n	UR
                   H5  n
U
R                  U	;   d  M  U(       a  [        SU
R                   S35        M7     UR
                   H  n
XU
R                  '   M     [        R                  R                  UR                  5        UR                  (       Gae  [!        UR                  5      S:w  a  [#        S5      eUR                  S   nUR$                  nUR&                  n[)        XU5      nXl        [-        UR.                  R0                  5      nU Vs/ s H  nUU;   d  M  UPM     nn[3        UR4                  UUR.                  R6                  5      u  nnnU Vs1 s H  owR$                  iM     nnUR8                  nUR;                  5        VVs0 s H  u  nnUU;   d  M  UU_M     nnn[        R<                  " UUUUS9n[        R                  " XUUS	S
9nUUR>                  URA                  5       '   U(       a  UR                  (       a  UR                   S3OSn[        SU S35        [B        RD                  " UR.                  R0                  5        [        S5        [B        RD                  " UR                  5        [        S5        UR                  (       a0  UR                   H   nUR                  URF                  [H        '   M"     [J        RL                  " UWURN                  (       a  UR.                  R0                  O/ UR                  UR.                  R6                  URP                  5        [R        (       a4  [T        RW                  UR.                  R0                  UR                  5        US-  n  O   URX                  R[                  5        H  nUR\                  [        R^                  R`                  :X  a  XPRc                  UURd                  X4S9-  nMJ  UR\                  [        R^                  Rf                  :X  d  Mt  URd                   H  nXPRc                  UUX4S9-  nM     M     GM     U R                    H&  nURh                  (       d  M  URi                  5         M(     U$ s  snf s  snf s  snnf )aq  
Apply the rewrite rules to the given graph or function.

Args:
    model: The model to which the rewrite rules are applied.
    graph_or_function: The graph or function to which the rewrite rules are applied.
    verbose: The verbosity level. Defaults to None.
    tracer: The tracer for debugging. Defaults to None.

Returns:
    The number of rewrite rules applied.
r   r   z:Rewrites adding initializers not supported for functions: zInitializer z already exists.r   zOas_function=True is only supported for patterns with a single replacement node.)r   r   r   )r   r  z: r   z----zMatched Nodes----z++++Replacement Nodes++++z++++End Replacement Nodes++++)5r6  r   r   r)   r   r   r   Functionrc   r   r3   
onnxscript	optimizerbasic_constant_propagationr   r   r   r   r   r  r*  r  setr   r   r%  re   r   r   ri   Graphr'  
identifier	_ir_utilsdisplay_nodesr  RULE_NAME_TAGr	   replace_nodes_and_valuesrF   r   r,  r+  copy_merged_metadatar  r  r   r  r  _apply_to_graph_or_functionr   r	  r   )r4   rn   rS   r8   rB   countr   rT   r   r   initializer	call_noder   r3   r  unsorted_nodesnoriginal_nodesre   r   r   used_domainsparent_opset_importskr  used_opset_importsr   r^   r
  s                                r   rL  *RewriteRuleSet._apply_to_graph_or_function  s   ( JJD%%%&&(  &D

((dF )  =F$6!%)<====))!"3R[[AA #!"\]a\b c !#4#A#AL','='=&++|;& %[5E5E4FFV&W X$	 (>
 (-'='=9D[%5%56 (> $$??P###5??+q0(m  !& 2I&--F$,,D0EH)1& &)):):%;N1B%Z1BAa>FYa1BN%Z-?!((.%++:M:M.*FE7 GU-UndkknL-U+<+J+J()=)C)C)E*)EAlIZ1)E ' * HHuDVE F(%TVWA67EOOALLN3/3yydii[+bDD&789++EKK,=,=>56++EOO<9:
 99"__:>))((7 - 44%)-):):EKK%%OOKK''%% ">,AA))5?? 
w #| ..099 0 0 6 66==tzz7 >  E YY""2"2"9"99!%!A!A!5' "B "  ", 1 &T JJD&&&'')  E &[ .V*s   3
UU<U2U"
U"
r   c          	        [        U[        R                  5      (       d   e[        R                  R                  UR                  5        [        UR                  R                  5       5      nU R                  XR                  X#S9nU H4  n[        R                  R                  U5        XPR                  XX#S9-  nM6     U R                  (       a  [        R                  R                  U5        U$ )ao  Apply the rewrite rules in the set to the model.

Args:
    model: The model to which the rewrite rules are applied.
    verbose: The verbosity level of messages. Defaults to None.
    tracer: if specified, no changes are made to the model, only
        information about the best matches found is computed.

Returns:
    The number of applications of rewrite rules.
r   )r)   r   ModelrA  rB  rC  r   rZ   r'  r  rL  r8  )r4   rn   r8   rB   original_functionsrM  r   s          r   r   RewriteRuleSet.apply_to_model  s    $ %****77D "%//"8"8":;00;; 1 
 +H  ;;HE55 6  E +
 ##  44U;r   c              #  8   #    U R                    S h  vN   g  N7frX   )r6  r=   s    r   __iter__RewriteRuleSet.__iter__.  s     ::s   )r8  r6  )r6  r   r   r    r|   r}   r~   )
rn   r   rS   r   r8   r   rB   r   r|   rz   )rn   r   r8   r   rB   r   r|   rz   )
r   r   r   r   r9   r=  rL  r   r]  r   r   r   r   r   r   s  s    HM P: 15HH 2H
 H .H 
H\ #04!! 	!
 .! 
!Fr   r   )r|   r    )rS   r   r   r   )re   zSequence[ir.Value | None]r   r   r   r   )rn   r   r   r   r3   r   r|   r   )2r   
__future__r   r   dataclassesr3  typingr   r   r   onnxscript.optimizerrA  onnxscript.rewriter._basicsrewriterrH   onnxscript.rewriter._ir_utilsrG  onnxscript.rewriter._matcherr/   onnxscript.rewriter._pattern_irr*    onnxscript.utils.metadata_mergerutilsmetadata_mergerr   onnxscript.irr   r	   r
   Builderr   rI  	dataclassr   r$   r&   r   r   r   ABCr   r   r%  r*  MetadataMergercomma_separator_mergerr+  r   r,  r   r   r   r   <module>rq     sP   % " 
     - - 1 1 / / 5 5 : :  ,CL--
 4 " " "W Wt
 
,-6IDL' DLNG
#'' G
T?; ?DJP%JP.?JPJ\JPZ* <K;Y;YO::;< 8   | |r   