
     Ti                    ^   % S r SSKJr  SSKrSSKrSSKrSSKrSSKJr  SSK	J
r
JrJrJrJrJrJrJr  SSKJs  Jr  SSKJr  \" S5      r " S S	\\   5      r " S
 S\R2                  \\   5      r " S S\5      r " S S\5      r " S S\\R<                     5      r " S S\5      r \\!\"\\\!   \\"   \\   4   r# " S S\5      r$S6S jr% " S S5      r&\&" S5      r'\&" \" S5      5      r( " S S5      r)    S7S jr*\'q+S\,S'   \RZ                  S8S j5       r. " S  S!5      r/ " S" S#5      r0 " S$ S%\/5      r1 " S& S'\/5      r2 " S( S)\/5      r3\3" 5       r4 " S* S+\/5      r5 " S, S-\/5      r6 " S. S/\/5      r7   S9         S:S0 jjr8S;S1 jr9        S<S2 jr: " S3 S45      r;S=S5 jr<g)>zDThe Pattern IR: used to describe (source) patterns of rewrite rules.    )annotationsN)Mapping)AnyCallableIterableIteratorProtocolSequenceTypeVarUnion)irTc                  "    \ rS rSrSrSS jrSrg)Pattern   z_This is essentially a Predicate[T], that is, a Callable[[T], bool] bound to the name "matches".c                    g N selfitems     ^/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/onnxscript/rewriter/_pattern_ir.pymatchesPattern.matches    s        r   N)r   r   returnbool)__name__
__module____qualname____firstlineno____doc__r   __static_attributes__r   r   r   r   r      s    i+r   r   c                  h    \ rS rSrSr\R                  SS j5       r\R                  SS j5       rSr	g)	StringPattern#   z(Abstract base class for string patterns.c                    g r   r   r   s     r   r   StringPattern.matches&       r   c                    g r   r   r   s    r   __str__StringPattern.__str__*   r)   r   r   Nr   strr   r   r   r/   )
r   r   r    r!   r"   abcabstractmethodr   r,   r#   r   r   r   r%   r%   #   s7    2  	 r   r%   c                  @    \ rS rSrSrS	S jrS
S jrSS jrSS jrSr	g)StringConstantPattern/   z!Matches strings with given value.c                    Xl         g r   _valuer   values     r   __init__StringConstantPattern.__init__2       r   c                    XR                   :H  $ r   r7   r   s     r   r   StringConstantPattern.matches5   s    {{""r   c                    U R                   $ r   r7   r+   s    r   r,   StringConstantPattern.__str__8       {{r   c                    U R                   $ r   r7   r+   s    r   r:   StringConstantPattern.value;   rB   r   r7   N)r:   r/   r.   r0   )
r   r   r    r!   r"   r;   r   r,   r:   r#   r   r   r   r4   r4   /   s    +#r   r4   c                  6    \ rS rSrSrSS jrS	S jrS
S jrSrg)PrefixPattern?   z$Matches strings with a given prefix.c                    Xl         g r   r7   r9   s     r   r;   PrefixPattern.__init__B   r=   r   c                8    UR                  U R                  5      $ r   )
startswithr8   r9   s     r   r   PrefixPattern.matchesE   s    ,,r   c                     U R                    S3$ )N*r7   r+   s    r   r,   PrefixPattern.__str__H   s    ++a  r   r7   N)r:   r/   r   None)r:   r/   r   r   r0   )	r   r   r    r!   r"   r;   r   r,   r#   r   r   r   rF   rF   ?   s    .-!r   rF   c                  f    \ rS rSrSrSS.SS jjr\SS j5       r\SS j5       rSS jr	SS	 jr
S
rg)AttrPatternL   zLBase class for an attribute pattern. Matches any attribute value by default.Fcan_match_nonec                   Xl         X l        g r   )_name_can_match_none)r   namerU   s      r   r;   AttrPattern.__init__O   s    
-r   c                    U R                   $ r   rW   r+   s    r   rY   AttrPattern.nameS       zzr   c                    U R                   $ )z:Indicates whether this pattern can match a None attribute.rX   r+   s    r   rU   AttrPattern.can_match_noneW        ###r   c                    g)NTr   r   attrs     r   r   AttrPattern.matches\       r   c                b    U R                   b  U R                   $ S[        [        U 5      5      -   $ Nz
anonymous:rW   r/   idr+   s    r   r,   AttrPattern.__str___   '    !ZZ3tzzUBtH9UUr   )rX   rW   NrY   
str | NonerU   r   r   ro   r   r   re   zir.Attrr   r   r0   )r   r   r    r!   r"   r;   propertyrY   rU   r   r,   r#   r   r   r   rR   rR   L   s@    VCH .   $ $Vr   rR   c                  8   ^  \ rS rSrSrSS.SU 4S jjjrSrU =r$ )AttrVarc   zERepresents a pattern variable used to match against attribute values.FrT   c                   > [         TU ]  XS9  g )NrT   superr;   )r   rY   rU   	__class__s      r   r;   AttrVar.__init__f   s    =r   r   rn   )r   r   r    r!   r"   r;   r#   __classcell__rz   s   @r   ru   ru   c   s    OCH > > >r   ru   c                  D   ^  \ rS rSrSrSU 4S jjrSS jrS	S jrSrU =r	$ )
AttrConstantPatternu   zMatches attributes with given value.

Uses standard equality for matching. For list-valued attributes, the order of elements matters.
If order is immaterial, we need to define a separate pattern for that.
c                0   > [         TU ]  S 5        Xl        g r   )ry   r;   r8   )r   r:   rz   s     r   r;   AttrConstantPattern.__init__|   s    r   c                @   UR                   [        R                  R                  [        R                  R                  [        R                  R
                  1;   a+  [        UR                  5      [        U R                  5      :H  $ UR                  U R                  :H  $ r   )	typer   AttributeTypeINTSFLOATSSTRINGStupler:   r8   rd   s     r   r   AttrConstantPattern.matches   sr    99!!##$$
 
 $dkk(:::zzT[[((r   c                ,    [        U R                  5      $ r   r/   r8   r+   s    r   r,   AttrConstantPattern.__str__       4;;r   r7   )r:   SupportedAttrTypesrr   r0   )
r   r   r    r!   r"   r;   r   r,   r#   r|   r}   s   @r   r   r   u   s    )   r   r   c                   [        U [        5      (       a  U $ [        U [        5      (       a6  U R                  b  [	        S5      e[        U R                  U R                  S9$ [        U [        [        [        45      (       a  [        U 5      $ [        U [        5      (       aO  [        S U  5       5      (       a  [        U 5      $ [        S U  5       5      (       a  [        U 5      $ [	        S5      e[        S[        U 5       S35      e)zhRepresents promotion of values allowed as keyword-arguments in a pattern-builder call to an AttrPattern.zDPattern variables used in attributes must not have check_method set.rT   c              3  N   #    U  H  n[        U[        [        45      v   M     g 7fr   
isinstanceintfloat.0is     r   	<genexpr>#_to_attr_pattern.<locals>.<genexpr>   s     :Eqz!c5\**E   #%c              3  B   #    U  H  n[        U[        5      v   M     g 7fr   )r   r/   r   s     r   r   r      s     15az!S!!5s   z9Only lists of int/float/str can be used as an AttrPatternCannot convert z to AttrPattern)r   rR   Varcheck_method
ValueErrorru   rY   rU   r   r   r/   r   r
   all	TypeErrorr   )r:   s    r   _to_attr_patternr      s    %%%% )V  uzz%2F2FGG%#uc*++"5))%"":E:::&u--15111&u--TUU
od5k]/B
CCr   c                  b    \ rS rSrSrSSS jjrSS jrSS jrSS jrSS jr	SS jr
SS	 jrS
rg)OpsetPatternBuilder   a  Represents an opset pattern and a pattern builder.

(i) It is used to create a NodePattern (via OpPatternBuilder).
Example usage:
::

    z = op.Matmul(x, y)

Here, `op` is an instance of OpsetPatternBuilder and `op.Matmul` is an instance
of OpPatternBuilder, and  `op.Matmul(x, y)` is an instance of NodePattern.

(ii) It contains a domain pattern matched against the actual opset domain used in the
input model.
c                |    [        U[        5      (       a  [        U5      nXl        U(       a  / U l        g S U l        g r   )r   r/   r4   _domain_pattern_nodes)r   domainrecords      r   r;   OpsetPatternBuilder.__init__   s0    fc""*62F%46DKDKr   c                    U R                   $ r   )r   r+   s    r   domain_pattern"OpsetPatternBuilder.domain_pattern   s    ###r   c                    [        X5      $ r   )OpPatternBuilder)r   op_names     r   __getattr__OpsetPatternBuilder.__getattr__   s    ..r   c                ,    [        U [        U5      5      $ )z?This method is used to match against submodule ops with prefix.)r   rF   )r   rY   s     r   	submoduleOpsetPatternBuilder.submodule   s    mD&9::r   c                ,    [        U R                  5      $ r   )r/   r   r+   s    r   r,   OpsetPatternBuilder.__str__   s    4''((r   c                V    U R                   b  U R                   R                  U5        g g r   )r   append)r   nodes     r   add_nodeOpsetPatternBuilder.add_node   s#    ;;"KKt$ #r   c                J    U R                   c  [        S5      eU R                   $ )NzNodes were not recorded.)r   r   r+   s    r   nodesOpsetPatternBuilder.nodes   s"    ;;788{{r   )r   r   N)F)r   zStringPattern | strr   r   r   rP   )r   r%   )r   r/   r   r   )rY   r/   r   r   r0   )r   NodePatternr   rP   )r   Sequence[NodePattern])r   r   r    r!   r"   r;   r   r   r   r,   r   r   r#   r   r   r   r   r      s*    $/;)%r   r    z	pkg.torchc                  `    \ rS rSrSr      S	S jrSSSSSSS.           S
S jjrSrg)r      a  A utility class to build a NodePattern.

It is used primarily to create a NodePattern.
Example usage:
::

    z = op.Matmul(x, y)

Here, `op` is an instance of OpsetPatternBuilder and `op.Matmul` is an instance
of OpPatternBuilder, and  `op.Matmul(x, y)` is an instance of NodePattern.

c                    Xl         X l        g r   )pattern_builderr   )r   r   r   s      r   r;   OpPatternBuilder.__init__   s    
  /r   N   )_domain_version_outputs_allow_other_attributes_allow_other_inputs_checkc                  Ub  [        S5      eUc  U R                  R                  5       n	O,[        U[        5      (       a  [        U5      n	O[        S5      e[        U[        5      (       a  [        U5       V
s/ s H  n
S PM     nn
O7[        U[        5      (       a  [        S U 5       5      (       d  [        S5      eU Vs/ s H  n[        U5      PM     nnUR                  5        VVs0 s H  u  pU[        U5      _M     nnn[        U	U R                  UUUUUUS9nU R                  R!                  U5        UR"                  n[%        U5      S:X  a  US   $ U$ s  sn
f s  snf s  snnf )NzzThe pattern builder does not support '_version' keyword argument. Version restrictions should be handled by rewrite rules.z_domain must be a string.c              3  X   #    U  H   n[        U[        [        S 5      45      v   M"     g 7fr   )r   r/   r   )r   xs     r   r   ,OpPatternBuilder.__call__.<locals>.<genexpr>  s&      ;
6>Jq3T
+,,hs   (*z,_outputs must be an int or a list[str|None].allow_other_attributesallow_other_inputscheckr   r   )r   r   r   r   r/   r4   r   r   ranger
   r   _to_value_patternitemsr   r   r   r   outputslen)r   r   r   r   r   r   r   argskwargsopset_pattern_r   inputsrY   r:   
attributesnode_patternoutput_valuess                     r   __call__OpPatternBuilder.__call__   sk    K  ? 00??AM%%1':M 788h$$&+Ho6ooH6HHh//s ;
6>;
 8
 8
 KLL0451#A&5IOXd,U33
X"LL#:2	
 	%%l3$,,}" ##  / 7
 6Xs   ;E!E&/E+)r   r   )r   r   r   str | Pattern[str]r   rP   )r   ro   r   z
int | Noner   zint | list[str | None]r   bool | Noner   r   r   Callable | None)r   r   r    r!   r"   r;   r   r#   r   r   r   r   r      s    , $ 
	 ##+,/3+/"&0! 0! 	0!
 )0! "-0! )0!  0! 0!r   r   c                j   U b  [        U [        5      (       a  U $ [        U [        [        45      (       a  [	        U 5      $ [        U [
        5      (       a-  [        S U  5       5      (       a  [	        U 5      $ [        S5      e[        U 5      (       a
  [        SU S9$ [        S[        U 5       S35      e)a/  Promotes an input-value used to construct a NodePattern to a ValuePattern.

Example usage:
::
    x = op.MatMul(a, b)
    z = op.Add(x, 0)

In this example, `a, `b`, and `x` are ValuePatterns used to construct a NodePattern.
`0` is a constant (int) value, and is automatically promoted to a ValuePattern.

Note that this is a shorthand for creating a Constant pattern. The user can more
explicitly write this as:
::
    z = op.Add(x, op.Constant(0))

If a callable is provided, it will be converted to a ValuePattern with the callable as the check attribute.
Nc              3  N   #    U  H  n[        U[        [        45      v   M     g 7fr   r   r   s     r   r   $_to_value_pattern.<locals>.<genexpr>?  s     6Aqz!c5\**Ar   z5Only lists of int/float can be used as a ValuePatternr   r   z to ValuePattern)r   ValuePatternr   r   Constantr
   r   r   callabler   r   )r   s    r   r   r   &  s    ( 	yJq,//!c5\""{!X6A666A;PQQ{{D**
od1gY.>?
@@r   _pattern_builderc              #  (   #    [         nU q S v   Uq g 7fr   )r   )builderprev_builders     r   r   r   K  s      $L	#s   c                      \ rS rSrSrSSS.       SS jjrSS jr\SS j5       r\SS	 j5       r	\SS
 j5       r
SS jrS S jrS!S jrS"S jrS rS rS rS rS rS rS rS rS rS"S jrSrg)#r   iT  zBase class for all patterns that match against IR values.

This is used primarily to provide operator overloadings for arithmetic
operations, so that we can write patterns like `x + 1` and `1 + x`.
NFr   rU   c               6    Xl         X l        X0l        / U l        g r   )rW   r   rX   _uses)r   rY   r   rU   s       r   r;   ValuePattern.__init__[  s     
-46
r   c                @    A[        U R                  U R                  S9$ )Nr   )r   rW   r   r   node_maps     r   cloneValuePattern.cloned  s    DJJdkk::r   c                    U R                   $ r   r\   r+   s    r   rY   ValuePattern.nameh  r^   r   c                    U R                   $ r   r   r+   s    r   r   ValuePattern.check_methodl      {{r   c                    U R                   $ )z7Indicates whether this variable can match a None input.r`   r+   s    r   rU   ValuePattern.can_match_nonep  rb   r   c                    g r   r   r+   s    r   producerValuePattern.produceru  rg   r   c                    U R                   $ r   )r   r+   s    r   usesValuePattern.usesx  s    zzr   c                <    U R                   R                  X45        g r   )r   r   )r   r   indexs      r   
append_useValuePattern.append_use{  s    

4-(r   c                $    SU R                   < S3$ )NzValuePattern()r\   r+   s    r   __repr__ValuePattern.__repr__~  s    tzznA..r   c                ,    [         R                  X5      $ r   r   Addr   others     r   __add__ValuePattern.__add__      ##D00r   c                ,    [         R                  X5      $ r   r  r  s     r   __radd__ValuePattern.__radd__      ##E00r   c                ,    [         R                  X5      $ r   r   Subr  s     r   __sub__ValuePattern.__sub__  r  r   c                ,    [         R                  X5      $ r   r#  r  s     r   __rsub__ValuePattern.__rsub__  r!  r   c                ,    [         R                  X5      $ r   r   Mulr  s     r   __mul__ValuePattern.__mul__  r  r   c                ,    [         R                  X5      $ r   r+  r  s     r   __rmul__ValuePattern.__rmul__  r!  r   c                ,    [         R                  X5      $ r   r   Divr  s     r   __truediv__ValuePattern.__truediv__  r  r   c                ,    [         R                  X5      $ r   r3  r  s     r   __rtruediv__ValuePattern.__rtruediv__  r!  r   c                ,    [         R                  X5      $ r   )r   Powr  s     r   __pow__ValuePattern.__pow__  r  r   c                b    U R                   b  U R                   $ S[        [        U 5      5      -   $ ri   rj   r+   s    r   r,   ValuePattern.__str__  rm   r   )rX   r   rW   r   rY   ro   r   r   rU   r   r   rP   )r   dict[NodePattern, NodePattern]r   r   rp   r   r   rq   )r   zNodePattern | None)r   z!Sequence[tuple[NodePattern, int]])r   r   r  r   r0   )r   r   r    r!   r"   r;   r   rs   rY   r   rU   r	  r  r  r  r  r  r%  r(  r-  r0  r5  r8  r<  r,   r#   r   r   r   r   r   T  s     =AY^77*97RV7	7;     $ $)/111111111Vr   r   c                      \ rS rSrSrSS.               SS jjrSS jrSS jr\SS j5       r	\SS	 j5       r
SS
 jrSS jrSrg)r   i  a  Represents a pattern that matches against a Node.

This differs from a NodeOutputPattern in that it matches against a node (which
may produce 1 or more outputs), whereas a NodeOutputPattern matches against
a specific output of a node.

Args:
    domain: pattern to match against the domain of the node.
    op: pattern or string constant to match against the op_type of the node.
    inputs: sequence of ValuePatterns (or constants) to match against the inputs of the node.
    attributes: dictionary of attribute patterns to match against the attributes of the node.
    outputs: specifies pattern-variable-name for outputs (or None)
    allow_other_attributes: specifies whether other attributes (not mentioned in `attributes`)
      are allowed in the node.
Nr   c          	     X   Uc  SnUc  SnXl         [        U[        5      (       a  [        U5      OUU l        U V	s/ s H  n	[        U	5      PM     sn	U l        X@l        X`l        Xpl	        Xl
        [        U[        5      (       a0  [        U[        5      (       a  Sn
UR                  5       UU
4U l        OS U l        [        U5       VVs/ s H  u  p[        XU5      PM     snnU l        [        U R                  5       H  u  pUc  M
  UR!                  X5        M     g s  sn	f s  snnf )NTFr   )r   r   r/   r4   opr   r   r   r   r   r   r:   _op_identifier	enumerateNodeOutputPatternr   r  )r   r   rE  r   r   r   r   r   r   r   overloadr   rY   r  r:   s                  r   r;   NodePattern.__init__  s    ")%)"%!&/9"c/B/B'+5;<V(+V<$&<#"4b#:f6K#L#LHAD #'DHQRYHZ[HZWQ)$48HZ[ &dkk2LE   - 3' =  \s   D!D&c                   SR                  S U R                   5       5      nSR                  S U R                   5       5      nSR                  S U R                  R	                  5        5       5      n[        U R                  5      n[        U R                  5      nU(       a  U SU 3OUnU(       a  U SU 3OUnU SU SU S3$ )	N, c              3  8   #    U  H  n[        U5      v   M     g 7fr   r/   r   vs     r   r   &NodePattern.__str__.<locals>.<genexpr>  s     7;a3q66;   c              3  8   #    U  H  n[        U5      v   M     g 7fr   rN  rO  s     r   r   rQ    s     9LqCFFLrR  c              3  4   #    U  H  u  pU S U 3v   M     g7f)=Nr   )r   krP  s      r   r   rQ    s     N6Mda!AaSz6Ms   .z = z (r  )joinr   r   r   r   r/   rE  r   )r   r   r   r   rE  r   qualified_opinputs_and_attributess           r   r,   NodePattern.__str__  s    74;;77))9DLL99YYNdoo6K6K6MNN
\T[[!+1&2$'r=G6("ZL 9V#l^2.C-DAFFr   c                    U R                   $ r   )rF  r+   s    r   op_identifierNodePattern.op_identifier  s    """r   c                ,    [        U R                  5      $ r   )r/   rE  r+   s    r   op_typeNodePattern.op_type  s    477|r   c                    U R                   $ r   r  r+   s    r   r   NodePattern.check_method  r  r   c           
        U R                   R                  UR                  5      (       d-  UR                  SU R                    SUR                   S3U5      $ U R                  R                  UR                  5      (       d-  UR                  SU R                   SUR                   S3U5      $ U R
                  R                  5        H  u  p4UR
                  R                  U5      nUc*  UR                  (       d  UR                  SU S3U5      s  $ O4UR                  U5      (       d  UR                  SU SU SU S3U5      s  $ UR                  c  M  UR                  UR                  U5      (       a  M  Us  $    U R                  (       d:  UR
                   H*  nX0R
                  ;  d  M  UR                  SU S3U5      s  $    U$ )	zMatches the pattern represented by self against a node.

This is purely a local node-level match, and does not consider the subgraph rooted at the node.
We check the domain, op_type, and attributes of the node, but not the inputs.
zOpType mismatch: expected z, got rW  zDomain mismatch: expected z
Attribute z not found in node.z mismatch: expected z not expected in node.)rE  r   r`  failr   r   r   getrU   rY   bindr   )r   r   matchrY   attr_pattern
attr_values         r   r   NodePattern.matches  s    wwt||,,::,TWWIVDLL>KT  {{""4;;//::,T[[M}ANPT  #'//"7"7"9D,,T2J!#22 ::
4&8K&LdSS 3!))*55zz &:<.zlZ[\    ,zz,"3"3Z@@ L #: **. ::
4&8N&OQUVV (
 r   c                   U R                    Vs/ s H  o3b  UR                  U5      OS PM     nnU(       a   [        U5      S:X  d   S5       eUS   US   /nU R                   Vs/ s H  oUR                  PM     nn[        U R                  U R                  UU R                  UU R                  U R                  U R                  S9nXqU '   U$ s  snf s  snf )N   z<Internal error: commutative swap applies only to binary ops.r   r   r   )r   r   r   r   rY   r   r   rE  r   r   r   r   )r   r   swaprP  r   r:   r   copieds           r   r   NodePattern.clone  s    JN++V+Q1778$4?+Vv;!# N# Qi+F+/<<8<%::<8KKGGOO#'#>#>#66++	
  % W 9s   C%C)	r   rF  r   r   r   r   r   rE  r   )r   r%   rE  r   r   z+Sequence[int | float | ValuePattern | None]r   zdict[str, AttrPattern]r   zSequence[str | None]r   r   r   r   r   r   r0   )r   zir.OperatorIdentifier | NonerB  )r   zir.Noderh  _basics.MatchResultr   rq  )r   rA  rn  r   r   r   )r   r   r    r!   r"   r;   r,   r]  rs   r`  r   r   r   r#   r   r   r   r   r     s    4 "&).). ). <	).
 +). &). !,). (). ).VG#    $Lr   r   c                  l   ^  \ rS rSrSr S       S	U 4S jjjrS
S jr\SS j5       rSS jr	Sr
U =r$ )rH  i-  zRepresents a pattern that matches against a specific output of a Node.

This is the primary pattern used to match against computed values, that
is values computed using a specific op.
c                <   > [         TU ]  U5        Xl        X l        g r   )ry   r;   	_producer_output_index)r   r	  output_indexrY   rz   s       r   r;   NodeOutputPattern.__init__4  s     	!)r   c                L    XR                      R                  U R                     $ r   )rt  r   ru  r   s     r   r   NodeOutputPattern.clone;  s     '//0B0BCCr   c                    U R                   $ r   )ru  r+   s    r   rv  NodeOutputPattern.output_index?  s    !!!r   c                    U R                   $ r   )rt  r+   s    r   r	  NodeOutputPattern.producerC  s    ~~r   )ru  rt  r   )r	  r   rv  r   rY   ro   r   rP   )r   rA  r   rH  r   r   r   r   )r   r   r    r!   r"   r;   r   rs   rv  r	  r#   r|   r}   s   @r   rH  rH  -  s]     LP*#*36*>H*	* *D " " r   rH  c                  R   ^  \ rS rSrSrSSS.       S	U 4S jjjrS
S jrSrU =r$ )r   iG  zRepresents a pattern-variable.NFr   c               "   > [         TU ]  XUS9  g )Nr   rx   )r   rY   r   rU   rz   s       r   r;   Var.__init__J  s     	>Jr   c                T    [        U R                  U R                  U R                  S9$ )zBClones the pattern-variable, preserving its name and check method.r   )r   rY   r   rU   r   s     r   r   	Var.cloneO  s!    499D$5$5dFYFYZZr   r   r@  )r   rA  r   r   	r   r   r    r!   r"   r;   r   r#   r|   r}   s   @r   r   r   G  sK    ( =AY^KK*9KRVK	K K
[ [r   r   c                  :   ^  \ rS rSrSrSU 4S jjrSS jrSrU =r$ )AnyValueiT  z4Represents a pattern that matches against any value.c                $   > [         TU ]  S 5        g r   rx   )r   rz   s    r   r;   AnyValue.__init__W  s    r   c                    U $ r   r   r   s     r   r   AnyValue.cloneZ  s    r   r   )r   rP   )r   rA  r   r  r  r}   s   @r   r  r  T  s    > r   r  c                  n   ^  \ rS rSrSr  S       S	U 4S jjjrS
S jr\SS j5       rSS jr	Sr
U =r$ )r   ib  zBRepresents a pattern that matches against a scalar constant value.c                   > [         TU ]  S 5        [        U[        5      (       a  [	        U5      OUU l        X l        X0l        g r   )ry   r;   r   r
   listr8   _rel_tol_abs_tol)r   r:   rel_tolabs_tolrz   s       r   r;   Constant.__init__e  s5     	%/x%@%@d5ker   c                Z    A[        U R                  U R                  U R                  5      $ r   )r   r8   r  r  r   s     r   r   Constant.clonep  s     T]]DMMBBr   c                    U R                   $ r   r7   r+   s    r   r:   Constant.valuet  r  r   c                ,    [        U R                  5      $ r   r   r+   s    r   r,   Constant.__str__x  r   r   )r  r  r8   )gh㈵>g:0yE>)r:   z-int | float | Sequence[int] | Sequence[float]r  r   r  r   r   rP   )r   rA  r   r   )r   z%int | float | list[int] | list[float]r0   )r   r   r    r!   r"   r;   r   rs   r:   r,   r#   r|   r}   s   @r   r   r   b  sb    L
 		 <	  	  		 
 
	  	 C     r   r   c                  n   ^  \ rS rSrSr  S       S	U 4S jjjr\S
S j5       rSS jrSS jr	Sr
U =r$ )OpIdDispatchOri|  z`Represents a (restricted) form of value pattern disjunction that enables deterministic matching.c                <   > [         TU ]  U5        Xl        X0l        g)aM  
Initialize an OpIdDispatchOr pattern.

Args:
    op_to_pattern: A dictionary mapping operator identifiers to tuples of tag values and patterns.
        The keys are operator identifiers, and the values are tuples containing a tag value
        and a pattern to match against.
    name: An optional variable name for the pattern. Defaults to None. If present,
        this name will be bound to the value matched by the pattern.
    tag_var: An optional variable name for the tag. Defaults to None. If present,
        it will be bound to a value indicating which alternative was matched.
N)ry   r;   _op_to_pattern_tag_var)r   op_to_patternrY   tag_varrz   s       r   r;   OpIdDispatchOr.__init__  s    $ 	+r   c                    U R                   $ z=Returns the tag variable associated with the OrValue pattern.r  r+   s    r   r  OpIdDispatchOr.tag_var       }}r   c                    [        U R                  R                  5        VVs0 s H  u  p#X#S   US   R                  U5      4_M      snnU R                  U R
                  5      $ s  snnf )Nr   r   )r  r  r   r   rY   r  )r   r   rV  rP  s       r   r   OpIdDispatchOr.clone  s^    9=9L9L9R9R9TU9TQ1qtzz(+,,9TUIIMM
 	
Us   %A&
c                    UR                  5       nUb1  UR                  5       nUb  X0R                  ;   a  U R                  U   $ g)z=Returns the pattern that should be tried for the given value.N)r	  r]  r  )r   r:   r	  rk   s       r   get_patternOpIdDispatchOr.get_pattern  sF    >>#'')B~"(;(;";**2..r   )r  r  )NN)r  z8Mapping[ir.OperatorIdentifier, tuple[Any, ValuePattern]]rY   ro   r  ro   r   rP   rp   )r   rA  r   r  )r:   zir.Valuer   ztuple[Any, ValuePattern] | None)r   r   r    r!   r"   r;   rs   r  r   r  r#   r|   r}   s   @r   r  r  |  sa    j
  "	 O    	 
 
   ,  
 r   r  c                  j   ^  \ rS rSrSr   S         SU 4S jjjr\S	S j5       rS
S jrSr	U =r
$ )BacktrackingOri  zMRepresents an unrestricted form of OR pattern implemented using backtracking.c                   > [         TU ]  U5        Ub2  Uc  [        S5      e[        U5      [        U5      :w  a  [        S5      eO[	        [        [        U5      5      5      nX0l        X@l        Xl        g)a-  
Initialize a BacktrackingOr pattern.

Args:
    values: A sequence of value patterns to match against.
    name: An optional variable name for the pattern. Defaults to None. If present,
        this name will be bound to the value matched by the pattern.
    tag_var: An optional variable name for the tag. Defaults to None. If present,
        it will be bound to a value (from tag_values) indicating which alternative was matched.
    tag_values: An optional sequence of values to bind to the tag_var. Defaults to None.
        If present, the length of tag_values must match the number of alternatives in values.
        In a successful match, tag-var will be bound to the i-th value in tag_values if the i-th
        alternative pattern matched. If omitted, the default value of (0, 1, 2, ...) will be used.
N4tag_var must be specified if tag_values is provided.Ctag_values must have the same length as the number of alternatives.)	ry   r;   r   r   r   r   r  _tag_values_values)r   valuesrY   r  
tag_valuesrz   s        r   r;   BacktrackingOr.__init__  ss    * 	! !WXX:#f+- Y  .
 uS[12J%r   c                    U R                   $ r  r  r+   s    r   r  BacktrackingOr.tag_var  r  r   c                    [        U R                   Vs/ s H  o"R                  U5      PM     snU R                  U R                  U R
                  5      $ s  snf r   )r  r  r   rY   r  r  )r   r   rP  s      r   r   BacktrackingOr.clone  sF    (,51WWX5IIMM	
 	
5s   A)r  r  r  NNN)
r  Sequence[ValuePattern]rY   ro   r  ro   r  Sequence[Any] | Noner   rP   rp   )r   rA  r   r  )r   r   r    r!   r"   r;   rs   r  r   r#   r|   r}   s   @r   r  r    sj    W
  "+/!&! ! 	!
 )! 
! !F  
 
r   r  c                  ^ ^^^ Tb2  Tc  [        S5      e[        T5      [        T 5      :w  a  [        S5      eO[        [        [        T 5      5      5      mSUUUU 4S jjnU" 5       nU=(       d    [	        T TTT(       a  TOS5      $ )a  
Creates an OR pattern.

Args:
    values: A sequence of value patterns to match against.
    name: An optional variable name for the pattern. Defaults to None. If present,
        this name will be bound to the value matched by the pattern.
    tag_var: An optional variable name for the tag. Defaults to None. If present,
        it will be bound to a value (from tag_values) indicating which alternative was matched.
    tag_values: An optional sequence of values to bind to the tag_var. Defaults to None.
        If present, the length of tag_values must match the number of alternatives in values.
        In a successful match, tag-var will be bound to the i-th value in tag_values if the i-th
        alternative pattern matched. If omitted, the default value of (0, 1, 2, ...) will be used.
Nr  r  c                    > 0 n [        T5       HO  u  p[        U[        5      (       d    g UR                  5       nUR	                  5       nUb  X@;   a    g TU   U4X'   MQ     [        U TT5      $ r   )rG  r   rH  r	  r]  r  )	mappingr   alternativer	  rk   rY   r  r  r  s	        r   make_op_id_or_pattern&OrValue.<locals>.make_op_id_or_pattern  ss    NP'/NAk+<=="++-H'')BzR]%a=+6GK 0 gtW55r   )r   zOpIdDispatchOr | None)r   r   r   r   r  )r  rY   r  r  r  optimized_patterns   ````  r   OrValuer    s    ( ?STTz?c&k)U  *
 5V-.

6 
6 ./ gWz$! r   c                P   ^^ / mSUU4S jjmT" U 5        TR                  5         T$ )zFReturns all nodes used in a pattern, given the outputs of the pattern.c                   > U  HU  n[        U[        5      (       d  M  UR                  5       nUT;  d  M2  TR                  U5        T" UR                  5        MW     g r   )r   rH  r	  r   r   )value_patternsvalue_patternr   node_patternsvisits      r   r   _nodes_in_pattern.<locals>.visit  sM    +M-):;;,557}4!((6,--. ,r   )r  zSequence[ValuePattern | None]r   rP   )reverse)r   r  r  s    @@r   _nodes_in_patternr    s-    ')M/ / 
'Nr   c                   X;   a  gUR                  U 5        U R                   Hb  n[        U[        5      (       a  [	        UR                  5       X5        M4  [        U[        [        45      (       d  MQ  UR                  U5        Md     g)zAdds all nodes in the backward slice of given node to the set `backward_slice`.

The backward slice of a node is the set of all nodes that are reachable from the node
in a backward traversal from the given node.
N)addr   r   rH  _add_backward_slicer	  r  r  )r   backward_slicebackward_slice_valuesr  s       r   r  r     so     tm%677&&(. 'GHH!%%m4 %r   c                      \ rS rSrSr        SS jr\SS j5       rSS jrSS jr	SS jr
\SS j5       r\SS	 j5       rSS
 jrSS jr\SS j5       r\SS j5       rSS jrSS jrSrg)GraphPatterni6  z<Represents a pattern that can be matched against a subgraph.c                J   Xl         X l        [        U5      S:X  a  [        S5      eX0l        [        5       n[        5       n[        5       n[        5       nU H  n[        U[        5      (       d  [        S[        U5       S35      e[        U[        5      (       a6  UR                  5       n	X;  a  UR                  U	5        [        XU5        My  M{  [        U[        [        45      (       d  M  UR                  U5        M     Xg::  d  [!        S5      e[#        U5      U l        g )Nr   z*GraphPattern must have at least one outputzInvalid type z for graph pattern output.z3Returning uncovered choice-values is not supported.)_inputsr   r   r   r   setr   r   r   r   rH  r	  r  r  r  r  NotImplementedErrorr  output_nodes)
r   r   r   r   r  coveredchoice_values_returnedcovered_choice_valuesr  	candidates
             r   r;   GraphPattern.__init__9  s    w<1IJJ *-$'E47E365$Mm\::#D$7#88RS  -):;;)224	+ $$Y/'	<QR , MNN+KLL&**=9 %  '?%&[\\/3L/Ar   c                h    [        U R                  5      S:w  a  [        S5      eU R                  S   $ )Nr   z.GraphPattern does not have unique output node.r   )r   r  r   r+   s    r   output_nodeGraphPattern.output_node`  s2    t  !Q&MNN  ##r   c                     U R                   U   $ r   )r   )r   r  s     r   r   GraphPattern.nodef  s    {{5!!r   c                ,    [        U R                  5      $ r   )r   r   r+   s    r   	num_nodesGraphPattern.num_nodesi  r   r   c                "    U R                  5       $ r   )r  r+   s    r   __len__GraphPattern.__len__l  s    ~~r   c                    U R                   $ r   )r  r+   s    r   r   GraphPattern.inputso  s    ||r   c                    U R                   $ r   )r   r+   s    r   r   GraphPattern.outputss  s    }}r   c                ,    [        U R                  5      $ r   )iterr   r+   s    r   __iter__GraphPattern.__iter__w  s    DKK  r   c                ,    [        U R                  5      $ r   )reversedr   r+   s    r   __reversed__GraphPattern.__reversed__z  s    $$r   c                2    [        U R                  5      S:H  $ )Nr   )r   r  r+   s    r   has_single_output_node#GraphPattern.has_single_output_node}  s    4$$%**r   c                ,    [        U R                  5      $ r   )r   r   r+   s    r   num_outputsGraphPattern.num_outputs  s    4==!!r   c                   ^  SS jnT R                    Vs/ s H
  o!" U5      PM     nnSU 4S jjn[        R                  " U6  Vs/ s H
  oT" U5      PM     sn$ s  snf s  snf )Nc                `    U R                  5       S:X  d  U R                  5       S:X  a  SS/$ S/$ )N)r   r  r   )r   r,  r   FT)r]  )r   s    r   commute_node*GraphPattern.commute.<locals>.commute_node  s<    !!#6$:L:L:N S ; t}$7Nr   c                ~  > [        U 5      (       d  T$ 0 nTR                   Vs/ s H  o"R                  U5      PM     nn[        TR                  U 5       VVs/ s H  u  pEUR                  X5      PM     nnnTR
                   Vs/ s H  o"R                  U5      PM     nn[        X7U5      $ s  snf s  snnf s  snf r   )anyr  r   zipr   r   r  )		swap_listr   rP  
new_inputsr   rn  	new_nodesnew_outputsr   s	           r   
copy_graph(GraphPattern.commute.<locals>.copy_graph  s    y>>79H59\\B\''(+\JB=@i=X=Xzt

8*=X   7;mmDm778,mKD
CC C Es   B/B4B:)r   r   r   Iterable[bool])r  r	  r   r  )r   	itertoolsproduct)r   r  r   iteration_spacer  r  s   `     r   commuteGraphPattern.commute  sc    		 ;?++F+$<-+F	D 8A7H7H/7Z[7Z)
9%7Z[[ G \s   AAc                    SR                  S U R                   5       5      nSR                  S U R                   5       5      nSR                  S U R                   5       5      nSU SU SU S	3$ )
NrL  c              3  8   #    U  H  n[        U5      v   M     g 7fr   rN  rO  s     r   r   'GraphPattern.__str__.<locals>.<genexpr>  s     8<a3q66<rR  c              3  8   #    U  H  n[        U5      v   M     g 7fr   rN  rO  s     r   r   r    s     :MqCFFMrR  z
   c              3  8   #    U  H  n[        U5      v   M     g 7fr   rN  )r   ns     r   r   r    s     9[SVV[rR  z	pattern (z) {
   z
   return z
})rX  r  r   r   )r   r   r   r   s       r   r,   GraphPattern.__str__  se    84<<88)):DMM::9T[[996()E7,witLLr   )r  r   r   r  N)r   r  r   r  r   r   r   rP   r  )r  r   r   r   r~  )r   r  )r   zIterator[NodePattern]rq   )r   zSequence[GraphPattern]r0   )r   r   r    r!   r"   r;   rs   r  r   r  r  r   r   r  r  r  r  r  r,   r#   r   r   r   r  r  6  s    F%B&%B (%B %	%B
 
%BN $ $
"      !% + + " "\:Mr   r  c                ^   [         R                  " U 5      R                  nU Vs/ s H  n[        U5      PM     snSS n[	        SSS9n[        U5         U " U/UQ76 nSSS5        [        W[        5      (       a  U/n[        X5UR                  5       5      $ s  snf ! , (       d  f       NE= f)aK  Convert a pattern-construction function to a GraphPattern.

A pattern-construction function will return values as below:
::
    def pattern(op, x: Var, shape1: Var, shape2: Var):
        ...
        return outputs

We create a pattern graph by creating pattern-variables for each parameter of the function,
and calling the function. The returned values are normalized to a list of ValuePatterns,
which represent the outputs of the pattern graph.

Args:
    pattern_constructor: Callable

Returns:
    GraphPattern: A representation of the pattern that can be matched against a subgraph.
r   Nr   T)r   )
inspect	signature
parametersr   r   r   r   r   r  r   )pattern_constructor_pattern_varsrP  pattern_inputsr   pattern_outputss         r   _to_graph_patternr    s    & %%&9:EEM&34mc!fm4QR8N!"T2G		!-gGG 
"
 /<00*+II 5	!	!s   B
B
B,)r:   z/AttrPattern | ValuePattern | SupportedAttrTypesr   rR   )r   z,ValuePattern | int | float | Callable | Noner   zValuePattern | None)r   r   r  )
r  r  rY   ro   r  ro   r  r  r   r   )r   r  r   zlist[NodePattern])r   r   r  zset[NodePattern]r  zset[ValuePattern]r   rP   )r  r   r   r  )=r"   
__future__r   r1   
contextlibr  r
  collections.abcr   typingr   r   r   r   r	   r
   r   r   onnxscript.rewriter._basicsrewriter_basics
onnxscriptr   r   r   ABCr/   r%   r4   rF   AttrrR   ru   r   r   r   r   r   r   onnxoptorch_module_opr   r   r   __annotations__contextmanagerr   r   r   rH  r   r  	ANY_VALUEr   r  r  r  r  r  r  r  r   r   r   <module>r.     sJ   K " 
    #	 	 	 . - CL,hqk ,	CGGWS\ 	M  
!M 
!V'"''" V.>k > 	SMUOSM  +  2D4- -` 
R	 %mK&@AF! F!RA3AAD )/ % . $ $IV IVXJ JZ 4
[, 
[|  J	 |  4,\ ,^1
\ 1
l '+	-"-
- - %	-
 -`"5
5$5 -5 
	5,pM pMfJr   