
    Ph                    	   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlmZ d dlmZ d dlmZmZ d dlm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mZm Z m!Z! d dl"Z"d dl#Z"d dl$m%c mZ& d dl'm(Z) d d	l*m+Z+m,Z,m-Z-m.Z.m/Z/ d d
l0m1Z1m2Z2 d dl"m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9 d dl:m;Z; d dl<m=Z=m>Z>m?Z? d dl@mAZA d dlBmCZCmDZDmEZEmFZF d dlGmHZH d dlImJZJmKZK d dlLmMZM d dlNmOZO eZPeZQ ej                  eS      ZT G d deU      ZVd dlWZWd dlXmYZY d dlZm[Z[m\Z\ e"j                  j                  j                  Z_g dZ`dZadZb ed      d        Zc G d deU      Zdd Zed  Zfdd!Zgd" Zhd#e eie5f   fd$Zjd%eWj                  fd&Zld%eWj                  fd'Zmd#e ene3f   fd(Zod)e e5e"j                  f   d*e!eWj                     fd+Zrd)e e5e"j                  f   d*eeWj                     fd,Ztd)e e5e"j                  f   d*enfd-Zud. Zvd*eeWj                     fd/Zwd0 Zxd1 Zyd2 Zzd3 Z{d4 Z|d5 Z}d6 Z~ e-       d7eWj                  d8eid9eid:eid;eif
d<       Zd= Z e-       dd>eei   d?eei   fd@       Z e-       ddAd>eei   d?eei   fdB       Z e-       dC        ZddDeifdEZdF ZdG ZdH ZdI ZdJ ZdKdLdMZdN Zd%eWj                  dOeEfdPZ G dQ dRe      Z edKS       G dT dU             Z edKS       G dV dWe             Z edKS       G dX dYe             Ze eedf   Z edKS       G dZ d[e             Zd\ Z edKS       G d] d^             Z edKS       G d_ d`e             Z edKS       G da dbe             Zd)e eie5ee4ene3f   d*enfdcZe?fZ edd      de        Zdf Zdg Zdh Zdie"jf                  d*e"jj                  fdjZi dkej>                  dlej@                  dmejB                  dnejD                  doejF                  dpejH                  dqejJ                  dredsedtejP                  duejR                  dvejT                  dwedxejV                  dyejX                  dzeZdd{Z edKS       G d| d}             Z G d~ deY      Z G d de      Z G d deY      Z G d d      Z e
jh                         Z G d d      Zd Zd Zy)    N)defaultdict)contextmanager)	dataclassfield)Enum)	lru_cache)AnycastCallableDictListOptionalSequenceSetTupleTypeUnionIterable)_config)FakeTensorMetaShapeEnvEventrecord_shapeenv_eventreplay_shape_env_eventsshape_env_check_state_equal)SymNodeSymTypes)SymBoolSymFloatSymInt)
ShapeGuardSourceTracingContext)is_traceable_wrapper_subclass)FloorDivMod!IsNonOverlappingAndDenseIndicator)	try_solve)bound_sympySymPyValueRangeAnalysisValueRangesValueRangeError)SingletonInt)format_frameCapturedTraceback)signpost_event)
LazyStringc                       e Zd Zy)GuardOnDataDependentSymNodeN__name__
__module____qualname__     pC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/fx/experimental/symbolic_shapes.pyr2   r2   4       r8   r2   )
StrPrinter)
precedence
PRECEDENCE)has_symbolic_sizes_stridescreate_contiguousShapeEnvis_concrete_int	guard_intguard_floatguard_scalarcanonicalize_bool_exprhint_intSYMPY_INTERPfree_symbolsis_symbol_binding_fx_nodeis_concrete_boolSHAPEENV_EVENT_KEYCURRENT_NODE_KEYhas_free_symbolssym_eqSymbolicContextStatelessSymbolicContextStatefulSymbolicContextshapeenv_eventcurrent_nodec                  d   dd l } dd l} t        j                  t           | j
                  j                  j                  | j
                  j                  j                  | | j                  j                  | j                  j                  g}|D ch c]  }t        j                  |       c}S c c}w Nr   )torch._inductor.sizevarstorch._library.abstract_implsysmodulesr4   fxexperimental	recordingsym_node	_inductorsizevars_libraryabstract_implinspectgetfile)torchmodsms      r9   uninteresting_filesrg   K   s    #'H''&&  $$D )--1GOOA---s   B-c                       e Zd Zy)ConstraintViolationErrorNr3   r7   r8   r9   ri   ri   _   r:   r8   ri   c                     | j                   S N)_has_symbolic_sizes_strides)elems    r9   r>   r>   b   s    +++r8   c                     dg}t        | d d       D ]  }|j                  ||d   z          t        t        |            S )N   )reversedappendlist)shapestridesdims      r9   r?   r?   e   sC    cGcr
#sWR[() $!""r8   c                     t        | t        j                        r| j                  j	                  |      S t        |       t        u sJ |        | S )z
    Retrieve the hint for an int (based on the underlying real values as observed
    at runtime).  If no hint is available (e.g., because data dependent shapes),
    if fallback is not None, use that instead (otherwise raise an error).
    )
isinstancerd   r   noderequire_hinttypeint)afallbacks     r9   rF   rF   k   sA     !U\\"vv""8,,7c>1>Hr8   c                 X    t        | t              r| j                  j                         S yNT)rx   r   ry   has_hintr}   s    r9   r   r   v   s     !Xvv  r8   r}   c                     t        | t        t        f      sJ t        | t              ryt        | j                  j                  t
        j                  j                  j                        ryy)z Utility to check if underlying object
    in SymInt is concrete value. Also returns
    true if integer is passed in.

    Args:
        a (SymInt or int): Object to test if it int
    TF)	rx   r   r|   ry   exprsympycorenumbersIntegerr   s    r9   rA   rA   {   sM     a&#'''!S!&&++uzz1199:r8   r   c           	         t        | t        j                  t        j                  t        j                  t        j
                  t        j                  t        j                  f      s| S t        | t        j                  t        j                  t        j
                  f      r)t        j                  j                  j                  |       } t        |       S )a   Canonicalize a boolean expression by transforming it into a lt / le
    inequality and moving all the non-constant terms to the rhs.
    We canonicalize And / Ors / Not via cnf and then canonicalize their subexpr
    recursively
    nb. sympy.Rel.canonical is not good enough https://github.com/sympy/sympy/issues/25924

    Args:
        expr (sympy.Expr): Expression to canonicalize
    )rx   r   RelAndOrNotEqNelogicboolalgto_cnf_canonicalize_bool_expr_implr   s    r9   rE   rE      s}      dUYY		588UYYRWRZRZ[\$EHHeii89{{""))$/'--r8   c                    t        | t        j                  t        j                  f      r& t	        |       t        t        | j                         S t        j                  t        j                  t        j                  t        j                  i}t        | t        |j                                     r(| j                  | j                  z
  }|t	        |          }nnt        | t        j                  t        j                  t        j                   t        j"                  f      sJ | j                  | j                  z
  }t	        |       }d}t        |t        j$                        rig }g }|j                  D ]1  }|j&                  r|j)                  |       !|j)                  |       3 t        j$                  | }t        j$                  |  } |||      S rU   )rx   r   r   r   r{   maprE   argsGtLtGeLetuplekeysrhslhsr   r   Add	is_numberrr   )r   oppositer   tr   cts	variablesterms           r9   r   r      sE   $EHH-.tDz35tyyABB%((EHHehh7H$hmmo./hh!T$Z $588UXXuxx HIIIhh!J
C#uyy!	HHD~~

4   &	 
 ii#yy#S#;r8   c                 $   t        | t        t        f      sJ t        | t              ryt        | j                  j                  t
        j                  j                  j                  t
        j                  j                  j                  f      ryy)z Utility to check if underlying object
    in SymBool is concrete value. Also returns
    true if integer is passed in.
    Args:
        a (SymBool or bool): Object to test if it bool
    TF)
rx   r   boolry   r   r   r   r   BooleanTrueBooleanFalser   s    r9   rJ   rJ      sb     a'4)))!T!&&++ 3 3 ? ?ATATAaAabcr8   valreturnc              #     K   t        | t              r%t        |       r| j                  j                   y y t        | t
        j                        r|  y t        | t        t        t        f      ry t        | t        j                        rdt        | j                               E d {    t        | j                               E d {    t        | j                               E d {    y t        | t         t"        f      r| D ]  }t        |      E d {     y t%        d|  dt'        |              7 7 s7 T7 'w)Nz&cannot extract sympy expressions from  )rx   r   is_symbolicry   r   r   Basicr|   floatr   rd   Tensor_iterate_exprssizestridestorage_offsetr   rs   AssertionErrorr{   )r   ss     r9   r   r      s     #x  s((-- 	C	%		C#ud+	,	C	&!#((*---!#**,///!#"4"4"6777	C%	'A%a(((  EcU!DQTI;WXX 	./7 )sH   B'E)D<* E
D> E+E ,.EE"E>E EEc                     t        |       }	 t        |      } |j                  j
                  d |D         S # t        $ r t               cY S w xY w)Nc              3   4   K   | ]  }|j                     y wrk   )rH   .0es     r9   	<genexpr>zfree_symbols.<locals>.<genexpr>   s     *G3a1>>3   )r   nextStopIterationsetrH   union)r   itr
first_exprs      r9   rH   rH      sS    

C#Y
 ):""((*G3*GHH  us   8 AAc                 :    t        d t        |       D               S )z)Faster version of bool(free_symbols(val))c              3   4   K   | ]  }|j                     y wrk   )r   r   s     r9   r   z#has_free_symbols.<locals>.<genexpr>   s     <(;11;;(;r   )allr   r   s    r9   rM   rM      s    <s(;<<<<r8   c                 v    t        |       D ch c]   }|j                  j                  d      s|" c}S c c}w )N)if)rH   name
startswith)xr   s     r9   free_unbacked_symbolsr      s/    #AH!!&&*;*;J*GAHHHs    66c                 H   | j                   dk(  rd| j                  v rt        | j                  d   t        j                        r^t        | j                  d   j
                  j                  t        j                        r#| j                  d   j
                  j                  S y Nplaceholderr   )	opmetarx   rd   r   ry   r   r   Symbol)ry   s    r9   rI   rI      sr    = 499U#U\\2499U#((--u||<yy$$)))r8   c                     | j                   D ci c]1  }t        |      r$|j                  d   j                  j                  |3 c}S c c}w )Nr   )nodesrI   r   ry   r   )graphry   s     r9   find_symbol_binding_fx_nodesr     sO     KKD$T* 			%""D(  s   6Ac                     t        | t              r&| j                  j                         rt	        |       S yt        |       S )a+  
    Returns True only if we can tell that a is True, possibly introducing
    a guard in the process.  If a depends on some unbacked SymInt, we may
    return False even though there may exist a possible value of the SymInt
    that would cause the expression to return True.

    When is it appropriate to use definitely_true?  First, if you can use
    a higher level combinator like parallel_or/parallel_and, prefer using
    those instead, they are definitely safe (modulo short-circuiting).
    Second, it can be used if the program would behave equivalently if
    definitely_true always returned False (parallel_or/parallel_and are
    examples of this pattern, modulo short-circuiting).  Finally, it even
    be OK if the program wouldn't behave equivalently, so long as the
    change is semantics preserving.  It can be semantics preserving if
    the program errors in more cases than it did previously (but otherwise
    behaves identically), or if it changes some quantity in a way that
    doesn't matter (e.g., strides often fall in this bucket.)
    Frx   r   ry   r   
guard_boolr   r   s    r9   definitely_truer     s2    & !W66??a= 7Nr8   c                     t        | t              r'| j                  j                         rt	        |        S yt        |        S )aK  
    Returns True only if we can tell that a is False, possibly introducing
    a guard in the process.  If a depends on some unbacked SymInt, we may
    return False even though there may exist a possible value of the SymInt
    that would cause the expression a to be False.  See definitely_true
    for more usage guidance.
    Fr   r   s    r9   definitely_falser   "  s8     !W66??!!}$$Aw;r8   c                  >    t        d | D              ryt        |       S )z
    Evaluate the logical OR of several arguments, avoiding guarding on
    unbacked SymInts if another argument is definitely True.
    c              3   2   K   | ]  }t        |        y wrk   )r   r   r}   s     r9   r   zparallel_or.<locals>.<genexpr>;  s     
,t!?1t   T)anyr   s    r9   parallel_orr   6  s    
 
,t
,,t9r8   c                  >    t        d | D              ryt        |       S )z
    Evaluate the logical FALSE of several arguments, avoiding guarding on
    unbacked SymInts if another argument is definitely False.
    c              3   2   K   | ]  }t        |        y wrk   )r   r   s     r9   r   zparallel_and.<locals>.<genexpr>D  s     
-1Ar   F)r   r   r   s    r9   parallel_andr   ?  s    
 
-
--t9r8   c                    t        | t              rt        |t              s t        | t              r\t        |t              rLt        |       t        |      k7  ryt	        j
                  t        j                  t        t        | |      d      S t        | t        t        j                  f      r%t        |t        t        j                  f      r| |k(  S t        dt        |        dt        |             )z
    Like ==, but when run on list/tuple, it will recursively test equality
    and use sym_and to join the results together, without guarding.
    FTzunexpected sym_eq between r   )rx   r   rs   len	functoolsreduceoperatorand_r   rN   r|   rd   r   r   r{   )r   ys     r9   rN   rN   H  s    
 	1eAu!5:a;NS]^_aeSfq6SVs61a/@$GG	AU\\*	+
1sELL>Q0RAv9$q'!DG9MNNr8   c                     t        | t        t        f      rt        |       S t        | t        t
        f      rt        |       S t        | t        t        f      rt        |       S t        d|        )Nzunrecognized scalar )rx   r   r   r   r   r|   rB   r   r   rC   r   r   s    r9   rD   rD   V  s^    !gt_%!}	A}	%|	A%(	)1~3A3788r8   r   compiler_mincompiler_maxruntime_minruntime_maxc                 l   t         j                  d|||||       | j                  j                  |d       x}rVt	        t        j                  |j                  |      t        j                  |j                  |            | j                  |<   nt	        ||      | j                  |<   | j                  j                  |d       x}rVt	        t        j                  |j                  |      t        j                  |j                  |            | j                  |<   y t	        ||      | j                  |<   y )Nz,_constrain_symbol_range %s [%s, %s] [%s, %s])logdebugvar_to_rangegetr*   builtinsmaxlowerminupperruntime_var_to_range)	shape_envr   r   r   r   r   rs          r9   _constrain_symbol_ranger  a  s    II<a|]hjuv""&&q$//q/$/LL,/agg|1T%
	q! %0l$K	q!**..q$77q7,7LL+.QWWk0R-
	&&q) -8[,Q	&&q)r8   c                    | dk\  sJ t        | t              rqt        | j                  t              rV| j                  j	                         s;t        | j                  j
                  t        j                        rt        |        yyyyy)ax  
    Don't use this directly; use torch._check_is_size instead.

    This is a softer version of _constrain_range_for_size (with min=0,
    max=Inf).  Instead of forcibly constraining a variable (and erroring if we
    failed to constrain it), it will simply advise us that a size is
    constrained in some way.  We will always defer a runtime assert for this
    constraint if we cannot prove it at compile-time, but we we only
    *sometimes* learn useful extra information at compile-time with this
    information.  This is in contrast to constrain_range_for_size, where if
    you don't call that on a fresh unbacked symint, chances are we will choke.

    TODO: Make Dynamo handle this appropriately if this is seen in Dynamo-ed
    code.  Right now this is only really used in code with AOTAutograd trace
    through, so it is not a big problem that this isn't supported, but in
    principle all of this code should be Dynamo'able too.

    TODO: I didn't support min/max because I didn't have a use case where this
    actually helped.  In principle we can support it, it just makes the
    implementation below more complicated.
    r   N)	rx   r   ry   r   r   r   r   r   _constrain_range_for_sizer   s    r9   _advise_is_sizer  s  si    2 6M6 	1fqvvw'!qvv{{ELL1!!$ 2 " ( 	r8   r   r   c                    t        | t        t        f      rt        d      t        | t              sJ d       t        | j
                  j                  t        j                        sJ d       |d}|t        j                  }|dk  rt        d|       ||k  rt        d      |dk  rdn|}t        | j
                  j                  | j
                  j                  ||||	       y)
z=
    This function is NOT INTENDED to be used by itself.
    z$Constraining SymFloat/SymBool is nyiz#can only constrain range for SymIntconstraining non-Symbols NYINr      zCMaximum value to constrain_as_size must be greater than 2, but was oMaximum value to constrain_as_size can't be less than the specified min value, received min={min} and max={max}r   r   r   r   )rx   r   r   
ValueErrorr   ry   r   r   r   oor  r  )r}   r   r   r   s       r9   r  r    s     !h()?@@a G"GG affkk5<<0P2PP0
{
{hh
ax^_b^cdee
Sy/
 	

 a1SL		!r8   )r   c          	         |t         j                   }|t         j                  }||k  rt        d      t        | t              r#|| cxk  r|k  sn t        d|  d| d| d      yt        | j
                  j                  t         j                        r]|t	        | j
                  j                        cxk  r|k  s4n t        dt	        | j
                  j                         d| d| d      yt        | j
                  j                  t         j                        sJ d       t        | j
                  j                  | j
                  j                  ||||       y)	a  
    Applies a constraint that the passed in SymInt must lie between min-max
    inclusive-inclusive, WITHOUT introducing a guard on the SymInt (meaning
    that it can be used on unbacked SymInts).  If min/max are None, we assume
    that the dimension is unbounded in that direction.  Repeated application
    of constrain_range intersects the ranges.  This is a fairly low level API
    that doesn't have a lot of safety guarantees (TODO: provide higher level
    APIs).

    Currently, we use this API in the following circumstance: when we allocate
    an unbacked SymInt, denoting an integer quantity which is data dependent,
    we ordinarily do not know anything about what values it may take.  This
    means that any sort of guard on it will immediately fail.  However, in
    many cases, we know something about the unbacked SymInt: for example, we
    know that nonzero(x).size(0) must be >= 0.  We use constrain_range to
    narrow the possible range, declaring that negative symbols are impossible.
    This permits to definitely answer True to queries like 'nnz >= 0', even if
    we don't know what the actual (hinted) value of 'nnz' is.  In fact, we
    actually use constrain_range to unsoundly discharge common guards: for an
    unbacked SymInt produced by nonzero, we will also assume that it is not
    equal to 0/1 (even though these are perfectly possible values at runtime),
    because we generally expect graphs that are valid for N=2 to also be valid
    for N=1.

    .. warning::
        If you use constrain_range in the context of tracing, we do NOT check
        that the constraint was actually valid at runtime!  In fact, we
        cannot (easily) do so, as we currently unsoundly assume that unbacked
        SymInt can never be zero/one, even if it may actually take on these
        values at runtime (we assume that a graph that is valid for N=2 will
        also be valid for N=1).
    Nr  zInvalid value z for range [:]r	  r  )r   r  r  rx   r|   ry   r   r   r+   r   r  r  )r}   r   r   s      r9   constrain_ranger    s-   D {xxi
{hh
Sy/
 	

 !SqC~aSSE3%qIJJ!&&++u}}-s166;;'.3.!N3qvv{{3C2DLQTPUUVWZV[[\"]^^affkk5<<0P2PP0 		r8   c                    t        | t              st        |t              s| |k(  sJ t        |j                  j                  t        j
                        sJ d       |j                  j                  }t	        j                  |       |j                  |j                  j                  <   yyt        | j                  j                  t        j
                        sJ d       | j                  j                  }t        |t              s7t	        j                  |      |j                  | j                  j                  <   y| j                  j                  |j                  j                  u sJ t        |j                  j                  t        j
                        sJ d       |j                  | j                  j                        }||j                  |j                  j                  <   y)z
    Given two SymInts, constrain them so that they must be equal.  NB:
    this will not work with SymInts that represent nontrivial expressions
    (yet!)
    r	  N)
rx   r   ry   r   r   r   r  r   replacements_find)r}   br  new_vars       r9   constrain_unifyr    sJ    a !V$6M6affkk5<<8X:XX8((I27--2BI""166;;/	  !&&++u||4T6TT4FF$$	!V$27--2BI""166;;/66##qvv'7'7777affkk5<<8X:XX8ooaffkk2G29I""166;;/r8   skipc                 0   t        | t              rmt        j                         }t	        |dz         D ]  }|j
                  } | j                  j                  |j                  j                  |j                        S t        |       t        u sJ |        | S Nro   )rx   r   rb   currentframerangef_backry   expect_truef_codeco_filenamef_linenor{   r   )r}   r  frame_s       r9   r  r  E  st    !W$$&taxALLE !vv!!%,,":":ENNKK7d?A?Hr8   c                     t        | t              r| j                  j                  dd      S t	        |       t
        u sJ |        | S N r   )rx   r   ry   r   r{   r   r   s    r9   r   r   O  s=    !Wvv  Q''7d?A?Hr8   c                     t        | t              r| j                  j                  dd      S t	        |       t
        u sJ |        | S r&  )rx   r   ry   rB   r{   r|   r   s    r9   rB   rB   U  s=    !VvvA&&7c>1>Hr8   c                     t        | t              r| j                  j                  dd      S t        | t              sJ |        | S r&  )rx   r   ry   rC   r   r   s    r9   rC   rC   [  s=    !Xvv!!"a((a""Hr8   c                     | j                   j                  D cg c]!  }|j                  dk(  s|j                  d   # c}S c c}w r   )r   r   r   r   gmns     r9   fx_placeholder_valsr.  b  s5    #%88>>K>aQTT]5JAFF5M>KKKs
   AAc                     | j                   j                  D cg c]  }|j                  dk(  s|j                    c}S c c}w )Nr   )r   r   r   targetr+  s     r9   fx_placeholder_targetsr1  e  s1     hhnnFn0EAHHnFFFs   ??Tignore_staticc                P    | j                   j                  t        |       ||      S )Nr2  )r  evaluate_guards_for_argsr.  )r,  r3  r   s      r9   eval_guardsr6  k  s%    <<001DR1H$^k0llr8   c                 L    | j                   j                  t        |       |      S rk   )r  bind_symbolsr.  )r,  r   s     r9   r8  r8  n  s    <<$$%8%<dCCr8   boundc                    |j                   j                  sT|j                   j                  s>|j                   j                  r(| j	                  t
        j                        s	J || f       |j                  j                  sW|j                  j                  s@|j                  j                  r)| j	                  t
        j                        s	J || f       yyyy)a8  
    We assert that the bounds are either Boolean, or not finite, or can be computed
    in exact prevision via rational arithmetic.
    The only exception to this is the rare case when the user calls `sqrt(s0)`
    sqrt is turned into sympy.Pow so we just match for that (it matches more things, but still)
    N)r   is_rational
is_Boolean	is_finitehasr   Powr   )r   r9  s     r9   _assert_bound_is_rationalr@  q  s     ;;""ekk&<&<EKKDYDY]a]e]efkfofo]psxz~rp;;""ekk&<&<EKKDYDY]a]e]efkfofo]psxz~rp]pDY&<"r8   c                       e Zd ZdZdZdZdZy)
DimDynamican  
    Controls how to perform symbol allocation for a dimension.  It is always
    sound to default this to DYNAMIC, but the policies DUCK and STATIC can
    result in better trace-time and compile-time performance, as they reduce
    the number of allocated symbols and generally make your graph more static.

    NB: If we notice you've applied a constraint to the dimension, we will
    force it to DYNAMIC for simplicity.

    DimDynamic is controlled by a variety of higher level UX features.
    Currently:

    - In eager mode, the default policy is DUCK.
        - The default is changed to STATIC with assume_static_by_default.
        - An individual dim is marked DYNAMIC if you mark_dynamic_dim.
    - In export mode, the default policy is STATIC.
        - An individual dim is marked DYNAMIC if you mention it as dynamic_dim
          in the constraints kwarg.
    r   ro   r
  N)r4   r5   r6   __doc__DYNAMICDUCKSTATICr7   r8   r9   rB  rB  {  s    ( G DFr8   rB  frozenc                       e Zd ZU eed<   y)
Constraint	warn_onlyN)r4   r5   r6   r   __annotations__r7   r8   r9   rJ  rJ    s    Or8   rJ  c                   (    e Zd ZU dZeed<   defdZy)StrictMinMaxConstrainta-  
    For clients: the size at this dimension must be within 'vr' (which
    specifies a lower and upper bound, inclusive-inclusive) AND it
    must be non-negative and should not be 0 or 1 (but see NB below).

    For backends: there must not be any guards on this dimension which
    are not implied by the given lower and upper bound.  Regardless of
    the lower bound, the backend can assume the size is non-negative
    and that it is not 0 or 1.

    An unbounded StrictMinMaxConstraint can be thought of as a strict version
    of "RelaxedUnspecConstraint".

    NB: Export will often unsoundly assume that a graph works for 0/1, even
    though at trace time we assumed size is not 0 or 1.  The idea is that
    if we produce a graph that works for a range of values, it will be OK
    for N=0/1 too.
    vrsourcec                     | j                   j                   d|j                          d| j                   j                   S )N <= )rO  r   r   r   selfrP  s     r9   renderzStrictMinMaxConstraint.render  s/    ''--V[[]O4GGr8   N)r4   r5   r6   rC  r*   rL  r!   rU  r7   r8   r9   rN  rN    s    $ 	OHV Hr8   rN  c                       e Zd ZdZdefdZy)RelaxedUnspecConstrainta  
    For clients: no explicit constraint; constraint is whatever is implicitly
    inferred by guards from tracing.

    For backends: there must exist at least TWO possible values for the
    size at this dimension which satisfy the guards for this dimension.

    In other words, this constraint helps us distinguish between "we don't
    care if this dimension specializes or not" versus "this dimension must be
    unspecialized."  However, this constraint doesn't say very much about what
    specialization is permitted; for example, if we guard on a size being
    even, this would still be acceptable under an unspec constraint.  This
    makes RelaxedUnspecConstraint useful for eager mode, where your backend compiler
    may add constraints to otherwise dynamic dimensions; we can't assert that
    there are NO guards as this is brittle because compilers should be able to
    add extra constraints.  If you want to assert that there are no guards,
    use StrictMinMaxConstraint with an unbounded ValueRanges.
    rP  c                 *    d|j                          dS )NzRelaxedUnspecConstraint()r   rS  s     r9   rU  zRelaxedUnspecConstraint.render  s    )&++-::r8   N)r4   r5   r6   rC  r!   rU  r7   r8   r9   rW  rW    s    $;V ;r8   rW  c                   J    e Zd ZU dZeeeef      ed<   d Zd Z	d Z
d Zd Zy)	EqualityConstraintz
    Given pairs of sources corresponding to pairs of dynamic dimensions that
    are specified equal, represent them in a union-find data structure so that
    we can efficiently check whether two such sources are transitively equal.
    source_pairsc                     t         j                  | di        | j                  D ]5  \  }}| j                  | j	                  |      | j	                  |             7 y )N_parents)object__setattr__r]  _unionr  rT  source1source2s      r9   __post_init__z EqualityConstraint.__post_init__  sI    4R0 $ 1 1GWKK

7+TZZ-@A !2r8   c                 ^    || j                   v r| j                  | j                   |         S |S rk   )r_  r  rS  s     r9   r  zEqualityConstraint._find  s+    T]]"::dmmF344Mr8   c                 .    ||k7  r|| j                   |<   y y rk   )r_  )rT  root1root2s      r9   rb  zEqualityConstraint._union  s    E>#(DMM%  r8   c                 V    dj                  d | j                  D              }d|z   dz   S )N, c              3   h   K   | ]*  \  }}|j                          d |j                           , yw) == NrZ  )r   rd  re  s      r9   r   z,EqualityConstraint.render.<locals>.<genexpr>  s6      
&7"' ||~d7<<>"23&7s   02{})joinr]  )rT  bufs     r9   rU  zEqualityConstraint.render  s3    ii 
&*&7&7
 
 Sy3r8   c                 H    | j                  |      | j                  |      k(  S rk   )r  rc  s      r9   is_equalzEqualityConstraint.is_equal  s    zz'"djj&999r8   N)r4   r5   r6   rC  r   r   r!   rL  rf  r  rb  rU  rt  r7   r8   r9   r\  r\    s7    
 uVV^,--B
):r8   r\  c                 b    t        | t              sJ d       t        |       t        usJ d       y )NzInvalid symbolic_context objectz%Illegal usage of symbolic_context ABC)rx   rO   r{   symbolic_contexts    r9   _assert_symbol_contextrx    s3    &8[:[[8 !8a:aa8r8   c                       e Zd ZdZy)rO   aS  
    Data structure specifying how we should create symbols in
    ``create_symbolic_sizes_strides_storage_offset``; e.g., should
    they be static or dynamic.

    This is an abstract base class because we are probably going to add
    another version of this that says "use exactly these SymInts, don't
    allocate fresh symbols."
    N)r4   r5   r6   rC  r7   r8   r9   rO   rO   
  s     	r8   rO   c                   <    e Zd ZU dZee   ed<   dZee   ed<   d Z	y)rP   z
    Create symbols in ``create_symbolic_sizes_strides_storage_offset`` via
    a symbolic_context determination as given by ``DimDynamic`` and ``DimConstraint``.
    This will cause fresh symbols to be allocated
    dynamic_sizesNconstraint_sizesc                 z    | j                   /t        j                  | dd gt        | j                        z         y y )Nr|  )r|  r`  ra  r   r{  rT  s    r9   rf  z&StatelessSymbolicContext.__post_init__#  s8      (t%7$#dFXFXBY9YZ )r8   )
r4   r5   r6   rC  DimListrB  rL  r|  DimConstraintrf  r7   r8   r9   rP   rP     s*    
 :&&/3gm,3[r8   rP   c                   >    e Zd ZU dZdZeed<   dZede	f   ed<   d Z
y)rQ   a   
    Create symbols in ``create_symbolic_sizes_strides_storage_offset`` via
    a symbolic_context determination as given by a cache of Source:Symbol. A cache hit
    will reuse a stored symbol, and a cache miss will write to this cache.

    This behaves like StatelessSymbolicContext, except the cache supersedes the
    other values - dynamic_sizes and constraint_sizes will not be read if we cache
    hit.

    It is the cache owners responsibility to maintain the lifecycle of the cache
    w/r/t different shape_envs, clearing, etc.
    Ntensor_sourceTensorPropertySourcesource_to_symint_node_cachec                 h    | j                   J | j                  st        j                  | di        y y )Nr  )r  r  r`  ra  r~  s    r9   rf  z%StatefulSymbolicContext.__post_init__O  s5    !!---//t%BBG 0r8   )r4   r5   r6   rC  r  r!   rL  r  r   r   rf  r7   r8   r9   rQ   rQ   >  s/     !M6 IM$'=v'E"FMHr8   rQ   c                 n    t        | t        t        t        f      ry| j                  j                         S NF)rx   r|   r   r   ry   r   r   s    r9   r   r   V  s)    #UD)*88!!r8      c                     t        | d      r	 t        j                  |       S | S # t        $ r t        j                  d|        | cY S w xY w)Nexpandz"RecursionError in sympy.expand(%s))hasattrr   r  RecursionErrorr   warning)r  s    r9   safe_expandr  ]  sK    q(	<<?"
 	  	KK<a@H	s   % !A	A	c                      t        d      )Nzshouldn't be hit)r   r7   r8   r9   errorr  h  s    
+
,,r8   c                 >    t        t        t        | |                  S rk   )r|   r   "_eval_is_non_overlapping_and_dense)sizesru   s     r9   !eval_is_non_overlapping_and_denser  m  s    z<UGLMNNr8   c                     t        |       }|dk(  r|d   dk(  xs | d   dk  S t        t        | |      t        j                  d            }d}|D ]  \  }}|dk(  r||k7  r y||z  } y)Nro   r   r
  keyFT)r   sortedzipr   
itemgetter)r  ru   rv   lengths_and_stridesexpected_stridelengthr   s          r9   r  r  p  s    
e*C
 axqzQ.%(Q,. !E7!4!4Q!7 O-Q;_$6! . r8   symboolc                     t        j                  d| j                  j                  fd      }| j                  j                  j                  |t        | j                  j                                     S )Nro   )r   Thint)r   	Piecewisery   r   r  create_symintnoder|   rz   )r  int_syms     r9    cast_symbool_to_symint_guardlessr    sS    ooq',,"3"34i@G<<!!33G#gllF_F_FaBb3ccr8   Absr   r   r   r   r   r   MinMaxr%   r$   TrueDivr&   floorceilingr  c                     t        |      |       dt        j                  r"dt        j                  |       fd       }nt        j                  |       fd       }j
                  |_        j                  |_        |S )a  
    Wrapper around lru_cache that clears when new info about shapes has been
    updated.

    Use lru_cache if the output is always the same, regardless of the
    constraints we know now (i.e. evaluate_expr)

    Use _lru_cache otherwise.

    Also note that this depends on _update_version_counter being called on the
    shape environment whenever the constraints are updated, otherwise the cache
    will not be cleared.
    r   Nc                     | j                         | j                  k7  r-j                          | j                  | j                         n| j                         k(  sJ d        | g|i |S )Nz9ShapeEnv cache key changed without version being updated!)_get_key_version_countercache_clear)rT  r   kwargsfn_cache	prior_keyprior_versions      r9   wrapperz_lru_cache.<locals>.wrapper  s}       MMO	 5 55$$& $ 5 5 MMO	 DMMO3 POP3 D242622r8   c                 r    | j                   k7  rj                          | j                    | g|i |S rk   )r  r  )rT  r   r  r  r  s      r9   r  z_lru_cache.<locals>.wrapper  s?      5 55$$& $ 5 5D242622r8   )r   configvalidate_shape_env_verison_keyr   wrapsr  
cache_info)fnmaxsizer  r  r  r  s      @@@r9   
_lru_cacher    s     "y!"%HM,,				3 
	3" 
		3 
	3 #..G!,,GNr8   c                   d    e Zd ZU ej                  ed<    ed      Zeed<    ed      Z	eed<   y)RuntimeAssertr   F)reprmsgstackN)
r4   r5   r6   r   ExprrL  r   r  strr  r7   r8   r9   r  r    s*    
**% C E"E3"r8   r  c                   <     e Zd Z fdZd Zd Zd ZdefdZ xZ	S )ShapeGuardPrinterc                 L    t         |           || _        || _        || _        y rk   )super__init__symbol_to_source
source_refvar_to_sources)rT  r  r  r  	__class__s       r9   r  zShapeGuardPrinter.__init__  s'     	 0$,r8   c                 T    d| j                  |j                  d   t        d         z  S )Nznot %sr   r   )parenthesizer   r=   rT  r   s     r9   
_print_NotzShapeGuardPrinter._print_Not  s'    4,,TYYq\:e;LMNNr8   c                 J    | j                  |j                  dt        d         S )N and r   	stringifyr   r=   r  s     r9   
_print_AndzShapeGuardPrinter._print_And  s    ~~dii*U2CDDr8   c                 J    | j                  |j                  dt        d         S )Nz or r   r  r  s     r9   	_print_OrzShapeGuardPrinter._print_Or  s    ~~diiD1ABBr8   r   c                 r    t        |t        j                        sJ t        t	        |                    fd} j
                  j                  |      s>J | d j                  |   D cg c]  }|j                          c} d |        d        j                   j
                  |   d         S c c}w )Nc                      t        j                  j                         D  ci c]$  \  } }| |D cg c]  }|j                          c}& c}}}       S c c}w c c}}} w rk   )r  r  itemsr   )symbolsourcesr   rT  s      r9   repr_symbol_to_sourcez>ShapeGuardPrinter._print_Symbol.<locals>.repr_symbol_to_source  s`    '+'<'<'B'B'D'DOFG 737a733'D  3s   AA	AAz (could be from z	) not in zu.  If this assert is failing, it could be due to the issue described in https://github.com/pytorch/pytorch/pull/90665r   )
rx   r   r   r  r{   r  r   r  r   r  )rT  r   r  r   s   `   r9   _print_SymbolzShapeGuardPrinter._print_Symbol  s    $->s4:>-	 $$((. 	
f$8K8KD8Q%R8Q1affh8Q%R$S T+-. /ZZ	
.
 t44T:1=>>	 &Ss   *B4
)
r4   r5   r6   r  r  r  r  r  r  __classcell__r  s   @r9   r  r    s&    	-OEC?S ?r8   r  c                        e Zd Z fdZ xZS )LoggingShapeGuardPrinterc                 *    t         |   |d |       y )Nc                 "    | j                         S rk   rZ  r-  s    r9   <lambda>z3LoggingShapeGuardPrinter.__init__.<locals>.<lambda>  s
    1668r8   )r  r  )rT  r  r  s     r9   r  z!LoggingShapeGuardPrinter.__init__  s    );^Lr8   )r4   r5   r6   r  r  r  s   @r9   r  r    s    M Mr8   r  c                   @     e Zd ZdZ fdZdefdZdefdZd Z xZ	S )DynamicDimConstraintPrinterz
    Printer for dynamic dim constraints.
    - Instead of t.size()[d] it prints dynamic_dim(t, d)
    - Instead of Eq(_, _), Mod(_, _), etc. it prints _ == _, _ % _, etc.

    We use this to suggest code for specifying dynamic dim constraints.
    c                 >    t         |           || _        || _        y rk   )r  r  r  source_name_to_debug_name)rT  r  r  r  s      r9   r  z$DynamicDimConstraintPrinter.__init__  s     0)B&r8   r   c                     | j                   r|j                         S d|j                  j                          d|j                   dS )Nzdynamic_dim(rl  rY  )r  r   baseidxrS  s     r9   print_sourcez(DynamicDimConstraintPrinter.print_source  s>    ));;= fkk..01FJJ<qAAr8   c                     t        |t        j                        sJ t        t	        |                   | j                  | j                  |   d         S rU   )rx   r   r   r  r{   r  r  r  s     r9   r  z)DynamicDimConstraintPrinter._print_Symbol#  sD    $->s4:>-  !6!6t!<Q!?@@r8   c           
          dj                  | j                  |j                  t        |            |j                  | j                  |j
                  t        |                  S )Nz{} {} {})formatr  r   r<   rel_opr   r  s     r9   _print_Relationalz-DynamicDimConstraintPrinter._print_Relational(  sN      dhh
4(89KKdhh
4(89
 	
r8   )
r4   r5   r6   rC  r  r  r  r  r  r  r  s   @r9   r  r    s/    C
Bc B
AS A

r8   r  c                       e Zd ZdZd Zd ZdefdZd Zd Z	d Z
d	 Zd
 ZddZd Zd Z	 	 ddej"                  fdZy)DimConstraintsz
    Custom solver for a system of constraints on symbolic dimensions.
    Solutions are "static" values or simplified "dynamic" constraints.
    c                 4   t        t              | _        t               | _        i | _        || _        t        t              | _        t               | _        g | _        t               | _	        t               | _
        t        ||      | _        g | _        || _        y rk   )r   r   _univariate_inequalities_symbols_with_equalities_substitutions_var_to_val_congruences_multivariate_inequalities_symbolic_equivalences_static_results_dynamic_resultsr  _dcp_inconsistencies_marked_dynamic)rT  r  
var_to_valmarked_dynamicr  s        r9   r  zDimConstraints.__init__6  s    MXY\M]% <?5% BD ?I-8-= <?5' HJ#
 *-*-% 00@B[\	 ,.  .r8   c                       fd} fd}|j                  t              r|j                  t        |      }|j                  t              r|j                  t        |      }|S )aA  
        Eliminate expressions of the form b // d and b % d while adding congruences of the form b % d == k.
        This leaves rational operators (in particular of the form b / d) that our inequality solver can handle.
        We solve the added congruences separately (using our congruence solver, see below).
        c                     | \  }}j                  |      j                  |      }}|j                  j                        |j                  j                        z  }||z
  |z  }|dk7  rj                     j	                  |       |S rU   rewrite_with_congruencessubsr  r  addr   r  divisormod_reduced
congruencer   rT  s        r9   mod_handlerz<DimConstraints.rewrite_with_congruences.<locals>.mod_handlerf  s    0 !MD' 99!TBDDaDabcelDm'D))D$4$45TEUEU8VVK,7JQ!!!$((4r8   c                  *   | \  }}j                  |      j                  |      }}|j                  j                        |j                  j                        z  }||z
  |z  }|dk7  rj                     j	                  |       ||z
  |z  S rU   r  r  s        r9   floor_div_handlerzBDimConstraints.rewrite_with_congruences.<locals>.floor_div_handler  s     !MD' 99!TBDDaDabcelDm'D))D$4$45TEUEU8VVK,7JQ!!!$((4;&'11r8   )r>  r%   replacer$   )rT  r   r   r  r  s   ``   r9   r	  z'DimConstraints.rewrite_with_congruences`  sM    	@	2 88C=<<[1D88H<<*;<Dr8   r   c                    |t         j                  k(  ry|}|j                  | j                        }|t         j                  k(  r| j
                  j                  | d       |j                  }|s
J d|        t        |      dkD  r| j                  j                  |       yt        t        |            }| j                  ||      }|t         j                  k(  ry|j                  | j                        }|t         j                  k(  r!| j
                  j                  | d| d       t        |t         j                        r| j                   j                  |       | j"                  |   j                  |       y)NTz is inconsistent!z2Did not expect constraint with no free variables: ro   z, obtained by rewriting z# with congruences, is inconsistent!F)r   truer
  r  falser  rr   rH   r   r  r  r   iterr	  rx   r   r  r  )rT  r   	orig_exprorig_reducedrH   r   reduceds          r9   r  zDimConstraints.add  s[    5::	 ~~d&6&67 5;;&!!((I;6G)HI((XQRVQWXX||q ++//5$  T,'(A00D9Duzz!ii 0 01G%++%%%,,f4YK @' ' $)--11!4))!,006r8   c                     |j                   r/| j                  j                  |j                          d|        y | j                  j                  ||f       y )Nrn  )r   r  r  r   r  rr   )rT  rP  r   s      r9   add_equalityzDimConstraints.add_equality  sH    >>  $$d4&%AB ''..~>r8   c                    i }| j                   j                         D ]j  \  }}g }t               }|D ]  }|j                  \  }}t	        j
                  dd      }	t	        j                  |||	z  z
  |g      \  }
}||
k(  rzt        j                  j                  j                  ||	      \  }}t        |t        j                        r3t        |t        j                        r||z  }|j                  ||f       |j                  |        |rst	        j                  j                  j                   | \  }}||z
  |z  h||<   ||t	        j
                  dd      z  |z   i||   j#                  fd|D               f|||<   m |S )NtmpTinteger)symbolsc              3   N   K   | ]  }t        j                  |      s|  y wrk   )r   checksol)r   r  substitutions     r9   r   z4DimConstraints.reduce_congruences.<locals>.<genexpr>  s'      .1E: >>*lC 1Es   "%)r  r  r   r   r   r   solve_linearpolys	polytoolsdivrx   r   rr   r  ntheorymodularsolve_congruenceupdate)rT  reduced_congruencesr   congruencesremainder_modulus_pairscongruences_to_checkr  r  r  r  r  solutionmodulus	remainderr$  s                 @r9   reduce_congruencesz!DimConstraints.reduce_congruences  s    "//557NA{&(##&5 )
 *g ll5$7#(#5#5dWs]6JUVTW#X  ;).)>)>)B)B8S)Q&GY!'5==9jTYTaTa>b$-$7	/66	77KL  %((4' *. '%*]]%:%:%K%KMd%e"	7+,y=G*C)D#A& !7U\\%-N#NQZ#Z[#A&-- .1E. 
 *>#A&G 8J #"r8   c                     | j                   rCdj                  | j                         }| j                   j                          t        d|       y )N
z*The following inconsistencies were found:
)r  rq  clearr  )rT  r  s     r9   raise_inconsistenciesz$DimConstraints.raise_inconsistencies  sI      ))D112C!!'')J3%PQQ !r8   c                     | j                   |   }| j                  j                  | j                  j                  |   d   j                          d|        || j                  |<   y )Nr   rn  )r  r  r  r  r  r   r  )rT  r   r   s      r9   _force_specializationz$DimConstraints._force_specialization  sa    q!  DII$>$>q$A!$D$I$I$K#LDQTPU!VW!$Ar8   c                    | j                   D ]R  }|j                  t        t              D ]3  }|j                  \  }}|j
                  D ]  }| j                  |        5 T | j                   }t               | _         |D ],  }| j                  |j                  | j                               . | j                          | j                  j                         D ci c]  \  }}|| j                  vr|| c}}| _        | j                  j                         D ci c]  \  }}|| j                  vr|| c}}| _        y c c}}w c c}}w rk   )r  atomsr$   r%   r   rH   r:  r   r  r
  r  r8  r  r  r  )	rT  r   atomr$  r  r   multivariate_inequalitiesexprsr.  s	            r9   specialize_divisor_symbolsz)DimConstraints.specialize_divisor_symbols  s3   33D

8S1!YY
7 --A..q1 . 2 4 %)$C$C!*-%'-DHHTYYt2234 .""$ !99??A)
A5+++ uHA)
% #'"3"3"9"9";
";;+++ {N";
)


s   EEc           
      L
   | j                          | j                  r| j                  j                         }| j                  j                  |      }t        j
                  j                  j                  ||      }t        |t        j                        rt        d |j                  D        |      }t        |t        j                        sJ d| d|        |j                  \  }}||k(  sJ d| d|        | j                  j                  | j                  j                   |   d   j#                          d|        || j$                  |<   | j&                  }t)               | _        |D ]0  }	| j                  |	j+                  || j$                  |                2 | j                          | j                  r| j-                          | j/                         }
|
j1                         D ]  \  }}|D ]  }|| j$                  vs&t	        j2                  ||| j$                  |   i      r7|r.| j5                  |       | j                  j                  |d        g| j6                  j                  | j                  j9                  t	        j                  |d                     | j                  j1                         D ]  \  }}	 t        j
                  j                  j                  ||      }t        |t        j                        rF|j                  D ]6  }| j6                  j                  | j                  j9                  |             8 n4| j6                  j                  | j                  j9                  |              | j@                  }g | _         |D ]  \  }}	|r{t        |	t        jB                        sa|	jD                  D ]R  }| j5                  |       | j                  jG                  |      }| j6                  D ch c]	  }||vs| c}| _        T | jI                  ||	j+                  | j$                                | j@                  D ]W  \  }}	| j6                  j                  | j                  jK                  |       d| j                  j9                  |	              Y y # t:        $ r\}t<        j?                  d|       |D ]6  }	| j6                  j                  | j                  j9                  |	             8 Y d }~Sd }~ww xY wc c}w )	Nc              3   V   K   | ]!  }t        |t        j                        s| # y wrk   )rx   r   r   )r   args     r9   r   z'DimConstraints.solve.<locals>.<genexpr>  s!      [CQVQYQYAZs   ))z$Expected an equality constraint for z, got zExpected a constraint on z instead of on r   rn  z!Failed to reduce inequalities: %s)&r8  r  popr  r   solversinequalitiesreduce_inequalitiesrx   r   r   r   r   r  r  r  r  r   r  r  r   r
  r@  r4  r  r#  r:  r   doprintNotImplementedErrorr   r  r  r   rH   r  r  r  )rT  disable_congruencesdisable_equivalencesr   r?  r1  r  r   r>  r   r-  r.  r  rC  r   symbolic_equivalencesrP  sexprr  s                      r9   solvezDimConstraints.solve  sL   ""$ ++--113A1155a8E}}11EEeQOH(EII. [ []efh1m5YZ[Y\\bckbl3mm1"--KFCQ;V";A3ofX VV;  $$		(B(B1(Ea(H(M(M(O'PPTUXTY%Z[%(D" )-(G(G%.1eD+11d&9&9!&<=> 2&&(' ++* 	'') #5571779NA{)
D///u~~jSTVZViVijkVlRm7n*22155599!TB--11$))2C2CEHHZYZD[2\] * : 55;;=HAuG ==55II%QRSh		2'}}--11$))2C2CC2HI  - ))--dii.?.?.IJ > !% ; ;&(#1LFD#JtU\\,J**A..q1 II33A6E8<8M8M,`8M1QV^_Q_Q8M,`D) + fdii0C0C&DE 2 !77LFD!!%%)?)?)G(HTYYM^M^_cMdLe&fg 8# ' G?C!D))--dii.?.?.EF "G -as&   B>R9	T!T!9	TATTc                       fd} j                   j                         D ci c]6  \  }}| j                  v r# | j                  j                  |   d         |8 c}}S c c}}w )Nc                     | j                         }j                  j                  rj                  j                  |    d| S |S )N = )r   r  r  )srcr   rT  s     r9   
debug_namez9DimConstraints.forced_specializations.<locals>.debug_name[  sA    88:Dyy22))==dCDCvNNr8   r   )r  r  r  r  r  )rT  rS  r   r   s   `   r9   forced_specializationsz%DimConstraints.forced_specializationsZ  sn    	 --335
53D((( tyy11!4Q78#=5
 	
 
s   ;A#c                     g }t               }| j                  D ]A  }t        j                  dd|      }||k7  r|j	                  |       1|j                  |       C |D ]&  }d}|D ]	  }||v sd} |r|j                  |       ( || _        y )Nz2 <= dynamic_dim(.+)zdynamic_dim\1FT)r   r   resubrr   r  )rT  candidates_for_removaldynamic_resultsdcdc_foundother_dcs          r9    remove_redundant_dynamic_resultsz/DimConstraints.remove_redundant_dynamic_resultsh  s    !#%''B &&02BBGCSy&--c2##C( ( )B E+> E , ##B' ) !0r8   Noriginal_signaturec                 ,    !  j                   j                  r fd}t        t              !d }!fd} j                  j                   j                        D ]  } ||      }||k(  r|j                  d      \  }	}
}|
dk(  r|	|k(  r1|j                         r ||	|
t        |             U|	j                         r || ||
      t        |	             |
dk(  sJ |!|	   d<    dt               }|rb|j                  d |j                         D               d	d
j                  |       dz  |j                         D ]  \  }}d| d| dz   g }g }d }|r#t        j                   d|j"                  d         }|/|j                  |j%                  d      j                  d
             !j                         D ]  \  }}||vrd|v rC|d   }t'        |t              r|j)                  | d|        ;|j)                  | d|        R|j+                  dd       }|dk(  rd }|j+                  dd       }| ||j)                  | d| d| d| d       ||j)                  | d| d| d       ||j)                  | d| d| d       |j)                  | d| d        dz  dj                  ||z         z  S d   fd }|j-                  t.        j0                  j2                  !      }i }t5        |j6                  j                               D ]  \  }}||f||<    fd"}d|r)d#z  |j                         D ]  \  }}d| d$| d%z   d&} j                  r: | j                  |      }d'z  d(t9        |       d)z   |||d*        d+z   j                  rO | j                  |      }d,z  d-z  d.t9        |       d)z  d/| d0z   |||dz  d1        d/| d2z  S )3Nc                     j                   j                  j                         D ]  \  }}| j                  ||      }  | S rk   )r  r  r  r  )r   kvrT  s      r9   	transformz2DimConstraints.prettify_results.<locals>.transform  s9     II??EEGDAq		!QA Hr8   c                 D    | dk(  ry| dk(  ry| dk(  ry| dk(  ry| dk(  sJ | S )N<=>=<>==r7   )r   s    r9   flipz-DimConstraints.prettify_results.<locals>.flip  s;    ::99Tz!z	r8   c                     |dk(  r	||    d<   y |dk(  r|dz
  |    d<   y |dk(  r	||    d<   y |dk(  r|dz   |    d<   y |dk(  sJ ||    d	<   y )
Nrf  r   rh  ro   rg  r   ri  rj  eqr7   )r   r   digitresultss      r9   relation_with_digitz<DimConstraints.prettify_results.<locals>.relation_with_digit  sy    :+0GDM%(3Y+019GDM%(4Z+0GDM%(3Y+019GDM%(:%:*/GDM$'r8   r   rj  rm  r'  c              3   D   K   | ]  }|j                  d       d     yw)rQ  r   N)split)r   rb  s     r9   r   z2DimConstraints.prettify_results.<locals>.<genexpr>  s      "\>[1775>!#4>[s    z'Specializations unexpectedly required (rl  6)! For more information, run with TORCH_LOGS=dynamic.
  - z must be specialized to z6 because the guards generated for it are too complex.
zConstraints violated \((.*)\)r   \1z = None  # rQ  r   r
  r   z = Dim('z', min=z, max=rY  z', max=z')z
Suggested fixes:
  z
  c                     t        j                  d|       }|y |j                  d      }t        j                  dd|       } || fS )NzL\['(.+?)'\]ru  )rV  searchr  rW  )rZ  matchrC  s      r9   extract_and_rewrite_localzBDimConstraints.prettify_results.<locals>.extract_and_rewrite_local  sC    IIor2E},,u%C3B7Nr8   c                    t        t              }| D ].  } 
|      }||\  }}||v r|||      j                  |       /0 g }t        |j	                               D ]&  \  }}|\  }	}|j                  |t        |      f       ( |S rk   )r   rs   rr   r  r  )ro  
args_indexgroupsrZ  localrC  sorted_groupsr  dcsr$  ry  s             r9   groupz.DimConstraints.prettify_results.<locals>.group  s     &F1"5= R*$:c?+2226
   M"6<<>2S3$$c6#;%78 3 ! r8   )return_annotationc                 x    d}| D ]2  \  }}|rdz  nd}d| d| dz  |D ]  }d|  ||       z   4 y )NFr6  Tz# r  r7   )groupedindent	result_fnspacerC  ro  resultrr  s          r9   print_resultsz6DimConstraints.prettify_results.<locals>.print_results  sg     E 'W4KC EF82cU!,,%FRx	&(9':;;C & !(r8   zuSome dynamic dimensions need to be specialized because the constraints inferred for them are too complex to specify.
z3, which was marked dynamic, must be specialized to z.
z    zF
The following dimensions have been specialized and CANNOT be dynamic.z
```
def specializationsr  c                     d|  S )Nzassert r7   r  s    r9   r  z1DimConstraints.prettify_results.<locals>.<lambda>(  s    1r8   z
```
z)
The following dimensions CAN be dynamic.zL
Please use the following code to specify the constraints they must satisfy:z
```
def specify_constraintsr6  zreturn [c                     |  dS )N,r7   r  s    r9   r  z1DimConstraints.prettify_results.<locals>.<lambda>4  s
    &|r8   z]
```
)r  r  r   dictr  r   r   rr  isdigitr|   r   r,  r   rq  r  rV  rw  r   r  rx   rr   r   r  rb   	Signatureempty	enumerate
parametersr  )"rT  r_  constraint_violation_errorrT  rd  rk  rp  r   r   leftr   rightdebug_namesr   dimsothersrx  rb  cothermin_max_r  	signaturer{  r   rC  r  r  grouped_static_resultsgrouped_dynamic_resultsrr  ry  ro  s"   `                              @@@r9   prettify_resultszDimConstraints.prettify_results~  s    99..
 "$'G
0 ))//0E0EFaL6"#''#,b%:$%-==?'b#e*=\\^'tBxTC:%:*/GDM$' G C%K%"""\>T>Y>Y>["\\=dii>T=U VK K 5::<FAsT!$<SEAxyyC = DFE)		"BD^DcDcdeDfg ""5<<#6#<#<T#BC1K'19dGE!%-;ug&>?3ug&6755-Dqy#55-D'D,<qc!GD6vQ$OP)qc!GD6$CD)qc!GD6$CDqc!B$78+ (. ++C6;;tf}--CJ		!. '..ARARAXAX.Y	
	 4 4 9 9 ;<FAs #hJsO =	< !RC 16683aS STWSXX[\\ 9%*4+?+?%L"\\C/I/?qAAC&1
 9C  &+D,A,A:&N#??CbbC3C	N3C1EECRxx((C'
+
 Rxx((C
r8   )TTNN)r4   r5   r6   rC  r  r	  r   r  r  r4  r8  r:  r@  rN  rT  r^  rb   r  r  r7   r8   r9   r  r  0  sj    
(.T9v$4 $L?'#RR%

.DhL
02 $(#	y#--yr8   r  c                      e Zd Zddddee   deee      ddfdZddddddd	d
ZdvdZ	deee      fdZ
dwdZdeddfdZdefdZed        Z e       d        Zdedeej*                     fdZdej*                  deddfdZdwdZdwdZdwdZ e       dededeeej>                  j@                     ef   fd       Z!dej*                  dedeej>                  j@                     fdZ"deej>                  j@                     ddfd Z#dej>                  j@                  ddfd!Z$d" Z% e       d#        Z& e       d$        Z'ed%        Z(d& Z)d' Z*d(e+e   ded)e,deejZ                     fd*Z.d+ee   ded)e,deejZ                     fd,Z/dd-d.ej`                  ded)ee,   fd/Z1 e       dd-d(e+e   d0e+e   d1ed2e+e   ded)ee,   fd3       Z2 e       ddd4d5d6d7ee   dee   d)ee,   fd8       Z3 e       d9        Z4dxd:Z5 e       d;        Z6 e       d<        Z7dej*                  defd=Z8 e       d>        Z9 e       e:jv                  dfd?e<ee=f   ded@e:dAe>dd6f
dB       Z? e       e:jv                  dddfd?eded@e:dAe>dCee   dDedd6fdE       Z@dF ZAdG ZBdH fdddddIdJeeCe<e>eeDe>      f         dKeeEeeef         deeF   fdLZGdydMZHdN ZIddOdPZJdQ ZKdR ZLdzdSZMdT ZNeOddddUdVd6dWedXeddYfdZ       ZPeOd{d[       ZQeOd\        ZReOd{d]       ZS eTd^      dd_d|d`       ZU eTd^      d|da       ZVdb ZWd}dcZXd|ddZYeO e       d~de              ZZ eTd^      dVe<df   dgeddfdh       Z[de\fdiZ]de\fdjZ^eOdk        Z_dl Z`dm ZadneFfdoZb eTd^       edp      	 	 dddq              Zcdr Zd edp      ddds       ZedtefddfduZgy)r@   N)should_record_eventstracked_fakesr  r  r   c                t    | j                   di | d|d<   ddlm}  |       | _        ||n| j                  xr t        j
                   | _        | j                  xr t        j                  | _        | j                   | _	        || _
        | j                  rt        t        |      g| _        y g | _        y )NFr  r   translation_validation_enabled)r  r7   )_inittorch.fx.experimental.validatorr  _translation_validation_enabledr   translation_validation_no_bisectr  check_shape_env_recorded_eventscheck_recorded_eventsis_recordingr  r   r@   events)rT  r  r  r  r  s        r9   r  zShapeEnv.__init__I  s     	

V */%&R/M/O, $/ ! 44 @??? 	! %%P&*P*P 	"
 !% 9 99* 9=8Q8Q]8F34 	WY 	r8   TF)allow_scalar_outputsallow_dynamic_output_shape_opsassume_static_by_defaultspecialize_zero_one
duck_shape	co_fieldsc                   || _         || _        g | _        i | _        i | _        i | _        i | _        i | _        i | _        i | _	        i | _
        t               | _        i | _        |r0t        j                  d      t        j                  d      d| _        t!        j"                         | _        t!        j"                         | _        i | _        d| _        || _        || _        || _        t2        | _        | j2                  j5                  d       d| _        d | _        t;        j<                         | _        |r|ni | _         | jC                         | _"        d| _#        i | _$        i | _%        ddl&m'}  |       | _(        | jP                  rqddl&m)}  |       | _*        tV        jX                  j[                         | _.        | j\                  j_                  | j\                  ja                  d              i | _1        y y )Nr   ro   r   ro   
create_envFr  )TranslationValidator)2r  r  guardsr  r   r  r  r  var_to_stackvar_to_guardsr  r   	divisible
val_to_varr   r   	itertoolscountunbacked_symfloat_counterunbacked_symint_counterdeferred_runtime_assertsnum_deferred_runtime_assertsr  r  r  r   inforH  dim_constraintscollectionsCountercounterr  r  _prev_cache_keyr  fx_node_cachesource_to_symbolr  r  r  r  	validatorrd   rZ   Graphr   inserting_beforeoutputname_to_node)	rT  r  r  r  r  r  r  r  r  s	            r9   r  zShapeEnv._inits  s   6 %9!.L+(* >@
 >@9;& FH!@BCE eg =?*-% 24"'--"2u}}Q7GHDO)2):&'0'8$: RT% -.)(@%#6 $l#9="**, '0R  $}} ! UW9;R/M/O,//L13DN)DJ JJ''

(9(9$(?@ ;=D# 0r8   c                 P    d}dt         dt        dt        fd}t        | |||       y )N)r  r   r  r  r   r  r  r  r  r  r  r  r  r  r  valuer   c           
         | dv rddl m } t         ||            S | dk(  r|D cg c]  }|j                   c}S | dk(  rG|j                         D ci c])  \  }\  }}|||j                  nd ||j                  nd f+ c}}}S | dk(  r>|j                         D ci c]   \  }}||D cg c]  }|j                   c}" c}}}S | dk(  rt	        |j                               S |S c c}w c c}}}w c c}w c c}}}w )N)r  r  r   )copyr  r  r  r  )r  r   r   r  r   r   )	r  r  r  gr   lbubrasras	            r9   	map_valuez'ShapeEnv.check_equal.<locals>.map_value  s   NN%
 DK(((-.1..' (-{{}
 (58B	 #%>t#%>t  (5  22AFOvq#c2cBGGc22OO&5::<((L# / 3Os#   C*.C/ C;-C6 C;6C;)r  r	   r   )rT  r  non_state_variable_namesr  s       r9   check_equalzShapeEnv.check_equal   s5    $
 0	3 	s 	s 	: 	$D%1I9Ur8   c                     | j                   y ddlm dffd}| j                   D cg c]
  } ||       c}S c c}w )Nr   )TrackedFakefakec                     t        | j                  t        j                        r| j                  nt	        j
                  | j                        } || j                  | j                        S rk   )rx   r  rd   r   r   	from_fakerP  constraint_dims)r  
inner_faker  s     r9   maybe_transform_fakez=ShapeEnv.snapshot_tracked_fakes.<locals>.maybe_transform_fakeC  sP    dii6 #--dii8  z4;;8L8LMMr8   )r  torch._dynamo.variables.builderr  )rT  r  r  r  s      @r9   snapshot_tracked_fakeszShapeEnv.snapshot_tracked_fakes=  sK    %?	N{ 	N 8<7I7IJ7It$T*7IJJJs   =c                 .    | xj                   dz  c_         y r  tracked_fakes_lengthr~  s    r9   inc_tracked_fakes_lengthz!ShapeEnv.inc_tracked_fakes_lengthO  s    !!Q&!r8   r   c                     || _         y rk   r  )rT  r   s     r9   set_tracked_fakes_lengthz!ShapeEnv.set_tracked_fakes_lengthR  s
    $%!r8   c                 2    t        | j                        dz
  S r  )r   r  r~  s    r9   last_event_indexzShapeEnv.last_event_indexU  s    4;;!##r8   c              #   J   K   d| _         	 d  d| _         y # d| _         w xY ww)NTF)r  r~  s    r9   r\   zShapeEnv.recordingX  s&      	& %DDs   # #	 #c                     d| _         y r   rG  r~  s    r9   freezezShapeEnv.freeze`  s	    r8   rP  c                     | j                   sy |j                         }|| j                  vr$t        j                  |d      | j                  |<   | j                  |   S )NTr  )r  r   r  r   r   )rT  rP  srcnames      r9   _create_symbol_for_sourcez"ShapeEnv._create_symbol_for_sourced  sS    33++-...-2\\'4-PD!!'*$$W--r8   r  r{   c                 V    | j                   r| j                  j                  ||       y y rk   )r  r  add_var)rT  r  r{   s      r9   
_add_z3varzShapeEnv._add_z3varl  s$    //NN""640 0r8   c                 T    | j                   r| j                  j                  |       y y rk   )r  r  add_target_exprr  s     r9   _add_target_exprzShapeEnv._add_target_exprp  s"    //NN**40 0r8   c                 T    | j                   r| j                  j                  |       y y rk   )r  r  add_assertionr  s     r9   _add_assertionzShapeEnv._add_assertiont  s"    //NN((. 0r8   c                 R    | j                   r| j                  j                          y y rk   )r  r  validater~  s    r9   _check_translation_validatez$ShapeEnv._check_translation_validatex  s     //NN##% 0r8   r   r   c                    ||f}d}| j                   r|| j                  vrddlm} t	        d |D              rt        d |D              sJ d |fS d} ||| j                        }t        d |D              sJ d|j                   d	|        | j                  j                  ||      x}| j                  |<   || j                  |j                  <   | j                  j                  |d       |fS )
NFr   )z3opc              3   $   K   | ]  }|d u  
 y wrk   r7   r   s     r9   r   z3ShapeEnv.create_fx_call_function.<locals>.<genexpr>  s     +d19d   c              3   f   K   | ])  }t        |t        j                  j                          + y wrk   )rx   rd   rZ   Noder   s     r9   r   z3ShapeEnv.create_fx_call_function.<locals>.<genexpr>  s#     JTz!UXX]];;Ts   /1Tc              3   $   K   | ]  }|d u 
 y wrk   r7   r   s     r9   r   z3ShapeEnv.create_fx_call_function.<locals>.<genexpr>  s     3dq}dr  zmissing arg in FX graph (z): )r  r  r  r  r   r   r  r4   r   call_functionr  r   r   )rT  r   r   node_keyfreshr  	lifted_opry   s           r9   create_fx_call_functionz ShapeEnv.create_fx_call_function|  s     ://HDDVDV4V< +d++ JTJJJJU{"ER0I 3d33g7PQSQ\Q\P]]`ae`f5gg326**2J2J9VZ2[[D4%%h/+/Ddii(!!%%h5u<<r8   c           	         | j                   sy | j                  j                  |ff}|| j                  vr| j	                  ||       t        j                  ddt        j                  dd|j                              }| j                  j                  |      x}| j                  |<   || j                  |j                  <   ||j                  d<   | j                  |   S )Nz[^a-zA-Z0-9]r$  z[()]r'  r  )
r  r   r   r  r  rV  rW  r   r  r   )rT  r  r{   r
  mangled_namery   s         r9   create_fx_placeholder_and_z3varz(ShapeEnv.create_fx_placeholder_and_z3var  s    
 33JJ**VI6
 4---OOFD)66/3wFKK8XYL26**2H2H2VVD4%%h/+/Ddii( #)DIIh!!(++r8   ry   c                     | j                   rD|A| j                  j                  |j                         | j                  j                  |       y y y rk   )r  r  rD  r   r   
erase_node)rT  ry   s     r9   remove_fx_nodezShapeEnv.remove_fx_node  sC    //D4D!!$)),JJ!!$' 5E/r8   c                     ddl m} | j                  r:| j                         |j                  t
        <    |       |j                  t        <   y y )Nr   )get_current_node)torch._dynamo.utilsr  r  r  r   rK   rL   )rT  ry   r  s      r9   add_fx_node_metadatazShapeEnv.add_fx_node_metadata  s=    8$$,0,A,A,CDII()*:*<DII&' %r8   c                 $    t        t        dd      S )Nsuppress_guardsF)getattrTLSr~  s    r9   _suppress_guards_tlszShapeEnv._suppress_guards_tls  s    s-u55r8   c                     dt         _        y r   r  r  r~  s    r9   suppress_guards_enterzShapeEnv.suppress_guards_enter  s
    "r8   c                     dt         _        y r  r  r~  s    r9   suppress_guards_exitzShapeEnv.suppress_guards_exit  s
    #r8   c              #      K   | j                          	 d  | j                          y # | j                          w xY wwrk   )r  r!  r~  s    r9   r  zShapeEnv.suppress_guards  s2     ""$	(%%'D%%'s   >) >;>c                 l    t        | j                        t        | j                        | j                  fS )z
        Defines the current "state" of the guards we've accumulated in this ShapeEnv.
        Determines when we need to invalidate our cache
        )r   r  r  r  r~  s    r9   r  zShapeEnv._get_key  s+    
 D%%&DNN(;T=^=^__r8   c                 |    | j                         }| j                  |k7  r|| _        | xj                  dz  c_        y y r  )r  r  r  )rT  cur_keys     r9   _update_version_counterz ShapeEnv._update_version_counter  s;     --/7*#*D !!Q&! +r8   ex_sizerw  c                 ^    | j                  t        t        j                               ||      S rk   )!_produce_dyn_sizes_from_int_tupler   exr   )rT  r'  rP  rw  s       r9   _produce_dyn_sizeszShapeEnv._produce_dyn_sizes  s%    
 55eBGGI6FP`aar8   tensor_sizec                 4   t        d |D              s
J d|        ddlm}m} t	        |       |j
                  }|j                  }g }t        |      D ]@  \  }	}
|j                  | j                  |
 |||j                  |	      ||	   ||	                B |S )Nc              3   4   K   | ]  }t        |         y wrk   )r   )r   r   s     r9   r   z=ShapeEnv._produce_dyn_sizes_from_int_tuple.<locals>.<genexpr>  s     ?;C{3'';r   z0Expect size to be a plain tuple of ints but got r   r  TensorProperty)r   torch._dynamo.sourcer  r0  rx  r{  r|  r  rr   create_symbolSIZE)rT  r,  rP  rw  r  r0  dynamic_dimsr  r   r   r   s              r9   r)  z*ShapeEnv._produce_dyn_sizes_from_int_tuple  s    
 ?;??  	BCst  tA  BB  	B?M/0'55*;;,FAsKK**)&.2E2EqI<XY?\klm\n  - r8   rv  r*  c                    |j                   rJ dt        f fdt        fd|j                         D              }t        fd|j	                         D              } |j                               } j                  |||t        |j                               D cg c]  }t        ||       c}||      S c c}w )z
        Returns a list of symbolic sizes and strides for the given tensor.
        We try our best to express stride in terms of the sizes, so as to not
        introduce new symbolic variables.
        r   c                     t        | t        t        j                  f      sJ t	        |       r9| j
                  j                  usJ d       | j
                  j                         S | S )NzFexpect the symbol is created from an shape env other than current one.)rx   r|   rd   r   r   ry   r  rz   )	maybe_symrT  s    r9   "maybe_specialize_sym_int_with_hintzaShapeEnv.create_symbolic_sizes_strides_storage_offset.<locals>.maybe_specialize_sym_int_with_hint0  sa    i#u||)<===9% ~~//t; ]\]; ~~2244r8   c              3   .   K   | ]  } |        y wrk   r7   )r   szr8  s     r9   r   zHShapeEnv.create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>8  s     S2:2>   c              3   .   K   | ]  } |        y wrk   r7   )r   sdr8  s     r9   r   zHShapeEnv.create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>9  s     W;R<R@;r;  rv  )
	is_nestedr|   r   r   r   r   -_create_symbolic_sizes_strides_storage_offsetr  rv   _is_dim_dynamic)	rT  r*  rP  rw  r'  	ex_strideex_storage_offsetr   r8  s	   `       @r9   ,create_symbolic_sizes_strides_storage_offsetz5ShapeEnv.create_symbolic_sizes_strides_storage_offset  s    ^ <<	S 	 SSSW299;WW	>r?P?P?RSAA-22668_=__R#_=- B 
 	
 >s    B=rA  rB  is_dim_dynamicc                   t        |      }|d g|z  }g }	t        |      D ]V  }
||
   rt        j                  }n-| j                  rt        j
                  }nt        j                  }|	j                  |       X t        j                  g|z  }	t        |	|      }t        |       |j                  }|j                  }	t        d |	D              rt        j
                  nt        j                  }t        |	      |k(  sJ t        |	       d|        t        |      |k(  sJ ddlm}m} | j!                  |||      }d gt        |      z  }t#        |      D ]"  \  }
}|dv st%        j&                  |      ||
<   $ t)        d |D              r9t        t        |            D 
ci c]$  }
||
   ||
   dk\  r||
   ||
   z  ||
   ||
   z  & }}
t+        t        t        |            D 
cg c]  }
||
   	||
   |
f c}
      }|D ]5  \  }}
||
   ||
   |v s|||
      ||
<   ||
   ||
   z  |||
   ||
   z  <   7 t)        d |D              rbt-        t        t        |            D 
cg c]  }
||
   ||
   |
f c}
      \  }}
| j/                  | |||j0                  |
      |d 	      ||
<   t)        d |D              r9t        d
 |D              sJ t#        t3        ||            D 
cg c]/  \  }
\  }}| j5                  || |||j6                  |
      |      1 }}}
}g }t#        |      D ]B  \  }
}|J |j                  | j5                  |||
    |||j0                  |
      |             D | j5                  | j/                  | |||j8                        |d 	      | |||j8                        |      }t;        |      t;        |      |fS c c}
w c c}
w c c}
w c c}}}
w )N)r{  r|  c              3   B   K   | ]  }|t         j                  k(    y wrk   )rB  rF  )r   r  s     r9   r   zIShapeEnv._create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>n  s     9gZfUV!z?P?P:PZfs    != r   r/  r  c              3   $   K   | ]  }|d u  
 y wrk   r7   r   r   s     r9   r   zIShapeEnv._create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>y  s     ,V!t)Vr  c              3   $   K   | ]  }|d u  
 y wrk   r7   rI  s     r9   r   zIShapeEnv._create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>  s     -f19fr  )dynamic_dimconstraint_dimc              3   $   K   | ]  }|d u 
 y wrk   r7   rI  s     r9   r   zIShapeEnv._create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>  s     1&Q1D=&r  )r  rP  rw  )r   r  rB  rD  r  rF  rE  rr   rP   rx  r|  r{  r   r1  r  r0  r)  r  r   r   r   r  r   r2  STRIDEr  r  r3  STORAGE_OFFSETr   )rT  r'  rA  rB  rD  rP  rw  rv   r  r4  r   r  dynamic_strides_offsetr  r0  r   r   r   
candidatesval_listr$  symr  	sym_sizes
sym_stridestride_exprsym_storage_offsets                              r9   r?  z6ShapeEnv._create_symbolic_sizes_strides_storage_offsetE  s}    'l ##fslOL3Z "!$"**A22"))A"A##A&   'OO,s2L7letu/0*;;'55 7:9gZf9g6g!2!2mwm|m|< C'HC,=+>d3%)HH'?#s***M!%!G!GQWYi!j.2Vc$i-?	*FAsf}!MM#.q	 + ,V,, s4y))A!9(Yq\Q-> 
Yq\)47VAY+>>)   ,1#f+,>T,>q&)BS)A,",>TH !1!9$1)C *9Q< 8F1I<@GfQi<OJwqzIaL89 !
 -f-- "'s6{!3!3A!!9, #1q)!3Q !..(1F1FJ 6#'	 / q	1 ,V,,< 1&1111 #,Cg,>"?
 #@;C ""+FN4G4GK!1	 #  #@ 	 
 
'/NA{ ***d44)A,7KFTbTiTikl7m!1 5 3 4	 0 "33!$V^-J-JK2#	   #'0M0MNaq 4 s Yz!24FFFs U
s   &)O!,
O&7	O&.O+64O0)rP  rw  rS  
sympy.Exprr  c          	      :   |r|j                         nd }| j                  rS|Q| j                  |      }|J | j                  |t              }| j                  t        j                  ||             nd }t        |t              r|r||j                  v r|j                  |   S t        |t        j                        r|t	        |      |k(  sJ t	        |      }nt        t        || t        ||            }t        |t              r|r||j                  |<   |S )Nfx_node)r   r  r  r  r|   r  r   r   rx   rQ   r  r   r   r   )	rT  rS  r  rP  rw  source_namer  r[  outs	            r9   r  zShapeEnv.create_symintnode  s    (.fkkm4//F4F33F;F%%% ::63GG  56G &(?@[.JJJ'CCKPPc5==)3x4'''c(CdCwGHC&(?@[HK88E
r8   c                 N    | j                  | j                  |||      ||      S )N)rP  rK  )r  rP  )r  create_unspecified_symbol)rT  r  rP  rK  s       r9   $create_unspecified_symint_and_symbolz-ShapeEnv.create_unspecified_symint_and_symbol  s>    %%**' + 
  & 
 	
r8   c                 8    t        t        || t        d             S rk   )r   r   r   )rT  rS  s     r9   create_symboolnodezShapeEnv.create_symboolnode  s     wsD$566r8   c           	      t   t        j                  dt        | j                               }| j                  dxx   dz  cc<   t        j                  d      | j                  |<   t        j                         | j                  |<   | j                  |t              }t        t        || t        d |            S )Nr   create_unbacked_symbolro   r  rZ  )r   r   r   r  r  r.   extractr  r*   unknownr   r  r   r   r   rT  r  r[  s      r9   create_unbacked_symfloatz!ShapeEnv.create_unbacked_symfloat  s    $||aT5S5S0T/U,VW-.!3.$5$=$=1$E&!$/$7$7$9&! 66vuEeT7KLLr8   c           
      
   t        j                  dt        | j                         d      }| j                  dxx   dz  cc<   t        j                  d      | j                  |<   | j                         x}| j                  |<   | j                  |t              }| j                         \  }}}t        j                  d||j                  |j                   |t#        |             t%        t'        || t        d |            S )	Nr   Tr  rd  ro   re  z)create_unbacked_symbol %s [%s, %s]%s (%s)rZ  )r   r   r   r  r  r.   rf  r   _default_unspecified_value_ranger   r  r|   _get_stack_summaryr   r  r   r   r-   r   r   )rT  r  rO  r[  fsummaryuser_tbmaybe_user_locs          r9   create_unbacked_symintzShapeEnv.create_unbacked_symint  s    $||aT5Q5Q0R/S,T^bc-.!3.$5$=$=1$E&!)-)N)N)PPTv& 66vsC,0,C,C,E)'><fbhhPRPXPXZhjvw  kA  	BgfdCwGHHr8   c                 6    t        |      j                  d      S )Nr   )r  r   )rT  r  s     r9   is_unbacked_symintzShapeEnv.is_unbacked_symint	  s    6{%%c**r8   c           	         t        j                  dt        | j                         d      }| j                  dxx   dz  cc<   t        j                  d      | j                  |<   t        dd      | j                  |<   | j                  |t              }t        t        t        j                  |d      | t        d |            S )	Nr   Tr  rd  ro   re  r   rZ  )r   r   r   r  r  r.   rf  r  r*   r   r  r   r   r   r   rh  s      r9   create_unbacked_symboolz ShapeEnv.create_unbacked_symbool	  s    $||aT5Q5Q0R/S,T^bc-.!3.$5$=$=1$E&!$/1$5&! 66vtDwuxx2D$gVWWr8   r   rK  rL  c                 0    | j                  ||||d d      S )NT)positivedo_not_specialize_zero_one)r2  )rT  r   rP  rK  rL  s        r9   r_  z"ShapeEnv.create_unspecified_symbol	  s$     !!#v{NUYvz!{{r8   rv  rw  c                    |rd}n| j                   }t        |t              sJ t        |       d|        |r|dk  r
J d|        |t        j
                  }|t        j                  u rt        j                  |      S |t        j                  u r| j                  }n#|t        j
                  u rd}nt        d|       |dv r|r| j                  |   }	ns|r|| j                  vr(t        j                  dt        | j                         |d	      }
t        |t               r#t        j                  |      | j                  |
<   nJt#        |j$                  j'                         |j$                  j)                         
      | j                  |
<   g | j*                  |
<   | j-                  |
t                |r|
| j                  |<   t        |t               r|r2| j/                  |
dkD         | j1                         | j2                  |
<   n| j5                         | j2                  |
<   t        |t6              r%|rJ | j2                  |
xx   |j8                  z  cc<   | j2                  |
   }||vr(t;        | d|j<                   d|j>                   d      || j@                  |
<   d|j<                   d|j>                   d}nd}|
}	| jB                  jE                  d|
||jG                         |       | jH                  dxx   dz  cc<   n:| j                  |   }	| jB                  jK                  d|	|jG                                t        |	t        j                        r| j*                  |	   jM                  |       |	S )NFr   r   z!positive set for negative value: zunhandled dynamic_dim r  r   Trv  r   )coeffro   z not in range [rl  r  [r'  zcreate_symbol %s = %s for %s %sr2  zcreate_symbol %s duck sized %s)'r  rx   r!   r{   rB  rD  rF  r   r   rE  r  r   r  r   r   r  r|   r,   ry   singleton_intsingleton_coeffr  r  r  _default_value_ranger   rk  rN  rO  ri   r   r   r  r   r  r   r  r   rr   )rT  r   rP  rK  rL  rv  rw  r  duckr  
sympy_exprrO  	range_strs                r9   r2  zShapeEnv.create_symbol*	  s%    &"'"&":":&&)Ed6l^1VH+EE)qT-Nse+TT) %$,,K*+++ ==%%JOO+ ??DJ...D #9+!GHH&=0$ADOO3 #doo*>)?&@8]abJ#s#.3mmC.@
+ /;388;Q;Q;S[^[c[c[s[s[u.v
+ /1D
+OOJ,'1$#s#''
Q7 594M4M4OD%%j1484Y4Y4[D%%j1 n.DE#O8%%j1^5F5FF1&&z2b=2cU/"((SUVXV^V^U__`3abb 9;))*5zBHH:Q7	 	AHHMM;Zfkkm]fgLL)Q.) $AHHNN;QNa&"))&1r8   c                 Z    |j                         }| j                  j                  ||      S rk   )r   r  r   )rT  rP  src_names      r9   rS  zShapeEnv.debug_name	  s&    ;;=--11(HEEr8   c                    t        |t              r|j                  j                  |j                  j                  }}| j                         }||j                  k  rd }||j                  k\  rd }| j                  |       d|j                          d}|!||d| d| j                  |       d| z  }|S |||d| j                  |       d| z  }|S |||d| d| j                  |       z  }|S |j                  |      S )NrQ  z in the specified ranger   rR  )	rx   rN  rO  r   r   r~  rS  r   rU  )rT  rP  r  r   r   defaultc_renders          r9   %render_range_for_constraint_violationz.ShapeEnv.render_range_for_constraint_violation	  s'   a/044::qttzz5E//1G%%//&12#fkkm_D[\H U%6awd4??6+B*C4wOO
 O	 5#4a 78UGDD O "u}awd4??6+B*CDDOxxr8   c                 "    | j                         S rk   rZ  r  s    r9   r  zShapeEnv.<lambda>	  s
    QVVXr8   )constraint_inputsequalities_inputs_simplifiedr3  r  r  c                   789:;<=>?@AB  j                   j                  d        j                  r&t         j                        } j                  |       t              t        |      k(  sJ t        j                  t        f}	|0D 
cg c]$  }
t        |
|	      rd g|
j                         z  nd & }}
nt        |      t              k(  sJ t        t        |            D ]w  \  }\  }
}t        |
|	      r9|d g|
j                         z  ||<   /t        |      |
j                         k(  rLJ t        |
t        t        f      sJ t        |t               swJ  ddlm9m8m7 g <t+        j,                  t               Bt+        j,                  t.              Ag :d%:fd	?89fd=|ri @t        |      D ]  \  }}|@|j1                         <    @fd}|j2                  D ]  \  }} ||       ||      }} j5                  t7        j8                  ||            }|r>t;        |j1                          d j<                  |    d|j1                          d j<                  |           d%7<? ABfd		}t        ||      D ]  \  }
}}t        |t>              rdd
lm }  ||      }t        |tB              sJ |
;t        |
t        t        f      r
 |||
       [t        |
|	      sJ ||
fg}tE        |
      r[|
jG                         \  }}ddlm$} |D cg c]  } |||      tK        |
|      f }}|
jL                  r|jO                  |       n|}|D ]  \  }}t        |jQ                               D ]&  \  }} 9|8jR                  |      } |||||          ( |
jL                  rUt        |jU                               D ]   \  }} | 9|8jV                  |      |       "  | 9|8jX                        |j[                                  g ;t]        B j<                  t/        Aj_                                j`                         _1        |s'<D ]!  \  }}  jd                  rP|j1                         }!|! jf                  v r2 ji                  t7        j8                   jf                  |!   |              t        | t6        jj                        rBjm                  |       r|B|    d   k(  r|r@t        |9      r4| jn                  r( j                   jq                  d |       d|          =|      r jb                  js                  ||        tu        B jv                        jy                  |       }";j{                   |       d|"        t        | t6        jj                        s^| Av sdt        |9      sr|j|                  8jR                  u s|s|j                  |B|    d         rd j                  |       d|j1                          d j                  B|    d          dB|    d   j1                          d	}# ?|j                   j                  |      |#       $ t/               >dt        dd f;=>? ABfd}$ j                  D ]&  }% j                  |%j                         |$|%       (  j                  j                         D ]  \  }&}'|&Bvr|'D ]  }%|% |$|%         |sBj                         D ]  \  }&} j                  jm                  |&      }(|(|& j                  vr3 j                  |&   }(|sJ |&j                  sJ  j                  jm                  |&d      \  })}*g }+|(j                  t6        j                   k7  rs|)qt        =fd|D              r9 jb                  j                  t7        j                  |&|(j                               |+j{                  t?        |(j                               |+j{                   |d                |(j                  t6        j                  k7  r|(j                  t        j                  dz
  k  rs|*qt        =fd|D              r9 jb                  j                  t7        j                  |&|(j                               |+j{                  t?        |(j                               t        |+      dkD  s;j{                  dj                  |+              :rg },g }-t/               }.:D ]_  \  }/}0}#|/r+dt        |,      dz    d |#        }#|,j{                  |#       4d |#        }#|-j{                  |#       |.j                  |0       a t        |-      dkD  r3dj                  |.      }.dj                  |-      }1t;        d|. d|1       t        |,      dkD  rt         jq                  d t        |,             t        d!di  j                   j                  t        ;      t        d" Bj                         D              d#        jd                  rKdd$lZm[}2  j                  j                         D ]$  }3|3D ]  }4 ji                  |4j                          &  j                  j                         D ]  \  }5}6|6j                  t6        j                   k7  r/ ji                  t7        j                  |6j                  |5             |6j                  t6        j                  k7  sq ji                  t7        j                  |5|6j                                t        j                         5   |2 j                   j                        j                          d d d         j                          ;S c c}
w c c}w # 1 sw Y   %xY w)&Nproduce_guardsr   )r  r0  NegateSourcec                 :    j                  | |fdf       y )Nc                  "     r           S S rk   r7   )r  r  s   r9   r  zNShapeEnv.produce_guards.<locals>.record_constraint_violation.<locals>.<lambda>4
  s    D3%x0@0Qc0Qr8   )rr   )rK  rS  r  r  constraint_violationss     ``r9   record_constraint_violationz<ShapeEnv.produce_guards.<locals>.record_constraint_violation2
  s    !((J(QRr8   c                 P    t        |       xr | j                  j                  u S rk   )rx   propr3  )rR  r0  r  s    r9   is_dimz'ShapeEnv.produce_guards.<locals>.is_dim7
  s%    c#78\SXXI\I\=\\r8   c                     | j                   j                               }|j                  | j                     }t	        |t
        j                        sJ |j                  j                  S rk   )	r  r   rt   r  rx   rd   r   ry   r   )tensor_dim_srcr  symintplaceholderssource_indexs      r9   
get_symbolz+ShapeEnv.produce_guards.<locals>.get_symbol?
  sY    #L1D1D1I1I1K$LMN$6$67!&%,,777{{'''r8   rQ  z is not equal to c           	      .   t         j                  dt        | j                        ||       t	        |t
              rt        |      sJ t	        |t
              r4|j                  j                         |j                  j                         }t	        |t
              r|j                  j                  }t	        |t        j                        r-|   j                  |        |q|   j                  |       n[t	        | t        j                        r|    j                   |              n#d}t	        |t              ru|j                  D ci c]  }|j                   j#                  |d       ! }}t%        d |j'                         D              rt)        ||      }||j*                  k7  r6d}n3d}n0t	        |t,              r |j.                  rt1        |      }|dvrd}nd}|rjfd}	j3                  | |      }
d|
 dj5                  |        d	} |j6                  j5                  |       |t9        j:                  |	|      
       j                  | |f       y t        j<                  |      }j                  | |f       d}t	        |t              rd}nt	        |t,              r|dvrd}|rQj3                  | |      }
d|
 dj5                  |        d| d} |j6                  j5                  |       |       y y c c}w )Nztrack_symint %s %s %sFc              3   $   K   | ]  }|d u 
 y wrk   r7   )r   rO  s     r9   r   z@ShapeEnv.produce_guards.<locals>.track_symint.<locals>.<genexpr>n
  s     I8H"r~8Hr  Tr  c                 Z    t        j                        j                  |       }| dS )N.)r  r  rH  )r   rM  rT  r  r  s     r9   r  z;ShapeEnv.produce_guards.<locals>.track_symint.<locals>.hint
  s1    $56F
TXTgTg$h$p$pqr$sE&+WA;.r8   Not all values of z are valid because z was inferred to be equal to r  z  was inferred to be a constant (z).)r   r   r0   r   rx   r   r   ry   maybe_as_intr   r   r   rr   r  rN  rH   r   r   r   valuesr(   rO  rW  r   r|   r  rS  rK  r   partialr   )rP  r   
constraintr   constraint_violatedr   sym_vrsexpr_vrr   r  var_with_ranger  r  input_guardsr  rT  r  symbol_to_constraintsr  s               r9   track_symintz-ShapeEnv.produce_guards.<locals>.track_symintZ
  s   II-z&++/FZX!#v.+c2BBB#v&388+@+@+B+Nhh++-#v&HHMMa.$Q'..v6!--a044Z@ELL1$aR(//V0DE*/'!*.DENOnn"]n1d&7&7&;&;At&D#Dn"]I8HII&1!W&=G ':== 86: 3 37/#J0GH;; #AA  !6: 3 37/*/ *.)S)STZ\f)g00@@S#v677TV  4&00 OOF3!*!2!24!;	 ##VQK0MM#&##VQK0&+#j*@A*.'
,CD &(.2+&%)%O%OPVXb%cN,^,<<O??6233STWSXXZ\  0
0D0DdooV\F]_bc 'c #^s   $LLocalSource)
AttrSourcezSkipping guard %srn  zThe values of r  z must always be equal.guardr   c                    j                  | j                        }|v ry j                  |       	 d}t        fd|j                  D              rj
                  j                  |      }t        j                        j                  |      }
j                  |       j                  |       |st        |j                        dk(  rt        t        |j                              }|   d   }|   }|D ]o  }t        |t              r?j!                  ||      }d| d| d}	 |j"                  j%                  |      |	       Rt        |t&              rct)        d|        y y y # t*        $ rE j,                  j/                  d	d
j1                  | j2                  j5                                       w xY w)NFc              3   B   K   | ]  }|   D ]  } |         y wrk   r7   )r   r   rP  r  r  s      r9   r   z?ShapeEnv.produce_guards.<locals>.issue_guard.<locals>.<genexpr>  s(     c/@!O_`aObVvf~Ob~/@s   ro   r   r  z satisfy the generated guard r  zunrecognized constraint zFailing guard allocated at: 
%sr'  )simplifyr   r  r   rH   r  r  r  rH  rr   r  r   r   r  rx   rN  r  rK  rS  rW  r   	Exceptionr   r  rq  r  r  )r  r   
is_trivial
guard_exprr  rP  constraintsr  r  r  r?  r  issuedr  rT  r  r  r  s             r9   issue_guardz,ShapeEnv.produce_guards.<locals>.issue_guard  s   ==,D v~JJt"
ct/@/@cc!%!5!5!9!9$!?J./?TM`M`aiijno
Z(%%d+ "c$*;*;&<&A!$t'8'8"9:F-f5a8F"7"?K(%a)?@-1-W-WX^`a-bN"4^4D E??Il!!M   8T__U[E\^ab'+BC
 !"03KA31O"PP )	 'Bz(    !CRWWU[[M_M_MaEbcs   D=E4 4AGr  c              3   .   K   | ]  } |        y wrk   r7   r   rP  r  s     r9   r   z*ShapeEnv.produce_guards.<locals>.<genexpr>Z       @f6&>r;  ro   c              3   .   K   | ]  } |        y wrk   r7   r  s     r9   r   z*ShapeEnv.produce_guards.<locals>.<genexpr>f  r  r;  rR  z  z. rt  rl  r6  zConstraints violated (rs  z$%s Warning only constraints violateddynamicc              3   &   K   | ]	  }|sd   ywro   Nr7   )r   rc  s     r9   r   z*ShapeEnv.produce_guards.<locals>.<genexpr>  s     #N/H!AA/Hs   )
num_guardsrH   )PopulateValidatorrk   )cr   r  r  r   r  r  r   rd   r   r   rx   rv   r  r  r   r|   rs   r1  r  r0  r  r  r   r   r   r]  evaluate_exprr   r   ri   r  r  r  r!   r#   __tensor_flatten__r  r  r>  extendr   r3  r   rN  rO  r   r  r   r  r  r  r  r  r   r   r   r   r  r  r  rH  rr   r  rt  rS  rK  r    r  _maybe_evaluate_staticr   r  r  r  r   
is_integerr   r  r   r  r   r   rX   r  r   rq  r/   r  r  sumr  r  r  r  fx_tracebackpreserve_node_metar   r  runr  )CrT  r  r  r  r  r  r  r3  r  
Tensorliker   r   r  rR  r  src1src2s1s2concrete_valr  rP  r  sources_and_tensorsattrsr$  r  attrinner_sources_and_tensorscurr_tssproperty_sourcer   r  rM  r  r  r  r  r  r  g_lowerg_upperbounds	warn_msgs
error_msgsr  rK  rS  errr  r  r  rS  rO  r  r0  r  r  r?  r  r  r  r  r  r  r  sC   `` `                                                   @@@@@@@@@@@@r9   r  zShapeEnv.produce_guards	  s
     	&' %%/<IY'< CL000llN3
 $Q]!Q]AJq*$= 4GQ]  ! ()S->>>>&/LBS0T&U"?Aza,!)04v/?)!,":!%%'999%a&#777)*d;;; 'VJ 	\[ &2248 + 7 7 <GI	
	] L#G,3+,SXXZ( -( 0<<
d#D):d+;B#11%((2r2BC#299;-s4??2+>*?+99;-s4??2+>*?A 	 =*J	d J	dX &)w@Q%R!Avz&#&<$V,ff---y!fc]+VQ'a,,,$*A;-,Q/ //1q;fk,lfk^bj.FPQSWHX-Yfk),l;;
 (../HI +D'2V&v{{}5EAr&:3@S@SUV&WO "jmD 6 {{!*6==?!;2$%9#~?T?TVW%XZ\] "< !5c>;X;X!Y[a[p[p[rs  3; &ST -OO%**,-**	 
  ,77$kkmG$"7"77--ehht7L7LW7UW[.\] tU\\2$((..t4Q77
 !Z8L%M~~':z&?Q>RRVW[V\<]^ &>((55fdC)*:JH[H[\ddeij
6 234w?@tU\\211v';<~':'::))226;KD;QRS;TU ))@(AV[[]OSX??+;D+A!+DEFcJZ[_J`abJcJhJhJjIk l00 
 00A0K0KT__]cMdfijS !-d (	z (	d (	 (	V [[E**5::6B ! #00668NFF--$&   9 #3#9#9#;--11&99T%6%66 ))&1Aw((((#'#5#5#9#9&,#O 77uxxi'GO@@@,,00&!''1JKMM#agg,/j45 77ehh&177S[[1_+D@@@,,00&!''1JKMM#agg,/v;?LLV!459 $<< !IJ%K.C*	:ss9~12"SUG<C$$S) .C%%c*OOJ/ /D :""ii4ii
+.,[M :Ke 
 Y!#		@#i.Q..,, "%j ##N/?/F/F/H#N N			
 //I
 44;;=B))"''2  >  ,,224R88y())%((288S*AB88uxx'))%((3*AB	 5 002!$**dnn=AAC 3 	((*Y!r -m^ 32s   )o(o
,oo#c           	          ddl m} t        t        |            D cg c]  }d| 	 }}| j	                  ||D cg c]
  } ||       c}|      }|rdj                  |      S yc c}w c c}w )a  
        Expected to be used with evaluate_guards_expression(). Produces the guards
        for the given placeholders and returns a string expression to be evaluated
        by evaluate_guards_expression given concrete values for the placeholders.
        r   r  r   r2  r  N)r1  r  r  r   r  rq  )rT  r  r3  r  r   	arg_namesr}   r  s           r9   produce_guards_expressionz"ShapeEnv.produce_guards_expression  sv     	5&+C,=&>?&>qW&>	?$$\I3VIqKNI3Vfs$t<<''	 @3Vs
   A'A,
c                     t        t        |            D cg c]  }d| 	 }}t        |t        dt	        t        ||            i      S c c}w )z
        Expected to be used with produce_guards_expression(). Evaluates an expression
        generated by produce_guards_expression for the given concrete args.
        r   L)r  r   evalrG   r  r  )rT  coder   r   r  s        r9   evaluate_guards_expressionz#ShapeEnv.evaluate_guards_expression  sN    
 ',CI&67&6qW&6	7D,d3y$3G.H(IJJ 8s   Ar2  c                R    | j                  ||      }|r| j                  ||      S y)Nr2  T)r  r  )rT  r  r   r3  r  s        r9   r5  z!ShapeEnv.evaluate_guards_for_args  s0    --l--X224>>r8   c                    i fd}t        ||      D ]  \  }}|	t        |t              r
 |||       #t        |t        j                        sJ t        |j                               D ]  \  }} ||j                  |      |        t        |j                               D ]  \  }} ||j                  |      |         ||j                         |j                                 S )Nc                 T   t        |t              r|j                  j                  }t        |t        j
                        r"|v r|   | k(  sJ |    d|         | |<   y y t        | t        j
                        r)| v r|    |  k(  sJ |     d|          y |  | <   y y y )NrG  )rx   r   ry   r   r   r   )rC  r   r   bindingss      r9   bind_symintz*ShapeEnv.bind_symbols.<locals>.bind_symint  s    #v&HHMMa.H}'{c1Lhqk]$se3LL1&)  2  ELL1rX~'|t3P!~T3$5PP3(+t!	 2 'r8   )	r  rx   r   rd   r   r  r   r   r   )	rT  r  r   r  r   rC  r   r   r  s	           @r9   r8  zShapeEnv.bind_symbols  s     -/	, ,-FAsy!V$C#a...!!&&(+1CHHQK+ ,!!((*-1CJJqM1- .**,a.>.>.@A . r8   c                     | j                   D cg c]9  }| j                  |j                        | j                  |j                        ; c}S c c}w rk   )r  r  r   r  )rT  r  s     r9   get_nontrivial_guardszShapeEnv.get_nontrivial_guards  sB    7;{{v{edFaFabgblblFmFuejj){vvvs
    AAc                 X    fddj                  fd| j                  D              S )Nc                 \    syddj                  d | j                         D               S )Nr'  z
   Guarded at:
c              3   &   K   | ]	  }d |z     yw)z   Nr7   )r   ls     r9   r   z<ShapeEnv.format_guards.<locals>.format_tb.<locals>.<genexpr>  s     /O;a	;s   )rq  r  )tbverboses    r9   	format_tbz)ShapeEnv.format_guards.<locals>.format_tb  s,    '/O299;/O(O'PQQr8   r6  c              3   `   K   | ]%  }d |j                     |j                          ' yw)z - N)r   r  )r   r  r  s     r9   r   z)ShapeEnv.format_guards.<locals>.<genexpr>  s-     ]Q\3uzzl9U[[+A*BCQ\s   +.)rq  r  )rT  r  r  s    `@r9   format_guardszShapeEnv.format_guards  s'    	R
 yy]QUQ\Q\]]]r8   c                     t        j                  t              }| j                  j	                         D ]  \  }}||   j                  |        |S rk   )r  r   rs   r  r  rr   )rT  shape_groupsrb  rc  s       r9   get_shape_groupszShapeEnv.get_shape_groups  sG    "..t4%%++-DAqO""1% .r8   )unbacked_onlycompute_hintexpect_rationalr   r  r  zOptional[sympy.Expr]c          	         | j                  |      }|r|j                  | j                        }t        |      }t	        |j
                        }|D ]  }|| j                  v ri }| j                  j                  |d      D ]  }|r/t        |j                  j                  | j                              }	n|j                  }	t        j                  ||	<   t        j                  |t        t        j                  |	            <   t        |	t        j                        st        j                  |t        j                  |	j                   |	j"                        <   t        j                  |t        j                  |	j                    |	j"                         <   t        j                  |t        j$                  |	j                   |	j"                        <   t        j                  |t        j$                  |	j                    |	j"                         <    |j'                  |      } i }
i }t)        |      D ]  \  }}t        | j                  j                  |d      t*              r1| j,                  |   }|j.                  t0        j2                   dz
  dz  k  s|r|| j                  v r|||<   zt        j4                  d| dd      }|j.                  dz
  }||z   |
|<   t7        j8                  ||       ||<    d }	  |||
      }i }|jC                  tD              D ]7  }t        jF                  |jH                  d   |jH                  d   z        ||<   9 tK        |j                  |            }|jL                  r|S tO        ||      }|r(tQ        ||       |jS                         r|j.                  S |r|S dS # t:        $ r1 t<        j?                  d	||
       | j@                  d
xx   dz  cc<   Y yw xY w)a-  
        Tries to evaluate expr without introducing guards

        If unbacked_only == True, then we only do substitutions on
        unbacked SymInts (leaving regular hinted integers alone).  This could
        result in an expression that still contains backed SymInts, which you
        could then potentially guard on.

        Use compute_hint == True if you are trying to compute a non-binding
        hint for the particular hint values of backed SymInts, e.g., if
        s0 happens to be 3 this run, compute_hint will subsitute s0 with 3.
        r7   Nro   r
  shape_Try  c                 $    | j                  |      S rk   )xreplace)r   repls     r9   r  z0ShapeEnv._maybe_evaluate_static.<locals>.replaceV  s    ==&&r8   z(RecursionError in sympy.xreplace(%s, %s)sympy_recursion_errorr   )*r  r  r  rE   rs   rH   r  r   r   r   r  r  r   rx   r   r   r   r   r   r
  r  r,   r   r   rX   r  r   r)   r  r  r   r  r  r<  r$   r  r   r  r   r(   r@  is_singleton)rT  r   r  r  r  r!  r   substr  r   new_shape_envnew_range_envr  rb  rO  offsetr  new_exprfloor_div_replacer=  r]  s                        r9   r  zShapeEnv._maybe_evaluate_static  sH   " }}T"==1D%d+t(() ADOO#E33772>.rww/?/?/PQAA ::a>Ckk,UYYq\:;a*49JJE%((155!%%016;jjE%((AEE6AEE62349KKE%((155!%%016;kkE%((AEE6AEE623 ? 99U#D) . (FC$//--a6E ""1%B
 S[[L1,221#7#%a  vcU^dDIAXX\F 6zM!6::2wGM!3 )6	'	t]3H NN8,D&+kk$))A,12M&Nd# -x001BCD O (M2%h4!yy (x2d2+  	KKBD-XLL01Q61	s   	O   7O:9O:c           
          |j                   D ci c],  }|| j                  t        t        j                  |            . }}t        |j                  |            S c c}w rk   )rH   r  r
   r   r   r  r  )rT  r   r   r  s       r9   r  zShapeEnv.replacer  sQ    FJFWFWXFW4::d5<<&;<<FWX4==677 Ys   1Ac                     t               }| j                  D ]1  }| j                  |      }|j                  r!|j	                  |       3 || _        | j                          y rk   )r   r  r  r   r  r&  )rT  new_divisiblerb  ress       r9   _update_divisiblezShapeEnv._update_divisiblew  sN    A,,q/C==!!!$  
 '$$&r8   c                     | j                  |      }|j                  t              r| j                          i }|j	                  t              D ]  }|j
                  \  }}t        |t              s#|j
                  \  }}| j                  t        ||            | j                  v sZ||k(  s`| j                  t        ||            | j                  v s|||<    |j                  |      }t        |      }|j                  t              roi }|j	                  t        j                        }|j	                  t        j                        j                  |j	                  t        j                              }	|j	                  t              D ]A  }
|
j
                  \  }}| j                  t        ||            | j                  v s:||z  ||
<   C |j                  |      }t        |      }|j	                  t        j                        }|j	                  t        j                        j                  |j	                  t        j                              }|j!                  |      r|j!                  |	      r|}|S rk   )r  r>  r$   r  r<  r   rx   r%   r  r  r  r   r?  Rational
differencer   issubset)rT  r   div_replacementsr=  r  r  base1divisor1pows	rationalsfdr  new_powsnew_rationalss                 r9   r  zShapeEnv.simplify  s   ||D! 88H""$!

8, $		ggx0&-llOE8||Cg$674>>I EMdll3uh;O.PTXTbTb.b19(. - ==!12Dt$D88H!::eii(D

5>>2==djj>WXIjj* "g<<D' 23t~~E+/'>$R( + }}%56H"8,H~~eii0H$NN5>>:EEhnnUZUbUbFcdM  &=+A+A)+Lr8   r  
allow_nonec                    t        |      j                  | j                        }|j                  s,| j	                  |d      }||S |ry| j                  ||      |S )a  
        Gets a size hint for a given expression from the underlying shapes we had.
        Does not introduce a guard, so only use this when you can guarantee that
        your code is still valid for arbitrary shapes (such as optimization decisions)
        T)r  N)r  r  r  r   r  _make_data_dependent_error)rT  r   r  result_exprr  s        r9   	size_hintzShapeEnv.size_hint  sd     "$'00A$$++Kd+KA}11+tDDr8   c                     t        |      j                  | j                        }|j                  xs | j	                  |      d uS rk   )r  r  r  r   r  )rT  r   r  s      r9   r   zShapeEnv.has_hint  s=    !$'00A$$\(C(CK(PX\(\\r8   c                     |j                   D ]K  }dj                  | j                  |   j                               }| j                  j                  d||       M t        d| d| d      S )Nr'  z-Data dependent variable '%s' allocated at:
%szIt appears that you're trying to get a value out of symbolic int/float whose value is data-dependent (and thus we do not know the true value.)  The expression we were trying to evaluate is z (unhinted: zU).  Scroll up to see where each of these data-dependent accesses originally occurred.)rH   rq  r  r  r   r   r2   )rT  r   unhinted_exprr   
stacktraces        r9   r  z#ShapeEnv._make_data_dependent_error  sx     ""A!2!21!5!<!<!>?JHHNNKQPZ[ # +<<@6m_ ]``
 	
r8   c                    t         j                  rt        |t        j                  t        j
                  f      rx|| j                  vs|| j                  |   k7  rX| j                  j                  d| j                  |   d   j                         |       | j                  j                  dd       t        j                  d||       || j                  |<   | j                          | j                  t        j                  ||             y)zx
        Adds or updates a replacement for a symbol.
        Use this instead of `self.replacements[a] = expr`.
        zSpecializing %s to %sr   SPECIALIZATIONT
stack_infozset_replacement %s = %sN)r  print_specializationsrx   r   r   Floatr  r   r  r  r   r   r  r&  r  r   )rT  r}   r   s      r9   _set_replacementzShapeEnv._set_replacement  s    
 ''JtemmU[[=Y,Z )))TT5F5Fq5I-I  !8$:M:Ma:PQR:S:X:X:Z\`a/DA*At4#!$$& 	ehhq$/0r8   c                 Z    | j                   j                  |       | j                          y rk   )r  r  r&  r  s     r9   _add_divisiblezShapeEnv._add_divisible  s     4 $$&r8   c                    || j                   vr|S | j                   |   }|j                  D ci c]  }|| j                  |       }}| j                  || j                   |   j	                  |             | j                   |   S c c}w )z
        Implements a DSU-like algorithm to find the variable that represents a
        Also handles transitive non-identity replacements.

        a: b + c
        c: d
        )r  rH   r  r*  r  )rT  r}   r  r   cur_replaces        r9   r  zShapeEnv._find  s     D%%%H"141A1AB1AAq$**Q-'1ABa!2!21!5!>!>{!KL  ## Cs   B)zsympy.Eqzsympy.Neconcrete_boolc                 	    t        |      t        u sJ t        |t        j                        r|syt        |t        j
                        r|ryt        |j                        }t        |      dkD  s
J d|        t        |      dkD  ryt        | fdd      }|j                  }|j                  }|j                  t              s	 |j                  t              j!                  |j                  t                    }t        |      dkD  rt#        d |D              rt$        t        |t        j&                        r.t)        |      r# j+                  | j-                  |             n
t        |t        j&                        r-t)        |      r" j+                  | j-                  |             nt/        ||d   d	
      }|t1        d t        j2                  |d         D              r j-                  |d         }d	}	 j5                  |d         rt        t)        |            dk  }	nt        t)        |            dk(  }	|	r- j+                  t7        t        j&                  |d         |       |j                  t              rt9        t;        |j                  t                          }
	 t/        ||
d	
      }||d   dk(  r j=                  |
       |
j>                  \  }}t        |t        j@                        rat        |t        jB                        rFt        |j>                        dk(  r-|j>                  \  }}t        |t        j@                        rt        |t        j&                        r j5                  |      r|t        jD                  ||      z  } jG                         jH                  jJ                  }tM        jN                   jP                  |   tS        jT                  |             jP                  |<   tM        jN                   jV                  |   tS        jT                  |             jV                  |<    j+                  |||z         yy# t$        $ r Y w xY w# t$        $ r Y yw xY w)z
        Evaluates the result of an eq call. If true, uses information to
        simplify shapes (i.e. a == b or a % 5 == 0)
        Nr   z3The expression should not be static by this point:    c                 f    j                  | d      xs t        j                  | j                  fS )NTr  )r  rX   r  r   )r   rT  s    r9   r  z*ShapeEnv._maybe_guard_eq.<locals>.<lambda>  s*    4>>!>+M+\QTQ\Q\^_^d^d*er8   T)r  reversec              3   :   K   | ]  }|j                   d k7    ywr  )r  r   s     r9   r   z+ShapeEnv._maybe_guard_eq.<locals>.<genexpr>  s     3\OqAIINOs   F)floordiv_inequalityc              3   4   K   | ]  }|j                     y wrk   )r  )r   r   s     r9   r   z+ShapeEnv._maybe_guard_eq.<locals>.<genexpr>!  s     ,bCaaQ\\Car   ro   r
  ),r{   r   rx   r   r   r   rs   rH   r   r  r   r   r>  r%   r<  r$   r   r   rI  r   r   r*  r  r'   r   preorder_traversalrr  r
   r   r  r,  r   NumberMulgcdrp  ry   r   r)   truedivr   r*   wrapr  )rT  r   r/  freer   r   floor_div_atomsr  r  okmod_exprpqr  i0di1s   `                r9   _maybe_guard_eqzShapeEnv._maybe_guard_eq  s    M"d***dEHH% 
 ehh'D%%&4y1}Z STXSYZZ}t9q=d eosthhhhxx}"%))H"5";";CIIh<O"P'!+3\O3\0\--c5<<05J35O))#tzz#?U\\27LS7Q))#tzz#?!$QUKA},b5C[C[\]^_\`Ca,b)b"&**QqT"2"2247; "%%:7%C!D!IB "%%:7%C!D!IB 11$u||T!W2MwW 88C=DC12HdH%H=QqTQY''1 $==DAq!!U\\2z!UYY7OTWXYX^X^T_cdTd !2 'q%,,7&r5<<8 33B7 !"EIIaO 3A!%!<!<!>!C!C!H!HB 5L4S4S $ 1 1" 5{7G7G7J5D--b1 =T<[<[ $ 9 9" ={?O?OPQ?R=D55b9 !11"a"f= 	I ' D ' s&   F/Q0 8F6R  0	Q=<Q= 	RRc                 \    | j                   rdnd}t        |t        j                  dz
        S )Nr
  r   ro   )r  r*   rX   r  )rT  r   s     r9   r~  zShapeEnv._default_value_rangeZ  s&    --15#++/22r8   c                 Z    t        t        j                   dz
  t        j                        S r  )r*   rX   r  r~  s    r9   rk  z)ShapeEnv._default_unspecified_value_range^  s    CKK<!+S[[99r8   c                    t        |j                  t                    }t        |      D ]D  }|j                  \  }}t        ||      }t        j                  |d      }| j                  |       F | j                  |      S rU   )
r   r<  r$   rq   r   r%   r   r   r  r  )rT  r   
floor_divsr  r  r  r@  eq_exprs           r9   _simplify_floor_divzShapeEnv._simplify_floor_diva  sn    4::h/0
 :&BGGMD'4)Hhhx+Gw' ' }}T""r8   c                     | j                   rR| j                  dxx   dz  cc<   t        ddi | j                  | d| dd       t        j                  d||       y y )	Nignored_backward_guardro   r  evaluate_expr_frozenrn  r
  )ignored_guardversionz>Ignored guard %s == %s, this could result in accuracy problems)rH  r  r/   r  r   r  )rT  r   r  s      r9   _check_frozenzShapeEnv._check_frozenq  so    ;;LL12a72&nn(,vT,%@  !
 KKXZ^`lm r8   c                    d }t        j                         }	 |y|j                  j                  t	               vrJt        j                  |j                  j                  |j                  |j                  j                        }n|j                  }|y~d}t        j                         }|rdt        |d         z   }|||fS # ~w xY w)Nr'  z at rp   )rb   r  r   r!  rg   	tracebackFrameSummaryr"  co_namer  r"   extract_stackr-   )rT  rm  r#  ro  rn  s        r9   rl  zShapeEnv._get_stack_summary  s    $$&	#<<++3F3HH(5500,, H
  #   ..0#l72;&??N.00 s   A:C Cprefixc           	      4   | j                   j                  t        j                        ro| j	                         \  }}}d}d}|r)|r'ddj                  t        j                  |            z   }| j                   j                  d|||t        |      ||       y y )NFr'  zM
User Stack (most recent call last):
  (snipped, see stack below for prefix)
z%s %s [guard added]%s (%s)%sr&  )
r   isEnabledForloggingINFOrl  rq  rT  format_listr  r-   )rT  rX  r  rm  rn  ro  is_debugmaybe_extra_debugs           r9   
_log_guardzShapeEnv._log_guard  s    88  .040G0G0I-Hg~ H "G@GGI11':;< "
 HHMM.X&!#   /r8   )save_tracked_fakesc                  	   || j                  |      }nt        j                  |      }d}d}| j                  r|| j	                         s|t        j
                  u r%| j                  t        j                  |f      \  }}n|t        j                  u rI| j                  t        j                  |f      \  }}	| j                  t        j                  |f      \  }}nI| j                  t        j                  ||f      \  }
}	| j                  t        j                  |
f      \  }}|J |r| j                  |       d}d}	 |j                  rE| j                  j!                  d|       t#        |t$        t&        f      r||k(  sJ | d|        |S |}| j)                  ||      }|F| j                  j!                  d||       t#        |t$        t&        f      r||k(  sJ | d|        |S |j*                  | j,                  j/                         k  sg| j)                  |d      }|j*                  | j,                  j/                         k  s+| j1                  |j3                  | j,                        |      |}| j5                  ||       t6        j8                  rOt#        |t&              r?t#        |t        j:                  t        j<                  f      rt        j>                  |      }t#        |t        j:                  t        j<                  f      r| jA                  |t'        |             n@t#        |t        jB                        r&| jA                  t        j:                  ||      d       |t        j
                  u r|}n>|t        j                  u rt        j>                  |      }nt        j:                  ||      }| j	                         s=tE        jF                  d	
      }tI        ||      }| jJ                  jM                  |       | j	                         s)|J | jO                  |       | jQ                  d|       |S | j                  j!                  d|       |S # tR        $ r |r| jU                  |        w xY w)zO
        Given an expression, evaluates it, adding guards if necessary
        NFzeval %s [trivial]rG  )r  z eval %s == %s [statically known]Tr  ro   re  r  zeval %s [guard suppressed])+r  r   sympifyr  r  r  r  rd   _assertr  r   not_rm  r  r   r   r   rx   r|   r   r  rH   r  r   r  r  rR  r  /inject_EVALUATE_EXPR_flip_equality_TESTING_ONLYr   r   r   rF  r   r.   rf  r    r  rr   refine_rangesr`  r  r  )rT  r  r  r[  r  r  ry   r  negr$  eqlr  r  r   static_exprr  r  r  s                     r9   r  zShapeEnv.evaluate_expr  s    <>>)4L ==.L 44'113uzz)"::5==7*Ue,55hmmgZPQ"::5==3&Qe55hkkG\CZ[Q"::5==3&Qe###
 ))$/ K	@""2I>dS$K0$,F4v.FF,  D55dFU 6 WK&A9kZdS$K0&$.J;-tD60JJ.""%%)=)=)??  66t46P --1E1E1GG99$--:XZ^__t\2 JJ"4."4%((EHH)=>yy$588 45$$T4+=>
 L%--8 $$UXXdL%A4Huzz),IIdOHHT<0,,.)11q9"1e,""5) ,,.(((""5)*  ;Q?  	##D)	s   AQ/ AQ/ 3H%Q/ /Rc                 8   | j                   D ]  }|j                  j                           | j                  j	                         D ]  }|j                           | j
                  j	                         D ]#  }|D ]  }|j                  j                           % y rk   )r  r  cleanupr  r  r  )rT  r  r   r  r  s        r9   rm  zShapeEnv.cleanup6  su     AGGOO ""))+AIIK ,00779C  "  :r8   c                 ^   |}| j                  |      }|| j                  j                  d||       |S | j                  |d      }|j                  | j                  j                         k  r| j                  ||      S | j                  rM|K| j                         s;| j                  t        j                  |f      \  }}|J |r| j                  |       | j                  |t        j                         t!        |t        j"                        r| j%                  |d       | j                         st'        |      }t)        j*                  d      }	t-        |||	      }
t/        |j                  D cg c]   }|j0                  j3                  d      s|" c}d 	      }| j4                  j7                  |d
   g       j9                  |
       | xj:                  dz  c_        | j=                          | j?                  d|       y| j                  j                  d|       yc c}w )Nz*runtime_assert %s == %s [statically known]Trc  rZ  ro   re  r   c                 2    t        | j                  dd        S r  )r|   r   )r   s    r9   r  z/ShapeEnv.defer_runtime_assert.<locals>.<lambda>j  s    cfghgmgmnonpgqcrr8   r  rp   runtime_assertz$runtime_assert %s [guard suppressed]) r  r   r   rH   r  r   r  r  r  r  rd   re  r  rR  r   r  rx   r   rF  rE   r.   rf  r  r  r   r   r  
setdefaultrr   r  r&  r`  )rT  r  r  r[  r   rk  r  ry   r  r  r  r   candss                r9   defer_runtime_assertzShapeEnv.defer_runtime_assertB  s   11$7"HHNNGT_` ..t4.H  DOO$8$8$::%%h%@@ 00#--/66u}}wjQKD%###))$/4, dEHH%  t,((*)$/D%--15EtS%0Bt'8'8S'8!AFF<M<Mc<RA'8SYrsE))44U2YCJJ2N--2-((* OO,d3  HHNNA4H Ts   8 H*H*r  c                    | j                  |j                        }|j                  D ]*  }t        |t        j
                        sJ t        | j                  j                  |d       t              rKt        ||      }||j                  r|d   j                  su|\  }}| j                  |   }|j                  |j                  }	}t        || j                        }
t        ||
       | j                   j                  |d      \  }}||
j                  k  rkt        |t        j"                  t        j$                  t        j&                  f      r2|
j                  t)        t        |t        j&                              z   }|}|	|
j                  kD  rkt        |t        j"                  t        j*                  t        j,                  f      r2|
j                  t)        t        |t        j,                              z
  }	|}|t/        ||	      k(  rt/        ||	      | j                  |<   ||f| j                   |<   | j0                  j3                          - y )Nro   r  )r  r   rH   rx   r   r   r  r   r,   r'   r  r   r   r   r(   r@  r  r   r   r   r|   r   r   r*   r  r  )rT  r  r   r  r  r_exprr   rO  r   r   rhs_vrlower_guardupper_guards                r9   rh  zShapeEnv.refine_ranges  s   }}UZZ(''Ffell333$//--fd;\J $'Ay!2!2qt KFC""6*B88RXX5E d&7&78F%c62'+'9'9'='=fl'S$K v||#
6EHHehhPUPXPX;Y(Z s:fehh+G'HH#v||#
6EHHehhPUPXPX;Y(Zs:fehh+G'HH# [.. )4E5(ADf%*5{)CDv&''335e (r8   )r  r@   r   N)r   N)rS  rX  )T)F)r   rX  r   rX  )r   rX  )r}   sympy.Symbolr   rX  r   N)r}   ry  r   rX  )NNT)r  rX  rk   )hr4   r5   r6   r   r   r   r	   r  r  r  r  r  r|   r  r  r   r\   r   r  r!   r   r   r  r   r  r  r  r  r   r   rd   rZ   r  r  r  r  r  r  r  r!  r  r  r&  r   rO   r  r+  r)  r   rC  r?  r  r`  rb  ri  rp  rr  rt  rB  rE  r   r   r  r_  r2  rS  r  	InputListr  r   r  r  r  r  r5  r8  r  r  r  r  r  r  r  r  r   r  r   r  r*  r,  r  rF  r*   r~  rk  rL  rR  rl  r`  r  rm  rs  r    rh  r7   r8   r9   r@   r@   >  s^    04-1(
&tn(
  S	*(

 
(
X "'+
 "' ! 1K=Z;VzKc(; K$'&# &$ &$# $ & &  . .8ELL;Q .1 1T 1d 11/& == = 
x&,	-	= =>,LL, , 
%((--	 	,4(8EHHMM#: (t (
= =4 =6 # # $ $ ( (`	'b$,SMb#)b .=b !%UZZ 0	b7<Sz28 =L 04EJJ/?	, 7;D
LLD
 D

 #?3D
L  7;mG#mG C=mG 	mG
 !mG mG #?3mG mGd  (,:>$$ 3-	$
 V$$ '7$ $L 	
 	
7
 	M 	M I I+ +$ + 	X 	X 
 #-//(,|3;| |  	|
 &| 
| | 
 #-//(,#'+0gg g  	g
 &g 4.g %)g 
g gRF J &	q jnBFq $IeM8GTaLbCc4c.d$efq $Cffn(=$>?q 
cqfK MQ -^w^ ;@W\h3 h348h3PTh3 
 h3 h3T 8 8 ' ' # #J s^:?  " s^] ]
1.' $  $ s^YE*@$A YRV Y[_ Y Y~3k 3:+ : # #n"12 . s^d3HL&*@ 4 @D
# d35 45B56: 56$ 56r8   r@   c                 f    t        | t              xr  | j                  j                  j                  S rk   )rx   r   ry   r   r   r   s    r9   _is_intr|    s"    dF#@		(@(@@r8   c                 :    t        | d      xr || j                  v S )N_dynamo_dynamic_indices)r  r~  )r   rD  s     r9   r@  r@    s     1/0SQ!:S:S5SSr8   rk   r  )r   )r   r  r   rb   r  r[  mathr   rV  rX   	threadingrT  r   
contextlibr   dataclassesr   r   enumr   r   typingr	   r
   r   r   r   r   r   r   r   r   r   r   rd   torch.fxtorch.fx.tracebackrZ   r  torch.fx.experimentalr   r  torch.fx.experimental.recordingr   r   r   r   r   torch.fx.experimental.sym_noder   r   r   r   r   torch._guardsr    r!   r"   torch.utils._python_dispatchr#   torch.utils._sympy.functionsr$   r%   r&   torch.utils._sympy.solver'   torch.utils._sympy.value_rangesr(   r)   r*   r+    torch.utils._sympy.singleton_intr,   torch.utils._tracebackr-   r.   torch._utils_internalr/   torch._loggingr0   rz  r  	getLoggerr4   r   RuntimeErrorr2   r   sympy.printing.strr;   sympy.printing.precedencer<   r=   _opsopsaten__all__rK   rL   rg   ri   r>   r?   rF   r   r|   rA   r  rE   r   r   rJ   r   r   r   r   rH   rM   r   rI   r   r   r   r   r   rN   rD   r  r  r  r  r  r  r   rB   rC   r.  r1  r6  r8  r@  rB  rJ  rN  rW  r  r\  rx  rO   rP   rQ   r   r   IndicatorTypesr  r  r  r  r  absrm  negtltleger   r   modfloordivr;  r  ceilrG   r  r  r  r  r  r  r}  r  r@   r|  r@  r7   r8   r9   <module>r     sA           	 
   # % (   i i i i   ) ) 3  = , + < < F Y Y . n n 9 B 0 %	
g!	, 	  ) <zz~~ & !  4. .&	| 	,#	
uS&[) $. ..uzz 2dGm, "Yfell23 Y8M Y(IeFELL01 Ic%,,6G I=% 45 =$ =
Ix'= 4(O9 R%,, Rc RY\ Rkn R  ~A R R"&%P "hsm "# " "L CG Bx} B8C= B BJ : :x LG *. mD@EJJ @{ @ Z $   $HZ H H2 $;j ; ;2 ,.EtKL
$: : :Db
 $
	 
	 
	 $[ [ [J $H6 H H."U3xwFG "D "
 45
3 -
O>demm d d	8<<(++ 	(++ 	(++	
 	(++ 	(++ 	(++ 
3 
3 
8<< !! x ()J TZZ tyy  '(H!(1p $# # ##?
 #?LM0 M

* 
>G GV ioo{!6 {!6zCATr8   