
    Vh             	      ,   U d dl m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Zd dlZd dlZd dlZd dlmZmZ d dlmZmZmZ d dlmZmZ d dlmZmZ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) d d	l*m+Z+m,Z,m-Z- d dl.Z.d dl/Z.d dl0m1c mZ2 d dl3m4c m5Z6 d d
l.m7Z7m8Z8m9Z9 d dl:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZG d dlHmIZJ d dlKmLZLmMZMmNZNmOZOmPZP d dlQmRZRmSZS d dlTmUZU d dlVmWZW d dlXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZa d dlbmcZc d dldmeZemfZf d dlgmhZh d dlimjZj d dlkmlZlmmZmmnZn d dlompZpmqZqmrZrmsZs d dltmuZumvZv e'rd dlwZwd dl.mxZx d dlymzZz d dl{m|Z| e}Z~e}Z e	j                   e      Zd dlZd dlmZmZ  G d  d!e      Z G d" d#e      Ze.j                  j                  j                  Zg d$Zd%Zd&Zdd'Zd(Zd)ed*<    e(d+      Z e(d,ej&                  eej(                        Z G d- d.      Z	 	 	 	 dd/Z	 	 	 	 dd0Z ed      dd1       Z G d2 d3e      Zdd4Ze)e.jr                  ef   Zd)ed5<   dd6Zddd7Ze)e.jr                  e.jp                  e.jn                  eeef   Zd)ed8<   dd9Zdd:Zdd;Zdd<Z	 	 	 	 	 	 dd=Zdd>Z	 	 	 	 	 	 dd?Ze)e.j                  ee.j                  d@f   f   Zd)edA<   	 	 	 	 	 	 	 	 ddBZddCZddDZ	 	 d	 	 	 	 	 	 	 	 	 ddFZddGZddHZddIZddJZe)e9e8e7eeeej(                  e.j                  f   Zd)edK<   e)eee   f   Zd)edL<   ddMZddNZddOZddPZddQZddRZ	 	 	 	 ddSZ edET       G dU dV             Z edET       G dW dX             Z edET       G dY dZ             Z edET       G d[ d\             Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd]Z	 	 d	 	 	 	 	 	 	 	 	 dd^Zdd_Zdd`ZddaZddbZ	 	 	 	 ddcZ	 	 	 	 	 	 	 	 	 	 ddeZddfZddgZ	 d	 	 	 	 	 	 	 ddhZddi	 	 	 	 	 	 	 ddjZddkZdddlZddmZddnZddoZddpZddqZdEdr	 	 	 	 	 	 	 ddsZddtZ G du dve      Z edET       G dw dx             Z edET       G dy dze׫             Z edET       G d{ d|e׫             Ze)eedf   Z edET       G d} d~e׫             ZddZddZddZ edET       G d d             Z edET       G d de߫             Z edET       G d de             Z edET       G d de             Z	 	 	 	 ddZe^fZddZddZ ed      dd       Z G d de$      Z ed      	 	 	 	 	 	 	 	 	 	 d d       ZddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZddZ	 	 	 	 ddZeee
e.dZ	 d	 	 	 	 	 ddZ edET       G d d             Z G d def      Z G d dej                        Z G d deef      Z e+de       G d de             Z G d deee      Z edET       G d d             Z edET       G d de             Z G d de      Z G d def      Z G d d      Z ej                         Z edET       G d d             Z e G d d             Zedd       Ze G d d             Z G d dd      ZddZd	dZ G d de.jb                  j                        Zd
dZ	ddZ
 G d def      Z	 	 	 	 	 	 ddZ	 	 	 	 ddZy(      )annotationsN)Counterdefaultdict)IteratorMappingSequence)_GeneratorContextManagercontextmanager)asdict	dataclassfield)Enum)	AnyCallablecast
NamedTupleNoReturnOptionalTYPE_CHECKINGTypeVarUnion)
deprecated	TypeAlias	TypeGuard)SymBoolSymFloatSymInt)
ShapeGuardSLocSourceTracingContext)dtrace_structured
LazyString
structuredtrace_structured)is_sparse_any)signpost_event)_config)FakeTensorMetarecord_shapeenv_eventreplay_shape_env_eventsshape_env_check_state_equalShapeEnvEvent)SymNodeSymTypes)
OrderedSet)is_traceable_wrapper_subclass)	Application	CeilToIntCleanDivFloorDiv
FloorToInt!IsNonOverlappingAndDenseIndicatorMaxMod	PythonMod)int_oo)
CppPrinterPythonPrinterSingletonInt)	try_solve)make_symbolsymbol_is_typeSymT)bound_sympySymPyValueRangeAnalysisValueRangeErrorValueRanges)CapturedTracebackformat_frame)Tensor
FakeTensor)BoolLikeType)AddSc                  ,     e Zd ZU ded<   d fdZ xZS )GuardOnDataDependentSymNodesympy.Basiccondc                ,    t        |   |  || _        y N)super__init__rS   )selfrS   args	__class__s      U/home/dcms/DCMS/lib/python3.12/site-packages/torch/fx/experimental/symbolic_shapes.pyrW   z$GuardOnDataDependentSymNode.__init__p   s    $	    )rS   rR   rY   r   returnNone)__name__
__module____qualname____annotations__rW   __classcell__rZ   s   @r[   rQ   rQ   m   s    
 r\   rQ   c                      e Zd Zy)PendingUnbackedSymbolNotFoundNr_   r`   ra    r\   r[   rf   rf   u       r\   rf   )"has_symbolic_sizes_stridescreate_contiguousShapeEnvis_concrete_intis_concrete_float	guard_intguard_floatguard_scalarcanonicalize_bool_exprhint_intSYMPY_INTERPfree_symbolsis_symbol_binding_fx_nodeis_concrete_boolis_nested_intSHAPEENV_EVENT_KEYCURRENT_NODE_KEYhas_free_symbolshas_free_unbacked_symbolssym_eqSymbolicContextStatelessSymbolicContextStatefulSymbolicContextSubclassSymbolicContextstatically_known_trueguard_size_obliviouscheck_consistentcompute_unbacked_bindingsConvertIntKeyrebind_unbackedresolve_unbacked_bindingsis_accessor_nodeValueRangesSLocSymIntEqByExprshapeenv_eventcurrent_nodec                b    t         j                  d| j                  | j                                y )Nzlru_cache_stats %s: %s)logdebugr_   cumulative_cache_info)	wrapped_fs    r[   log_lru_cache_statsr      s$    II )"4"4i6U6U6Wr\   zsympy.logic.boolalg.Booleanr   SympyBoolean_T_SympyTc                  D    e Zd ZU dZded<   d
dZddZddZddZddZ	y	)r   a  
    This is a wrapper around SymInt which has alternative semantics for
    equality.  Specifically, instead of erroring or guarding, we
    instead will hash/compare equality based on the underlying sympy
    expression; e.g., s0 and s1 will always compare as False.

    NB: This does NOT do fancy analysis that maybe_evaluate_static does;
    we can only reason through equalities that occur because to expressions
    canonicalize to the same expression via regular simplification.
    Union[torch.SymInt, int]valc                    || _         y rU   r   )rX   r   s     r[   rW   zSymIntEqByExpr.__init__   s	    r\   c                ,    t        | j                        S rU   )reprr   rX   s    r[   __repr__zSymIntEqByExpr.__repr__   s    DHH~r\   c                    t        | j                  t        j                        r | j                  j                  j
                  S t        j                  | j                        S rU   )
isinstancer   torchr   nodeexprsympyIntegerr   s    r[   _extractzSymIntEqByExpr._extract   s;    dhh-88==%%%==**r\   c                   t        |t              sJ t        | j                        t        u r4t        |j                        t        u r| j                  |j                  k(  S | j                         |j                         k(  S rU   )r   r   typer   intr   )rX   others     r[   __eq__zSymIntEqByExpr.__eq__   s^    %000 >S T%))_%;88uyy((}}%.."222r\   c                4    t        | j                               S rU   )hashr   r   s    r[   __hash__zSymIntEqByExpr.__hash__   s    DMMO$$r\   N)r   r   r]   r^   r]   str)r]   
sympy.Expr)r   objectr]   boolr]   r   )
r_   r`   ra   __doc__rb   rW   r   r   r   r   rh   r\   r[   r   r      s(    	 
"!+3%r\   r   c                p    t        | d         r#d| d   j                  j                         | d   fS dg| S Nr      )rx   r   nested_int_coeff)tups    r[   _nested_int_aware_sortr      sF     Q  
CFKK((*CF3
 Y#Yr\   c                     d fd}|S )Nc                    t        j                        |       j                  dddfd}dfd}|_        |_        t        j                  t        j                        rt        j                  t               S )Nr   c                     j                         } t        j                  | j                  z   | j                  z   | j
                  | j                        S rU   )
cache_info	functools
_CacheInfohitsmissesmaxsizecurrsize)cur	prev_hitsprev_missesr   s    r[   r   z7lru_cache.<locals>.inner.<locals>.cumulative_cache_info  sJ    &&(C''CHH$cjj(	 r\   c                 p    j                         } | j                  z  | j                  z           y rU   )r   r   r   )r   old_cache_clearr   r   r   s    r[   new_cache_clearz1lru_cache.<locals>.inner.<locals>.new_cache_clear
  s3    &&(C!I3::%Kr\   )r]   zfunctools._CacheInfor]   r^   )r   	lru_cachecache_clearr   r   isEnabledForloggingDEBUGatexitregisterr   )fr   r   r   r   r   r   r   s      @@@@r[   innerzlru_cache.<locals>.inner   sw    0I''03	#//			 	 !0	*?	'GMM*OO/;r\   )r   Callable[..., _T]r]    functools._lru_cache_wrapper[_T]rh   )r   r   s   ` r[   r   r      s    @ Lr\   c                 *   dd l } dd l} dd l} dd l} dd l} dd l} dd l} dd l} t        j                  t           | j                  j                  j                  | j                  j                  j                  | j                  j                  | | j                   | j"                  j$                  | j&                  j(                  | j*                  j,                  | j*                  j.                  | j0                  j2                  | j0                  j4                  | j6                  j8                  | j6                  j:                  g}dd l} |D ch c]  }t?        j@                  |       c}| j"                  jB                  jE                         z  dhz  S c c}w )Nr   <string>)#torch._compiletorch._dynamo.eval_frametorch._inductor.sizevarstorch._library.custom_opstorch._library.fake_impltorch._loggingtorch._subclasses.fake_tensortorch._subclasses.meta_utilssysmodulesr_   fxexperimental	recordingsym_nodeinterpreter_compile_dynamo
eval_frame	_inductorsizevars_library
custom_ops	fake_impl_subclasses
meta_utilsfake_tensor_logging	_internalr$   torch._dynamo.guardsinspectgetfileguardsuninteresting_files)r   modsms      r[   r   r     s#   ##$#(' 	H''&&    !!  $$%%  !!D    &**	*
--


2
2
4	5,	*s   Fc                      e Zd Zy)ConstraintViolationErrorNrg   rh   r\   r[   r   r   @  ri   r\   r   c                    | j                   S rU   )_has_symbolic_sizes_strides)elems    r[   rj   rj   D  s    +++r\   Intc                    dg}t        | d d       D ]  }|j                  ||d   z          t        t        |            S )Nr   )reversedappendlist)shapestridesdims      r[   rk   rk   K  sH    Gcr
# *sWR[()*!""r\   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).
    )r   r   r   r   require_hintr   r   )afallbacks     r[   rs   rs   R  sA     !U\\"vv""8,,7c>1>Hr\   Scalarc                X    t        | t              r| j                  j                         S y)NT)r   r/   r   has_hintr  s    r[   r  r  a  s     !Xvv  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)	r   r   r   r   r   r   corenumbersr   r  s    r[   rm   rm   g  sM     a&#'''!S!&&++uzz1199:r\   c                    t        | t        t        f      sJ t        | t              ryt        | j                  j                  t
        j                  j                  j                        ryy)zUtility to check if underlying object
    in SymInt is concrete value. Also returns
    true if integer is passed in.

    Args:
        a (SymInt or float): Object to test if it float
    TF)	r   r   floatr   r   r   r  r  Floatr  s    r[   rn   rn   {  sN     a(E*+++!U!&&++uzz11778r\   c                    t        | t        j                        r| j                  j	                  dd      S t        | t
              sJ |        | S )a  
    Perform a guard on a symbolic boolean expression in a size oblivious way.
    This is typically used when a non-oblivious test would result in a guard
    on a data dependent value of which we don't know the value of at compile time.
    When a guard is tested this way, we may diverge in behavior from how regular
    PyTorch semantics would treat it.  For more information, see
    https://github.com/pytorch/pytorch/pull/118579
     r   )r   r   r   r   r   r   r   s    r[   r   r     sC     $&yy--b!44$%+t+%r\   c                l    t        |       t        |      k(  xr t        d t        | |      D              S )z
    Leverage guard_size_oblivious to compare if two lists of int/symint are equal.
    Useful to compare sizes, strides etc.
    c              3  >   K   | ]  \  }}t        ||k(          y wrU   )r   ).0lhs_itemrhs_items      r[   	<genexpr>z)_guard_sizes_oblivious.<locals>.<genexpr>  s&      4Hh 	X124s   )lenallzip)	lhs_sizes	rhs_sizess     r[   _guard_sizes_obliviousr(    s9     y>S^+  4"%i";4 1 r\   c                    t         j                  t         j                  t        t        f}t         t         j                        rt        t         j                        sJ t        j                  j                          j                         k(   fd       t        j                   j                        D ]"  \  }}t        j                  ||k(   fd       $ yt         |      rWt         t              sFt        |      rt        t              rJ  d         t        j                   k(   fd       yyy)z
    Test that two "meta" values (typically either Tensor or SymInt) have
    the same values, e.g., after retracing.  If we don't understand the
    quantities in question, we'll just skip the consistency check.
    c                 <    j                    d j                    dS N != z (old != new)r	  newolds   r[   <lambda>z"check_consistent.<locals>.<lambda>  s    syykcii[,V r\   c                 <    j                    d j                    dS r+  r-  r.  s   r[   r1  z"check_consistent.<locals>.<lambda>  s    CII;d399+])S r\   r,  c                      d  dS r+  rh   r.  s   r[   r1  z"check_consistent.<locals>.<lambda>  s    C5SE)G r\   N)r   r   r   r   r  r   rJ   _checkr  r%  r	  r   )r/  r0  scalar_typesijs   ``   r[   r   r     s     LL%..#u=L#u||$#u||,,,GGI"$V	
 		399- 	UDAqLLa!ST	U 
C	&z#t/D#|,Z6
 	U$se	 
 	SCZ!GH	 0E	&r\   c                    |y | J |j                         D ci c]"  \  }}| j                  j                  ||      |$ c}}S c c}}w rU   )itemsunbacked_renamingsget)	shape_envbindingskvs       r[   r   r     sP        BJ..BRS$!QI((,,Q2A5SSSs   'A.Resultc                   |j                   dk(  ryt        | |j                  j                  d            x}rT| J |j	                         D ];  \  }}t        j                  ||      }t        |t              r$t        j                  d|j                  |||       Q|j                  j                  h|j                  j                  }t        |t        j                         rPt#        |j$                        dk(  r7t'        t(        t        j*                  t        j*                  f   |j$                  d         x}r|d   dk(  rt        |d   x}	t        j,                        rt        |	j.                  x}
t        j0                        r| j2                  |
   j5                  t7        dd            r|	j8                  dk(  rst'        t(        t        j*                  t        j*                  f   |j$                  d         dk(  r2t;        t        j,                  |
d            }||k(  sJ | d	|        |
}t        |t        j0                        s|j<                  r
J d
|        ||k7  s
J | d       | j?                  ||       > yy)a  
    Suppose we are retracing a pre-existing FX graph that previously had
    fake tensor propagation (and therefore unbacked SymInts).  When we retrace,
    we re-propagate fake tensors, which results in new unbacked SymInts.
    When this happens, we need to tell the shape environment about the equivalence
    of the old and new unbacked SymInts.  Pass us the old torch.fx.Node (which
    has the old binding information) and the new result (which we can extract the
    new unbacked SymInts out from).
    placeholderNunbacked_bindingsz'rebind_unbacked: discard %s %s %s -> %s   r   r   r   Tr,  z#should have been constant, but got z possible memo disaster) opr   metar;  r9  pytreekey_getr   r   r   infotargetr   hintr   r   	Piecewiser#  rY   r   tupleBasicEqlhsSymbolvar_to_rangeissubsetrG   rhs'_sympy_cast_symbool_to_symint_guardlessru   _rename_unbacked_to)r<  nresultr=  raw_u0pathu1raw_u1raw_u1_args0eq
new_raw_u1repackeds               r[   r   r     sQ    	tt},166::12 x  $$$$NN, ]	:LFD-BT "c"=HH  ww||'WW\\F 65??3$)$(ekk5;;67Q% L  !Oq(\!_4rehh?RVV3zU\\B**:6??Aq@QRFFaKu{{EKK78&++a.IYV CHHZ+  6)DhZtF8+DD) $fell3++B8AB+ V#Gx/F%GG#))&&9{]	:	r\   c           
     N   | j                   dk(  rt        | j                  d   t        j                  j
                        rOt        | j                  d   j                  j                  d      t        j                        r| j                  dv ry| j                   dk(  r| j                  t        j                  j                  j                  t        j                  j                  j                  j                  t        j                  j                  j                  j                  t        j                  j                  j                  t        j                  j                  j                  j                  t        j                  j                  j                  j                  t        j                  j                  j                   t        j                  j                  j                   j                  t        j                  j                  j"                  j                  f	v ryy)Ncall_methodr   example_value)sizestridestorage_offsetitemTcall_functionF)rF  r   rY   r   r   NoderG  r;  rJ   rK  opsatensym_sizedefaultr   
sym_stridesym_storage_offset	sym_numelr   s    r[   r   r   P  sB    	= tyy|UXX]]3tyy|((,,_=u||LKKGGww/!dkk				''		##		!!		!!))		!!%%		))		))11		  ((
6 
' 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
    )r   r   RelAndOrNotrP  Nelogicboolalgto_cnf_canonicalize_bool_expr_implr  s    r[   rr   rr   h  s    " uyy%))UXXuyy%((EHHM $EHHeii89{{""))$/'--r\   Tc                   |s| j                   S |r| t        j                  u r%t        j                  j                  j
                  }nE| t        j                  u r%t        j                  j                  j                  }nt        d|        |du sJ |d   j                  r'|dd  } ||       | j                  |d   g|z   |      S |j                         } ||       | j                  ||      S | j                  ||      S )NzUnknown cls: Tr   r   is_commutative)identityr   rN   r  add_addsortMulmul_mulsort
ValueError	is_Number
_from_argscopy)clsrY   sortr  sort_fnrests         r[   _sympy_from_argsr    s     || %))jjnn--GEIIjjnn--G}SE233 %%%78DDM>>47)d"2>>RR99;DDM>>$~>FF ~~d>~BBr\   c                F   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d}t$        j&                  }t)        |      }t        |t        j*                        r|g }g }|j                  D ].  } ||      r|j-                  |        |j-                  |       0 t/        t        j*                  |dd      }t/        t        j*                  |dd      }n ||      r| t$        j&                  }} |||d      S )z
    After canonicalization, we are guaranteed to have eliminated Ge/Gt relations
    (rewriting them to Le/Lt, respectively).
    c                    | j                   xr | j                  xsP t        | t        j                        xr4 | j
                  d   j                   xr | j
                  d   j                  S Nr   )r  is_negativer   r   r  rY   ts    r[   is_negz,_canonicalize_bool_expr_impl.<locals>.is_neg  sP    - 
q%))$V)<)<VAVAV	
r\   FTr  r  evaluate)r  r   r]   r   )r   r   ru  rv  r   maprr   rY   GtLtGeLerN  keysrQ  rU  rP  rx  rO   Zero_reduce_to_lowest_termsrN   r  r  )	r   oppositerU  r  r  rQ  posnegterms	            r[   r|  r|    s   
 $EHH-.tDz35tyyABB%((EHHehh7H$hmmo./hh!T$Z $588UXXuxx HIIIhh!J

 &&C
!#
&C#uyy!HH 	!Dd|

D5!

4 		! uyy#E$Ouyy#DN	4S S#&&r\   c                   dd}dd}| j                   rt        t        t        j                     | j
                        }t        j                  t        j                  t        ||            }|dk(  r| S |D cg c]  } |||       }}t        t        j                  |d| j                        S | j                  rt        j                   S | j"                  r ||  ||             S | S c c}w )z
    Eliminates any integer factor from a given expression.
    E.g., 6x + 4y reduces to 3x + 2y.

    Useful when an expression is == or != to 0.
    c                    | j                   rt        t        |             S | j                  r<| j                  d   j                   r!t        t        | j                  d               S dS yr   )
is_Integerabsr   is_MulrY   xs    r[   integer_coefficientz4_reduce_to_lowest_terms.<locals>.integer_coefficient  sO    <<s1v;XX +,&&)*>*>3s166!9~&EAEr\   c                d   | j                   r| |z  S | j                  r| j                  d   |k7  r6| j                  d   t        j                  |      z  g| j                  dd  }nt        | j                  dd        }t        t        j                  || j                        S t        d|        )Nr   r   r~  zillegal arg to div_by_factor: )
r  r  rY   r   r   r  r  r  r  AssertionError)r  factorrY   s      r[   div_by_factorz._reduce_to_lowest_terms.<locals>.div_by_factor  s    <<v:XXvvayF"q	EMM&$99GAFF12JG AFF12J'#EIItADTDTUU #A!!EFFr\   r   Tr  )r  r   r]   r   )r  r   r  r   r]   r   )is_Addr   r   r   ExprrY   r   reducemathgcdr  r  rN   r  r  rO   Oner  )r   r  r  atomsr  r  s         r[   r  r    s    G {{Xejj)4995!!$((C0CU,KLQ;K389aq&)99IIu48K8K
 	
 
uu	T#6t#<==K :s   9C+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)
r   r   r   r   r   r   ry  rz  BooleanTrueBooleanFalser  s    r[   rw   rw     sg     a'4)))!T	ekk))55u{{7J7J7W7WX r\   c                n    t        | t        j                        xr | j                  j	                         S rU   )r   r   r   r   rx   ss    r[   rx   rx     s%    a&A166+?+?+AAr\   IterateExprsAtomIterateExprsc              #  &  K   t        | t              r%t        |       r| j                  j                   y y t        | t
        j                        r|  y t        | t        t        t        f      ry t        | t        t        f      r| D ]  }t        |      E d {     y t        |       r"t        | j                               E d {    y t        | t        j                         rdt        | j                               E d {    t        | j#                               E d {    t        | j%                               E d {    y | y t        | t        j&                        ry t)        d|  dt+        |              7 7 7 7 d7 Ew)Nz&cannot extract sympy expressions from  )r   r/   is_symbolicr   r   r   rO  r   r  r   rN  r  _iterate_exprsr&   re  r   rJ   rf  rg  	Generatorr  r   )r   r  s     r[   r  r  !  s4    #x  s((-- 	C	%		C#ud+	,	C%	' 	)A%a(((	)	s	!#((*---	C	&!#((*---!#**,///!#"4"4"6777		C	)EcU!DQTI;WXX )--/7sZ   BFF.FF	;FF F(F) F	F
>F	FFFFc                    | 
t               S t        |       }	 t        |      } |j                  j
                  d |D         S # t        $ r t               cY S w xY w)Nc              3  4   K   | ]  }|j                     y wrU   )ru   r  es     r[   r"  zfree_symbols.<locals>.<genexpr>I  s     *Ga1>>*G   )r0   r  nextStopIterationru   union)r   itr
first_exprs      r[   ru   ru   =  sa    
{|

C#Y
 ):""((*G3*GHH  |s   A AAc                :    t        d t        |       D               S )z)Faster version of bool(free_symbols(val))c              3  4   K   | ]  }|j                     y wrU   )	is_numberr  s     r[   r"  z#has_free_symbols.<locals>.<genexpr>N  s     <11;;<r  )r$  r  r   s    r[   r{   r{   L  s    <s(;<<<<r\   c                    ddl m} t        |       D ]I  } ||      D ]<  }|j                  st	        |t
        j                  t
        j                  f      s;  y K y)z2Faster version of bool(free_unbacked_symbols(val))r   )iterargsTF)sympy.core.traversalr  r  	is_SymbolrB   rC   UNBACKED_INTUNBACKED_FLOAT)r  r  r  args       r[   r|   r|   Q  sZ    -A A; 	C}}d'')<)<=" 		 r\   c                8    t        d t        |       D              S )Nc              3  t   K   | ]0  }t        |t        j                  t        j                  f      r| 2 y wrU   )rB   rC   r  r  r  r  s     r[   r"  z(free_unbacked_symbols.<locals>.<genexpr>a  s3      !d//1D1DEF 	
s   68)r0   ru   r  s    r[   free_unbacked_symbolsr  _  s      a  r\   c                   d| j                   v rt        | j                   d   t        j                        rt        | j                   d   j                  j
                  t        j                        r^| j                  dk(  s,t        | j                   d   j                  j
                        r#| j                   d   j                  j
                  S y )Nr   rB  )
rG  r   r   r   r   r   r   rR  rF  r  rr  s    r[   rv   rv   j  s    tyy'6tyy',,115<<@GG}$$TYYu%5%:%:%?%?@ yy$$)))r\   c                \    i }| j                   D ]  }t        |      x}||vs|||<    |S rU   )nodesrv   )graphrr   r  s       r[   find_symbol_binding_fx_nodesr  x  sB     	A *400A=!1*AaD Hr\   frozenc                      e Zd ZddZddZy)r   c                     y)Nz#.cast_symbool_to_symint_guardless()rh   r   s    r[   __str__zConvertIntKey.__str__  s    4r\   c                    t        |      S )zGet the int value from bool) cast_symbool_to_symint_guardless)rX   bs     r[   r;  zConvertIntKey.get  s    /22r\   Nr   )r  r   r]   Union[int, SymInt])r_   r`   ra   r  r;  rh   r\   r[   r   r     s    53r\   r   c                  (    e Zd ZU ded<   ddZddZy)CallMethodKeyr   namec                "    d| j                    dS )N.z()r  r   s    r[   r  zCallMethodKey.__str__  s    499+R  r\   c                8     t        || j                               S )zCall the method on object)getattrr  rX   os     r[   r;  zCallMethodKey.get  s    $wq$))$&&r\   Nr   r  r   r]   r   r_   r`   ra   rb   r  r;  rh   r\   r[   r  r    s    
I!'r\   r  c                  (    e Zd ZU ded<   ddZddZy)InnerTensorKeyr   
inner_namec                     d| j                    S Nr  )r  r   s    r[   r  zInnerTensorKey.__str__  s    4??#$$r\   c                .    t        || j                        S )zGet the inner tensor attribute)r  r  r  s     r[   r;  zInnerTensorKey.get  s    q$//**r\   Nr   r  r  rh   r\   r[   r  r    s    O%+r\   r  c                  (    e Zd ZU ded<   ddZddZy)DivideByKeyr  divisorc                "    d| j                    dS )Nz.__floordiv__()r   r   s    r[   r  zDivideByKey.__str__  s    ~Q//r\   c                     || j                   z  S )zDivide object by divisorr  r  s     r[   r;  zDivideByKey.get  s    DLL  r\   Nr   )r  r   r]   r   r  rh   r\   r[   r  r    s    0!r\   r  c           
     h   t        j                  t        |      }dfd}|
t               }i }t	        | t
        t        f      rVt        t        |             D ]=  }	|j                   || |	   |t        j                  |	      fz   |||	   nd              ? |S t        |       rM| j                         \  }
}|
D ]3  }t        | |      }|j                   |||t        |      fz                5 |S t	        | t         j"                        rqddlm} t	        | |      sJ |j                   || j)                         |t+        d      fz   | j,                  | j,                  j)                         nd              | j.                  t         j0                  t         j2                  t         j4                  t         j6                  fvr[|j                   || j9                         |t+        d      fz   | j,                  | j,                  j9                         nd              |j                   || j;                         |t+        d      fz   | j,                  | j,                  j;                         nd              |S t	        | t         j<                  t         j>                  f      rlt	         ||       x}t@        jB                        rJ||v rF|||<   r,|*t	        |tD        tF        f      sJ jI                  ||       |jK                  |       |S t	        | t         j<                        rt	         ||       x}t@        jL                        rut        |jN                        d	k(  r\t	        |jN                  d   x}t@        jP                  t@        jB                  f      r"t	        |jN                  d
   x}t@        jB                        r||v ||v z  rt	        ||vr|n|x}t@        jP                        sr|jR                  v rdfd}||v r|n|}r%t	        |t@        jP                        rtE        |      n ||      }|tU        |      fz   ||<   |Zt	        |tD              sJ t	        |t@        jP                        r|tE        |      z  ntW        ||      }rjI                  ||       |jK                  |       |S t	        | t         jX                        rt	         ||       x}t@        jZ                        rt	        |j\                  t@        jB                        r|j^                  d
k(  rv|j\                  |v rh|ta               fz   ||j\                  <   |0tc        |      td        u sJ rjI                  |tE        |             |jK                  |j\                         |S )Nr<  pendingsimplifyc                `    r| j                   j                  S | j                   j                  S rU   )r   r   _expr)r  r  s    r[   r   z._free_unbacked_symbols_with_path.<locals>.expr  s$    66;; vv||r\   )realr   rK   re  rf  rg  rD  r   c                    j                  | t        j                  |          j                  j	                  | d g      d         S )Nr   rL  source)create_symintnoder   
var_to_valvar_to_sourcesr;  )r  r<  s    r[   _symint_wrapz6_free_unbacked_symbols_with_path.<locals>._symint_wrap   sN    ..--a01 //33Av>qA /  r\   )r   Union[SymInt, SymFloat, SymBool]r]   r   )r  sympy.Symbolr]   r   )3r   partial _free_unbacked_symbols_with_pathsetr   rN  r  ranger#  updaterH  SequenceKeyr1   __tensor_flatten__r  r  r   rJ   r   rL   re  r  real_tensorlayout
sparse_csr
sparse_csc
sparse_bsr
sparse_bscrf  rg  r   r   r   rR  r   r  set_unbacked_var_to_valremover  rY   r   r  r  r4   r   rP  rQ  rU  r   r   r   )r  r[  r  r<  r  r  gor   r  r6  attrs_attrsubrL   r  rQ  rU  coeffr  unbackedr   r   s      ` `                 r[   r  r    s    
		(	
B %
A!eT]# s1v 	AHHaDF..q133$($4a$	x Hi 
'q	)'')q 	>D!T"CHHRT^D%9$;;<=	>b H] 
Au||	$<!Z(((	f-//-.]]-FQ]]'')D	
 88	
 
 HHHHJM(35534==3L--/RV 	
  "&6799 }}0 MM002
	
l HS 	1u||U^^45DG|qU\\2L!)dS%L111--a6qB Hu 	1ell#DG|qUYY/K1affQi's%--)FGaffQi's6Wn0 s''9sBuEMMR---	 .3c Zu}}= Je$ 	 k'244(dC((( eU]]3 E
"dE* 
 11(C@x & H 	1emm$DG|qUXX.quuell+EEQJEEW=?,,!%%:%%%11!SY?quuHr\   c           	        | y| j                   }t        |      }|sy|s&t        j                  d|       |j	                          t        |d| |d      }|s\|rZt        |t        j                        r)t        |j                         |j                         f      nd}t        d| d| d	| d
      |&|j                         D ]  }t        j                  ||      }	t        j                  ||      }
t        |
t               sAt        |
j"                  j$                  x}t&        j(                        srt        |	t               r[|	j"                  j$                  x}|k7  r@t        |t&        j(                        r| j+                  ||       | j-                  ||       t        |	t               r| j-                  |t'        j.                  |	              |S )a  
    After having run fake tensor propagation and producing example_value
    result, traverse example_value looking for freshly bound unbacked
    symbols and record their paths for later.  It is an error if
    we have allocated an unbacked SymInt but it cannot be found in
    example_value.  (NB: this means if you have a multi-output
    function, you must call this on the tuple of tensor output, you
    cannot wait!)

    The peek parameter lets you check out what the bindings are without
    changing the affected list.  This is primarily useful for ensuring
    unbacked_var_to_val is promptly populated when propagate_real_tensors is on.
    Nzcompute_unbacked_bindings %srh   Fr  r  zPending unbacked symbols z not in returned outputs r  z.
Did you accidentally call new_dynamic_size() or item() more times than you needed to in your fake implementation?
For more help, see https://docs.google.com/document/d/1RWrH-3wLEpzR9kCS6gGBNen_-Fs-8PVbWWFE5AcgeWE/edit)pending_fresh_unbacked_symbolsr  r   rJ  clearr  r   r   rJ   r   rf  rg  rf   valuesrH  rI  r/   r   r   r   rR  rW  _eliminate_unbackedsympify)r<  rd  old_example_valuepeekfsr  symbol_to_pathextrakeypathold_symnew_symnew_sold_ss                r[   r   r   N  s   & 		1	1B"gG/4

5rY%N G -6 -&&(-*F*F*HIJ 	
 ,'y0I-XYZ_Y` av v
 	
( $%,,. 	QGnn%6@Gnn]G<G'8, ***ELL2 w1"),,"3"33=!%6!55eUC!55eUC#GX611%w9OP	Q" r\   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 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. 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r   r   r   r  
guard_boolr   r  s    r[   definitely_truer>    s2    $ !W66??a= 7Nr\   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    r[   definitely_falser@    s8     !W66??!!}$$Aw;r\   c                .   t        | t              rM| j                  j                  }| j                  j                  }	 |j                  |      }|t        |      S 	 yt        | t              sJ | S # t        $ r t        j                  d|       Y yw xY w)aE  
    Returns True if x can be simplified to a constant and is true.

    .. note::
        This function doesn't introduce new guards, so the expression may end
        up evaluating to true at runtime even if this function returns False.

    Args:
        x (bool, SymBool): The expression to try statically evaluating
    zCould not simplify %sF)
r   r   r   r   r<  _maybe_evaluate_staticr   	Exceptionr   r   )r  r   r<  
simplifieds       r[   r   r     s     !Wvv{{FF$$		5"99$?J%J'' & aH	  	5II-t4	5s   A2 2BB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  )r   rN  r  r#  r   r  operatorand_r  r}   r   r   r   r  r   )r  ys     r[   r}   r}     s    
 	1eAu!51d
1d 3q6SVs61a/@$GG	AU\\*	+
1sELL>Q0RAv9$q'!DG9MNNr\   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 )r   r   r   r=  r   r   ro   r   r  rp   r  r  s    r[   rq   rq     s`     !gt_%!}	A}	%|	A%(	)1~3A3788r\   rl   c                *    | j                  |||       y rU   )constrain_symbol_range)r<  r  compiler_mincompiler_maxs       r[   _constrain_symbol_rangerN     s     $$QlCr\   c                D   t        | t              rt        | j                  t              rut        | j                  j                  t
        j                        rF| j                  j                  j                  | j                  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.
    N)
r   r   r   r.   r   r   rR  r<  is_unbacked_symint_constrain_range_for_sizer  s    r[   _advise_is_sizerR    so    D 	1fqvvw'qvv{{ELL1FF//<!!$ = 2 ( 	r\   c                   t        | t              rt        | j                  t              rt        | j                  j                  t
        j                        r| j                  j                  j                  | j                  j                        rLt        |t              r;| j                  j                  j                  | j                  j                  |       y y y y y y rU   )r   r   r   r.   r   r   rR  r<  rP  r   _constrain_is_bounded)r  upper_bounds     r[   _advise_is_boundedrV  0  s    1fqvvw'qvv{{ELL1FF//<{C(	..qvv{{KH ) = 2 ( 	r\   c                Z   t        | t        t        f      rt        d      t        | t              sJ d       t        | j
                  j                  t        j                        s
J d|         | j
                  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 SymIntzconstraining non-Symbols NYI: N)r   r   r   r  r   r   r   r   rR  r<  rQ  r  minmaxs      r[   rQ  rQ  ;  s     !h()?@@a G"GG affkk5<<0V4RSTRU2VV0FF..qvv{{CEr\   )rZ  c          	     "   |t          }|t         }||k  rt        d      t        | t              r#|| cxk  r|k  sn t        d|  d| d| d      y| j                  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.
    NoMaximum value to constrain_as_size can't be less than the specified min value, received min={min} and max={max}Invalid value  for range [:])r;   r  r   r   r   r<  _constrain_ranger   rX  s      r[   constrain_rangerb  L  s    6 {g
{
Sy/
 	

 !SqC~aSSE3%qIJJFF%%affkk3<r\   c                    t        | t              s/t        |t              s| |k(  sJ y|j                  j                  }n| 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!)
    N)r   r   r   r<  _constrain_unify)r  r  r<  s      r[   constrain_unifyre  z  sT     a !V$6M6((IFF$$	q!$r\   c                P   t        | t              r}t        j                         }t	        |dz         D ]  }| n|j
                  } | j                  j                  |r|j                  j                  nd|r|j                        S d      S t        |       t        u sJ |        | S )Nr   r  r   )r   r   r   currentframer  f_backr   expect_truef_codeco_filenamef_linenor   r   )r  skipframer&  s       r[   ri  ri    s    !W$$&tax 	!A}LLE	! vv!!(-ELL$$2u~~
 	
TU
 	
 7d?A?Hr\   c                    t        | t              r| j                  j                  dd      S t	        |       t
        u sJ |        | S Nr  r   )r   r   r   r=  r   r   r  s    r[   r=  r=    s=    !Wvv  Q''7d?A?Hr\   c                    t        | t              r| j                  j                  dd      S t	        |       t
        u sJ |        | S rp  )r   r   r   ro   r   r   r  s    r[   ro   ro     s=    !VvvA&&7c>1>Hr\   c                    t        | t              r| j                  j                  dd      S t        | t              sJ |        | S rp  )r   r   r   rp   r  r  s    r[   rp   rp     s=    !Xvv!!"a((a""Hr\   c                    | j                   j                  D cg c]!  }|j                  dk(  s|j                  d   # c}S c c}w )NrB  r   )r  r  rF  rG  gmrX  s     r[   fx_placeholder_valsrv    s1    #%88>>KaQTT]5JAFF5MKKKs
   AAc                    | j                   j                  D cg c]  }|j                  dk(  s|j                    c}S c c}w )NrB  )r  r  rF  rK  rt  s     r[   fx_placeholder_targetsrx    s-     hhnnF0EAHHFFFs   ??ignore_staticc               P    | j                   j                  t        |       ||      S )Nry  )r<  evaluate_guards_for_argsrv  )ru  rz  rY   s      r[   eval_guardsr}    s,     <<00B] 1  r\   c                L    | j                   j                  t        |       |      S rU   )r<  bind_symbolsrv  )ru  rY   s     r[   r  r    s    <<$$%8%<dCCr\   c                  (    e Zd ZdZdZdZdZdZdZdZ	y)	
DimDynamicai  
    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 specify it in
          dynamic_shapes passed to export.
    r   r   rD           N)
r_   r`   ra   r   DYNAMICDUCKSTATICSIZE_LIKE_UNBACKEDINFER_STRIDEOBLIVIOUS_SIZErh   r\   r[   r  r    s*    * G DFLNr\   r  c                      e Zd ZU ded<   y)
Constraintr   	warn_onlyNr_   r`   ra   rb   rh   r\   r[   r  r    s    Or\   r  c                  $    e Zd ZU dZded<   d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.
    rG   vrc                    | j                   j                   d|j                          d| j                   j                   S )zFormat the constrain equation <= )r  lowerr  upperrX   r  s     r[   renderzStrictMinMaxConstraint.render9  s1     ''--V[[]O4GGr\   Nr  r    r]   r   )r_   r`   ra   r   rb   r  rh   r\   r[   r  r  "  s    & 	OHr\   r  c                      e Zd ZdZd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.
    c                *    d|j                          dS )NzRelaxedUnspecConstraint(r  r  r  s     r[   r  zRelaxedUnspecConstraint.renderT  s    )&++-::r\   Nr  )r_   r`   ra   r   r  rh   r\   r[   r  r  ?  s    &;r\   r  c                      e Zd ZU dZded<   ded<   ded<   ded	<    ed
      Zded<    ed
      Zded<   ddZddZ	ddZ
ddZddZ	 	 	 	 	 	 	 	 ddZy)EqualityConstrainta  
    Represent and decide various kinds of equality constraints between input sources.

    A "source pair" is a pair of input sources for dynamic dimensions that
    are specified equal. We represent `source_pairs` in a union-find forest
    so that we can efficiently check whether two such sources are transitively equal.

    A "derived equality" relates an input source to an expression over a root.
    The root can be another input source, corresponding to some dynamic dimension,
    or a phantom symbol that does not directly represent any dynamic dimension. We
    represent `derived_equalities` involving input sources in a transitively-closed map
    so that we can efficiently check whether an input source is transitively equal to
    a given expression over another input source.
    (NOTE: In contrast, it is easy to decide whether an input source is transitively equal
    to a given expression over a phantom symbol; such expressions are already in canonical
    form and so the problem reduces to symbolic expression equality.)
    zlist[tuple[Source, Source]]source_pairszTlist[tuple[Source, Union[Source, sympy.Symbol], Callable[[sympy.Expr], sympy.Expr]]]derived_equalitieszlist[sympy.Symbol]phantom_symbolszset[Source]relaxed_sourcesF)initzdict[Source, Source]_parentszdict[Source, sympy.Expr]_defsc                   i }t         j                  | d|       i }t         j                  | d|       | j                  D ]5  \  }}| j                  | j	                  |      | j	                  |             7 | j
                  D ]x  \  }}}t        |t        j                        r% ||      | j                  | j	                  |      <   F || j                  |            | j                  | j	                  |      <   z y)a  
        Pre-processing to answer queries `is_equal` and `is_derived` below.

        Example: Suppose we are given:
          source_pairs [a = b, b = c]
          derived_equalities [d = c + 1, e = d - 1]
        We first construct a union find with source_pairs:
          _parents = {a: a, b: a, c: a}
        Then we compute canonical symbolic expressions, recursively applying derived_equalities
        until we bottom out:
          _defs = {d: c + 1, e: (c + 1) - 1 aka c}
        r  r  N)r   __setattr__r  _union_findr  r   r   rR  r  _rewrite)rX   r  r  source1source2r  rootfns           r[   __post_init__z EqualityConstraint.__post_init__|  s      *,4X6 +-4%0 $ 1 1 	BGWKK

7+TZZ-@A	B !% 7 7 	IFD" $-13D

4::f-.13DMM$4G1H

4::f-.	Ir\   c                ^    || j                   v r| j                  | j                   |         S |S rU   )r  r  r  s     r[   r  zEqualityConstraint._find  s+    T]]"::dmmF344Mr\   c                .    ||k7  r|| j                   |<   y y rU   )r  )rX   root1root2s      r[   r  zEqualityConstraint._union  s    E>#(DMM%  r\   c                    | j                  |      }|| j                  v r| j                  |   S t        j                  |j	                               S rU   )r  r  r   rR  r  )rX   srcs     r[   r  zEqualityConstraint._rewrite  sB    jjo$** ::c?" <<
++r\   c                    | j                  |      x}| j                  v xs< | j                  |      x}| j                  v xs ||k(  xs | j                  ||d       S )Nc                    | S rU   rh   r  s    r[   r1  z-EqualityConstraint.is_equal.<locals>.<lambda>  s    1 r\   )r  r  
is_derived)rX   r  r  src1src2s        r[   is_equalzEqualityConstraint.is_equal  si     ZZ((TT-A-AA >

7++0D0DD>t|> w=	
r\   c                T    | j                  |       || j                  |            k(  S rU   )r  )rX   r  
symbol_srcr  s       r[   r  zEqualityConstraint.is_derived  s&     }}S!Rj(A%BBBr\   Nr   )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  z"Callable[[sympy.Expr], sympy.Expr]r]   r   )r_   r`   ra   r   rb   r   r  r  r  r  r  r  r  r  rh   r\   r[   r  r  ^  s    $ .-  ('  %*%6H"6&+&7E#7!IF)

,	
CC'-C3UC	Cr\   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 ABCT)r   r~   r   symbolic_contexts    r[   _assert_symbol_contextr    sD    / )()  	o5/./5r\   c                z   t        | t        j                  t        j                  f      rxt	        | j
                        dkD  ry| j
                  \  }}t        |      xr t        |t        j                        xs' t        |t        j                        xr t        |      S t        | t        j                        S )NrD  F)	r   r   rN   r  r#  rY   _is_supported_equivalencer   rR  )r   rQ  rU  s      r[   r  r    s     $EII./tyy>A99S)#.Q:c5==3Q 
sEMM*M/H/M	
 dELL))r\   c                0   | j                  t        j                  j                  j                  j
                  t        j                  j                  j                  j                  t        j                  j                  j                  j                        S )zL
    Add functions that our sympy interpreter can't reify into FX nodes
    )hasr   utils_sympy	functionsToFloat
TruncToIntr3   r  s    r[   #_has_uninterpretable_sympy_functionr    s`     88$$,,$$//$$.. r\   c                      e Zd ZdZy)r~   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)r_   r`   ra   r   rh   r\   r[   r~   r~     s    r\   r~   c                  \    e Zd ZU dZded<   dZded<   dZded<   dZded<   dZd	ed
<   ddZ	y)r   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
    zDimList[DimDynamic]dynamic_sizesNdynamic_strideszDimList[DimConstraint]constraint_sizesconstraint_stridesOptional[SymbolicContext]view_base_contextc                   | j                   <t        j                  | dt        j                  gt        | j                        z         | j                  .t        j                  | dd gt        | j                        z         | j                  .t        j                  | dd gt        | j                        z         t        d | j                   D              sJ y )Nr  r  r  c              3  ~   K   | ]5  }|t         j                  t         j                  t         j                  fv  7 y wrU   )r  r  r  r  )r  rf  s     r[   r"  z9StatelessSymbolicContext.__post_init__.<locals>.<genexpr>  s4      
 z..
0B0BJOOTT
s   ;=)
r  r   r  r  r  r#  r  r  r  r$  r   s    r[   r  z&StatelessSymbolicContext.__post_init__  s    '!(()C0B0B,CC
   ((4&3t7I7I3J*J ""**TFS9K9K5L,L  
..
 
 	
 
r\   r   )
r_   r`   ra   r   rb   r  r  r  r  r  rh   r\   r[   r   r     sE     '&+/O(//3,315.5 4807
r\   r   c                  B     e Zd ZU dZdZded<   dZded<   d fdZ xZS )	r   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.
    Nr    tensor_sourcez dict[int, dict[str, sympy.Expr]]#shape_env_to_source_to_symbol_cachec                    t         |           | j                  J | j                  st        j                  | di        y y )Nr  )rV   r  r  r  r   r  rX   rZ   s    r[   r  z%StatefulSymbolicContext.__post_init__Q  sA    !!---77t%JBO 8r\   r   )	r_   r`   ra   r   r  rb   r  r  rc   rd   s   @r[   r   r   6  s0     !M6  MQ')IPP Pr\   r   c                  4     e Zd ZU dZdZded<   d fdZ xZS )r   a  
    The correct symbolic context for a given inner tensor of a traceable tensor subclass
    may differ from that of the outer symbolic context. This structure allows for this
    flexibility, with inner symbolic contexts mapped via attr -> symbolic context.
    Nzdict[str, SymbolicContext]inner_contextsc                J    t         |           | j                  i | _        y y rU   )rV   r  r  r  s    r[   r  z%SubclassSymbolicContext.__post_init__c  s'    &"$D 'r\   r   )r_   r`   ra   r   r  rb   r  rc   rd   s   @r[   r   r   Y  s     26N.5% %r\   r   c                n    t        | t        t        t        f      ry| j                  j                         S NF)r   r   r  r   r   r  r   s    r[   r  r  i  s+     #UD)*88!!r\   c                   g g }}| D ]1  }|j                   r|j                  |       !|j                  |       3 t        j                  | g}|D ]7  }t	        j
                  ||j                        D cg c]
  \  }}||z   }}}9 t        j                  | }|t        |      dkD  xs t        |      dkD  xr t        |      dkD  fS c c}}w )Nr   r   )	r  r  r   r  	itertoolsproductrY   rN   r#  )rY   addsr   r  rY  r  r  r  s           r[   _expandsumsr  t  s    b%D ::KKLL	 ii F I$-$5$5fchh$GHDAq!a%HHI YYF3t9q=FSY]%Es5zA~FF Is   6Cc                   | j                   D cg c]  }t        |       }}t        d t        | j                   |      D              rt         | j                  |       S | j
                  r| j                   \  }}|j                  rf|j                  rZ|dkD  rt        j                  | d      S |dk  r9t        j                  t        j                  t        j                  | z  d      z  S | S | j                  rg }g }| j                   D ]T  }|j
                  r5|j                   d   dk(  r#|j                  t        j                  |z         D|j                  |       V t        |      \  }}t        |      \  }}|s|r||z  S | S c c}w )Nc              3  *   K   | ]  \  }}||u  y wrU   rh   )r  r  new_args      r[   r"  z_fast_expand.<locals>.<genexpr>  s     
K,#w3g
Ks   r   F)deepr   r  )rY   _fast_expandanyr%  funcis_Powr  r  r   expand_multinomialrO   r  r  r  r  )	r   r  new_argsbaseexpnumdennum_changedden_changeds	            r[   r  r    sR    .2YY7cS!7H7

K#dii2J
KKIDIIx011{{ II	c>>dkkQw//5AAquuu775QQQ K 
 " "99 	 CzzchhqkR/

1553;'

3		  's+[&s+[+9K7 8s   F
   c                    t        | d      r	 t        |       S | S # t        $ r t        j	                  d|        | cY S w xY w)a  
    Expand the given symbolic expression by recursively rewriting product of
    sums into sum of products (with the product being either a multiplication or
    exponentiation).

    NOTE: using this on an intermediate expression may prevent simplification
    down the line, e.g., if we eagerly expand `(a + b)^2` into `a^2 + 2ab + b^2`,
    we won't be able to simplify `(a^2 + 2ab + b^2) / (a + b)` as easily.
    expandz"RecursionError in _fast_expand(%s))hasattrr  RecursionErrorr   warning)r  s    r[   safe_expandr    sI     q(	?"
 	  	KK<a@H	s   
 !??c                  6    e Zd ZU ded<   ded<   ded<   ded<   y	)
_SymbolInfor  r>  zOptional[ValueRanges]r  zOptional[sympy.Integer]r   r   is_size_likeNr  rh   r\   r[   r  r    s    O	  r\   r  c                   i }i }t        |      D ]  \  }}|\  }}	}
}t        |
t              r|	J |rJ|rHt        d|	j                        }t        d|	j                        }||kD  r|dz
  }||k  rt        ||      }	n|	j                  }|t         u s|r|
|	j                  s|	||<   t        j                  d| dd      }t        |dz
        }||z   ||<   t        j                  |	|       ||<    	 | j                  |      }t'        t)        |            }|j*                  r|S t-        ||      }|j/                         r|j                  S |r|S dS # t         $ r t"        j%                  d| |       Y yw xY w)	a  
    This variant of ShapeEnv._maybe_evaluate_static has no dependence on
    ShapeEnv and thus can be cached indefinitely.  It does the "heavy" lifting
    for static evaluation, including nontrivial reliance on Sympy simplification
    that occurs when we reallocate the symbols
    NrD  l          r   evaluate_static_shape_Tpositiveintegerz(RecursionError in sympy.xreplace(%s, %s))	enumerater   r?   rZ  r  rY  r  rG   r;   is_intr   rR  r   rE   r  xreplacer  r   r  rr   r  r  rD   is_singleton)r   symbol_infounbacked_onlysize_obliviousnew_shape_envnew_range_envidxsinfor>  r  r   r  r  r  r  offsetnew_exprouts                     r[   _maybe_evaluate_static_workerr    s     MM, 9D
U#( 2sLc<( ~~l288$E rxx(Eu}	 ~ .HHE VG#/"))!M! LL1#7$PTU UQYv:a266rF7Cas9Dx==/ &k(&;<H h
.C
yy$8.$.!  >mTs   7E  E;:E;c                     t        d      )Nzshouldn't be hit)r  rh   r\   r[   errorr  (  s    
+
,,r\   c                >    t        t        t        | |                  S rU   )r   r=  "_eval_is_non_overlapping_and_dense)sizesr
  s     r[   !eval_is_non_overlapping_and_denser  -  s     z<UGLMNNr\   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)Nr   r   rD  keyFT)r#  sortedr%  rF  
itemgetter)r  r
  r  lengths_and_stridesexpected_stridelengthrf  s          r[   r  r  3  s     e*C
 axqzQ.%(Q,. !UG!4(:M:Ma:PQ O- "Q;_$6!" r\   c                2    t        j                  d| fd      S )Nr   rE  )r   rM  r  s    r[   rV  rV  Q  s    ??Aq69--r\   c                    t        | t              r| rdS dS t        | j                  j                        }| j                  j
                  j                  |t        |       r(t        | j                  j                                     S d       S )Nr   r   rL  )
r   r   rV  r   r   r<  r  r  r   r  )symboolint_syms     r[   r  r  U  s     '4 q""5gll6G6GHG<<!!33(7:Kc',,3356 4  QU 4  r\   )r7   r  r  r   c                    t        |      |       dt        j                  r#dt        j                  |       dfd       }nt        j                  |       d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_counterr   )rX   rY   kwargsfn_cache	prior_keyprior_versions      r[   wrapperz_lru_cache.<locals>.wrapper~  s       MMO	 5 55$$& $ 5 5 MMO	 0ONO0 D242622r\   c                r    | j                   k7  rj                          | j                    | g|i |S rU   )r(  r   )rX   rY   r)  r*  r,  s      r[   r-  z_lru_cache.<locals>.wrapper  s?      5 55$$& $ 5 5D242622r\   )rX   rl   rY   r   r)  r   r]   r   )r   configvalidate_shape_env_version_keyr   wrapsr   r   )r  r   r-  r*  r+  r,  s      @@@r[   
_lru_cacher2  h  s      "y!"%HM,,				3 
	3$ 
		3 
	3 #..G!,,GNr\   c                  P    e Zd ZU ded<    ed      Zded<    ed      Zded<   y	)
RuntimeAssertr   r   F)r   r   msgrH   stackN)r_   r`   ra   rb   r   r5  r6  rh   r\   r[   r4  r4    s'    
% C $%0E0r\   r4  c                      e Zd ZddZy)SymExprPrinterc                *    t        t        |            S rU   r   r  rX   r   s     r[   _print_FloatzSymExprPrinter._print_Float      5;r\   Nr   zsympy.Floatr]   r   )r_   r`   ra   r<  rh   r\   r[   r8  r8    s     r\   r8  c                       e Zd Z	 	 	 	 	 	 	 	 d fdZddZddZej                  d	d       Zej                  d
d       Z	 xZ
S )_ShapeGuardPrinterc                L    || _         || _        || _        t        |           y rU   )symbol_to_source
source_refr  rV   rW   )rX   rB  rC  r  rZ   s       r[   rW   z_ShapeGuardPrinter.__init__  s'     !1$,r\   c                *    t        t        |            S rU   r:  r;  s     r[   r<  z_ShapeGuardPrinter._print_Float  r=  r\   c                t    t        |t        j                        sJ t        t	        |                   d 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 rU   )r   rB  r9  r  )symbolsourcesr  rX   s      r[   repr_symbol_to_sourcez?_ShapeGuardPrinter._print_Symbol.<locals>.repr_symbol_to_source  s^     ,0+@+@+F+F+H ' w7!QVVX77 7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   r   )
r   r   rR  r   r   rB  r;  r  r  print_source)rX   r   rI  r  s   `   r[   _print_Symbolz _ShapeGuardPrinter._print_Symbol  s    $->s4:>-	 $$((. 	
f$8K8KD8Q%R1affh%R$S T+-. /ZZ	
.
   !6!6t!<Q!?@@	 &Ss   +B5
c                     y rU   rh   r  s     r[   rJ  z_ShapeGuardPrinter.print_source      r\   c                     y rU   rh   r;  s     r[   doprintz_ShapeGuardPrinter.doprint  rM  r\   )rB  #Mapping[sympy.Symbol, list[Source]]rC  Callable[[Source], str]r  rP  r]   r^   r>  r   r  r]   r   r  r   r   r]   r   )r_   r`   ra   rW   r<  rK  abcabstractmethodrJ  rO  rc   rd   s   @r[   r@  r@    sm    	=	 ,	 <		
 
	 A$ 	  	 r\   r@  c                  0     e Zd Zd fdZddZddZ xZS )ShapeGuardPythonPrinterc                ,    t        |   |  i | _        y rU   )rV   rW   _print_cacherX   rY   rZ   s     r[   rW   z ShapeGuardPythonPrinter.__init__  s    $35r\   c                $    | j                  |      S rU   )rC  r  s     r[   rJ  z$ShapeGuardPythonPrinter.print_source  s    v&&r\   c                    | j                   j                  |d       }||S t        j                  | |      }|| j                   |<   |S rU   )rY  r;  r=   rO  )rX   r   r   ress       r[   rO  zShapeGuardPythonPrinter.doprint  sK    ##D$/?J''d3C&)Dd#Jr\   rY   r   r]   r^   r  rS  r_   r`   ra   rW   rJ  rO  rc   rd   s   @r[   rW  rW    s    6'r\   rW  z`torch.fx.experimental.symbolic_shapes.ShapeGuardPrinter` is deprecated, please use `torch.fx.experimental.symbolic_shapes.ShapeGuardPythonPrinter` instead.)categoryc                      e Zd Zy)ShapeGuardPrinterNrg   rh   r\   r[   rb  rb    s     	r\   rb  c                  0     e Zd Zd fdZddZddZ xZS )_ShapeGuardCppPrinterc                J    t               | _        i | _        t        |   |  y rU   )r  all_symbolssource_to_symbolrV   rW   rZ  s     r[   rW   z_ShapeGuardCppPrinter.__init__  s"    %(U<>$r\   c                v   || j                   v r| j                   |   j                  S |j                         }t        j                  dd|      }|}d}|| j                  v r| d| }|dz  }|| j                  v rt        j                  |      | j                   |<   | j                  j                  |       |S )Nz[^0-9a-zA-Z_]+r&  r   r   )rg  r  rer(  rf  r   rR  r  )rX   r  source_namemangled_nameold_mangled_namecounts         r[   rJ  z"_ShapeGuardCppPrinter.print_source  s    T***((0555kkmvv.[A'd..../q8LQJE d... ).\(Bf%\*r\   c                .    t        j                  | |      S rU   )r<   rO  r;  s     r[   rO  z_ShapeGuardCppPrinter.doprint
	  s    !!$--r\   r^  r  rS  r_  rd   s   @r[   rd  rd    s     
.r\   rd  c                      e Zd ZU ded<   y)_ShapeGuardsHelper	list[str]exprsNr  rh   r\   r[   rp  rp  	  s    r\   rp  c                      e Zd ZU ded<   y)_CppShapeGuardsHelperzdict[Source, sympy.Symbol]rg  Nr  rh   r\   r[   rt  rt  	  s    00r\   rt  c                        e Zd Zd fdZ xZS )LoggingShapeGuardPrinterc                *    t         |   |d |       y )Nc                "    | j                         S rU   r  rX  s    r[   r1  z3LoggingShapeGuardPrinter.__init__.<locals>.<lambda>	  s    1668 r\   )rV   rW   )rX   r  rZ   s     r[   rW   z!LoggingShapeGuardPrinter.__init__	  s    );^Lr\   )r  rP  )r_   r`   ra   rW   rc   rd   s   @r[   rv  rv  	  s    M Mr\   rv  c                  4     e Zd ZdZ	 	 	 	 d fdZddZ xZS )DynamicDimConstraintPrinterz
    Printer for dynamic dim constraints.
    - Instead of symbol s_k it prints its source t.size()[i]
    - Instead of Eq(_, _), Mod(_, _), etc. it prints _ == _, _ % _, etc.

    We use this to suggest code for specifying dynamic dim constraints.
    c                >    t         |           || _        || _        y rU   )rV   rW   rB  source_name_to_debug_name)rX   rB  r}  rZ   s      r[   rW   z$DynamicDimConstraintPrinter.__init__(	  s     
 	 0)B&r\   c                    t        |t        j                        sJ t        t	        |                   | j
                  j                  |      sJ d| d       | j
                  |   d   j                         S )NzUnknown symbol z created by constraints solverr   )r   r   rR  r   r   rB  r;  r  r;  s     r[   rK  z)DynamicDimConstraintPrinter._print_Symbol1	  sy    $->s4:>-$$((
 	BTF"@A	B 
 $$T*1-2244r\   )rB   dict[sympy.Symbol, list[Source]]r}  Mapping[str, str]rR  r_   r`   ra   r   rW   rK  rc   rd   s   @r[   r{  r{  	  s'    C:C $5C5r\   r{  c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 	 ddZddZddZddZddZddZ	ddZ
dd	Zdd
Zedd       ZddZ	 	 	 	 ddZddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZy)DimConstraintsz
    Custom solver for a system of constraints on symbolic dimensions.
    Solutions are "static" values or simplified "dynamic" constraints.
    c                   t        t              | _        t               | _        i | _        || _        t        t              | _        t               | _        g | _        t               | _	        t               | _
        t        ||      | _        g | _        || _        t        t         t"        t$        h| _        | j)                          y rU   )r   r  _univariate_inequalities_symbols_with_equalities_substitutions_var_to_val_congruences_multivariate_inequalities_symbolic_equivalences_static_results_dynamic_resultsr{  _dcp_inconsistencies_marked_dynamicr2   r9   r:   r5   _supported_sympy_functions_enumerate_sympy_functions)rX   rB  r  marked_dynamicr}  s        r[   rW   zDimConstraints.__init__?	  s      	% <?5% BD BLHSTWHX >AU' HJ#
 *-*-% 07
	
 ,.  . 	@
' 	'')r\   c                (    d fd}d fd}|j                  t              r|j                  t        |      }|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 r  rewrite_with_congruencesr  r  r  r  rY   r  r   mod_reduced
congruencer  rX   s        r[   mod_handlerz<DimConstraints.rewrite_with_congruences.<locals>.mod_handler	  s    0 !MD' 994,,Q8 D --(8(89G<L<L  = K ,7JQ!!!$((4r\   c                 *   | \  }}j                  |      j                  |      }}|j                  j                        |j                  j                        z  }||z
  |z  }|dk7  rj                     j	                  |       ||z
  |z  S r  r  r  s        r[   floor_div_handlerzBDimConstraints.rewrite_with_congruences.<locals>.floor_div_handler	  s     !MD' 994,,Q8 D --(8(89G<L<L  = K ,7JQ!!!$((4 ;&'11r\   )rY   r   r]   r   )r  r9   replacer:   r5   )rX   r  r   r  r  s   ``   r[   r  z'DimConstraints.rewrite_with_congruences|	  sk    "	H	2, 88C=<<[1D 88I<<	;7D88H<<*;<Dr\   c                0   t         j                  j                  j                  }t	               }t        |      D ]:  }t        t        ||      x}t        j                        s*|j                  |       < |j                  | j                        | _        y rU   )r   r  r  r  r  dirr   r  r   FunctionClassr  
differencer  _unsupported_sympy_functions)rX   moduleall_functionsr'  r  s        r[   r  z)DimConstraints._enumerate_sympy_functions	  sy    ##--K 	(D'&$"77$9L9LM!!$'	( -:,D,D++-
)r\   c                4     |j                   | j                   S )z^
        Tracks list of sympy.Functions the export solver doesn't know how to handle.
        )r  r  r;  s     r[   _has_unsupported_sympy_functionz.DimConstraints._has_unsupported_sympy_function	  s     txx::;;r\   c                   |t         j                  k(  ry|}|j                  | j                        }|t         j                  k(  r| j
                  j                  | d       t        |t         j                        s| j                  |      ry|j                  }|s
J d|        t        |      dkD  r| j                  j                  |       yt        t        |            }t        | j                   |         }| j#                  ||      }t        | j                   |         }|t         j                  k(  r||k(  S |j                  | j                        }|t         j                  k(  r!| j
                  j                  | d| d       t        |t         j$                        r| j&                  j                  |       | j(                  |   j                  |       y)zAdd an expression to the set of constraints.

        Return whether the expression is a trivial constraint (i.e., an obvious tautology).
        Tz is inconsistent!Fz2Did not expect constraint with no free variables: r   z, obtained by rewriting z# with congruences, is inconsistent!)r   truer  r  falser  r  r   rx  r  ru   r#  r  r  r  iterr  r  rP  r  r  )	rX   r   	orig_exprorig_reducedru   r  old_n_congruencesnew_n_congruencesreduceds	            r[   r  zDimConstraints.add	  s   
 5::	 ))$*:*:; 5;;&!!((I;6G)HIdEHH%)M)Md)S((XQRVQWXX||q ++//5( # T,'(A #D$5$5a$8 900D9D #D$5$5a$8 9uzz!(,===mmD$4$45G%++%%%,,f4YK @' ' $)--11!4))!,006r\   c                    |j                   r/| j                  j                  |j                          d|        y| j                  j                  ||f       y)zAdd an equality constraint == N)r  r  r  r  r  r  )rX   r  r   s      r[   add_equalityzDimConstraints.add_equality
  sH    >>  $$d4&%AB ''..~>r\   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reduce_congruences_tmpTr  )symbolstmpc              3  N   K   | ]  }t        j                  |      s|  y wrU   )r   checksol)r  r  substitutions     r[   r"  z5DimConstraints._reduce_congruences.<locals>.<genexpr>3
  s'      ." >>*lC .s   "%)r  r9  r  rY   r   rR  solve_linearpolys	polytoolsdivr   r   r  r  ntheorymodularsolve_congruencer  )rX   reduced_congruencesr  congruencesremainder_modulus_pairscongruences_to_checkr  r  r   r  rG  solutionmodulus	remainderr  s                 @r[   _reduce_congruencesz"DimConstraints._reduce_congruences
  s   CE"//557 *	>NA{&(##&5 ) 5
 *g ll#;TJ#(#5#5dWs]6JUVTW#X  ;).)>)>)B)B8S)Q&GY!'5==9j!5==? %.$7	/66	77KL  %((4+52 '%*]]%:%:%K%K,&"	7 ,-y=G*C)D#A&weT!BBYN  $A&-- .&:.  *>#A&U*	>X #"r\   c                    | j                   rCdj                  | j                         }| j                   j                          t        d|       y )N
z*The following inconsistencies were found:
)r  joinr-  r  )rX   r5  s     r[   _raise_inconsistenciesz%DimConstraints._raise_inconsistencies=
  sI      ))D112C!!'')J3%PQQ !r\   c                d     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 ]1  } j                  |j+                  | j$                  |   i             3  j                           j                  r j-                         }|j/                         D ]  \  }}	|	D ]  }
| j$                  vs&t	        j0                  |
| j$                  |   i      r8 j3                  |
      sJ|
j                  \  }}dt5         j                  j6                  j9                   j                  j                   |   d   j#                          j                  j                   |   d   j#                                     z   }t	        j:                  |d	
      }ddlm}  ||      g j                  j                   |<   tA        t	        j                  |||z        |      }|J  jB                  j                   j                  jE                  t	        j                  ||d                         j                  j/                         D ]  \  }}	 t        j
                  j                  j                  ||      }t        |t        jF                        r't        tI         fd|j                  D                    }t        |t        j                        rF|j                  D ]6  } jB                  j                   j                  jE                  |             8 n4 jB                  j                   j                  jE                  |             	  jR                  }g  _)        |D ]0  \  }} jU                  ||j+                   j$                               2  jR                  D ]L  \  }} jB                  j                  |j#                          d j                  jE                  |              N y# tJ        tL        f$ r\}tN        jQ                  d|       |D ]6  } jB                  j                   j                  jE                  |             8 Y d}~d}~ww xY w)zGSolve the system of constraint equations to find simplified constraintsc              3  V   K   | ]!  }t        |t        j                        s| # y wrU   )r   r   rP  )r  r  s     r[   r"  z'DimConstraints.solve.<locals>.<genexpr>N
  s     OSZUXX5NSO   ))z$Expected an equality constraint for z, got zExpected a constraint on z instead of on r   r  r&  Tr  )ConstantSourceNr   c              3  X   K   | ]!  }|j                  j                        r| # y wrU   )r  r  )r  r  rX   s     r[   r"  z'DimConstraints.solve.<locals>.<genexpr>
  s+       #"||D,<,<=  s   '*z!Failed to reduce inequalities: %s)+r  r  popr  r   solversinequalitiesreduce_inequalitiesr   ru  r  rY   rP  r  r  r  rB  r  r  r  r  r  r  r9  r  _is_supported_congruencer   r}  r;  rR  torch._dynamo.sourcer  r@   r  rO  rv  r  NotImplementedErrorr  r   r  r  r  )rX   r  rr  r  rG  r   multivariate_inequalitiesr   r  r  r  r  r   tmp_namer  r  r  r  r  expr2symbolic_equivalencesr  expr3s   `                      r[   solvezDimConstraints.solveC
  s   ##% ++--113A1155a8E}}11EEeQOH(EII.OHMMO %(( J5aSxjIJ  #--KFCQ;V";A3ofX VV;  $$99--a0388:;4uE &)D" )-(G(G%.1eD+1 E4+>+>q+A'BCDE'')5 ++< #6681779 	XNA{) X
D///u~~D$7$7$: ;8 44Z@(2g#& II??CC $		 : :1 =a @ E E G $		 : :1 =a @ E E G* $ $ll8TBG;I(;S:T		2237%ehhtWs]&CQG },}--11$))2C2CEHHQPQRSPTDU2VW'X	X. 55;;= 	HHAuH ==55II%QRSh1# '/}}  H h		2'}} J--11$))2C2CC2HIJ ))--dii.?.?.IJ!	H. !% ; ;&(#2 	KMFEfennT5H5H&IJ	K "88 	XMFE!!%%tDII<M<Me<T;U&VW	X (8 H?C" HE))--dii.?.?.FGHHs   C?UV/AV**V/c                   |j                   \  }}t        |t        j                        r~|j                   \  }}t        |t        j                        xr t        |t        j
                        xs6 t        |t        j
                        xr t        |t        j                        }nt        |t        j                        }|xr t        |t        j
                        }|S rU   )rY   r   r   rN   rR  r   )r  r  r  r   rQ  rU  rS   s          r[   r  z'DimConstraints._is_supported_congruence
  s    "g
 dEII&yyHC3-P*S%--2PTS%--0RZU\\5R  dELL1D:
7EMM:r\   c                     d fd} j                   j                         D ci c]6  \  }}| j                  v r# | j                  j                  |   d         |8 c}}S c c}}w )zGReturns a dictionary of the names of symbols to their specialized valuec                    | j                         }j                  j                  rj                  j                  |    d| S |S )N = )r  r  r}  )r  r  rX   s     r[   
debug_namez9DimConstraints.forced_specializations.<locals>.debug_name
  sA    88:Dyy22))==dCDCvNNr\   r   )r  r    r]   r   )r  r9  r  r  rB  )rX   r  r  r   s   `   r[   forced_specializationsz%DimConstraints.forced_specializations
  si    	 --335
3D((( tyy11!4Q78#=
 	
 
s   ;A$c                ^    t        |t        j                  j                  j                        S rU   )r   r   exportdynamic_shapes_DerivedDimrX   r  s     r[   _is_derived_dimzDimConstraints._is_derived_dim
  s!     #u||::FFGGr\   c                    t        |t        j                  j                  j                        xr/ t        |t        j                  j                  j
                         S rU   )r   r   r  r  _Dimr  r  s     r[   _is_dimzDimConstraints._is_dim
  sI    #u||::??@ 
,,88J
 F
 	
r\   c           
         ddl m} d fd}i }t        |j                               D ]I  \  }}d|v st	        |d   t
        j                        s*t        t        |d   j                              }t        |      |vsY||t        |      <   t
        j                  j                  j                  |d   |      \  }	}
|j                  dd      }t        j                   ||
z
  |	z        }|j                  dt"              }t        j$                  ||
z
  |	z        }||d|t        |      <    |t        |      ||      |t        |      <   |j'                  dd	       |j'                  dd	       L |j)                         D ]  }t        |j                               D ]  \  }}d|v st	        |d   t
        j                        s)t        t        t        |d   j                              x}      |k(  sY|t        |         d   }|d   j+                  ||i      }||d<     t-               }|j                         D ]  \  }}||vr j/                  ||         rd|v sd|v r|j1                  |       9d|v s>t	        |d   t
        j                        s\t        t        |d   j                              }|J |j1                  t        |              |j3                  |      }i }|D ]2  }d
}||v r3||   }d|v sd|v st	        |d   t4              r ||||         s|||<   d}|s@|j                         D ]  \  }}||vr||   }|j6                  j8                  dk(  s*|j:                  j8                  |k(  sDd|v sd|v sMt        j<                  |      }t        t        |j                              }t?        t        j@                  ||d         |      d   t?        t        j@                  ||d         |      d   d} ||||         r|||<    2 5 t        |jC                               D ]#  }||vr jE                  ||         s||v s!||= % |jG                  |       y	)a
  
        Here we resolve 2 concerns with derived dims suggested fixes: 1) newly introduced roots,
        and 2) root swapping.

        1) Newly introduced roots appear with modulo guards, e.g. Mod(dx, 2) = 0 suggests
        dx is a derived dim equal to 2 * _dx, introducing a new root _dx. Currently the final
        suggested fixes handle this correctly, but we can get intermediate results that look like
        {"dy": {"eq": "dx + 1"}, "dx": {"eq": "2 * _dx + 1, "min": 3, "max": 15}}
        and this routine prettifies this by unifying to a single root, and making each suggestion
        either a derived dim or min/max range, not both.

        2) With suggested fixes for derived dims, roots can be swapped,
        e.g. dx, dx - 1 -> dy + 1, dy. Here we don't want to print out the attached name,
        since this leads to messages like "dx - 1 = Dim("dx - 1", ...)".
        Instead we evaluate the new root value, and remove results for its derivations.

        First we find all the original roots (specified in dynamic_shapes), that are found in the
        values of results (i.e. used for computing suggesting fix values). These original roots
        (suppose `dx`) are either specialized, unchanged, refined, or swapped
        (expressed as a derived dim). If any of the first 3 cases happen, we suggest `dx`'s value
        in results, and remove suggestions for derivations of `dx`, assuming the derived relation
        is valid. If swapped, we find the new root, and use the fix to evaluate `dx`'s new value,
        and then do the same with `dx`'s derivations.

        Assuming the originally specified derived relations are correct is valid, because:
            1) if the relations are plain wrong (e.g. input shape = (6, 4) with spec (dx, dx - 1))
               produce_guards() will catch this and crash before hand.
            2) if the relations are numerically correct but do not match the emitted guard,
               for example:

                    def forward(self, x, y):
                        return x.reshape([-1]) + y  # guard: s0 * 2 = s1
                    inputs = (torch.randn(6, 2), torch.randn(12))
                    dx = Dim("dx", min=2, max=32)
                    dynamic_shapes={"x": (dx, 2), "y": (dx + 6, )}  # this matches values but not op

               then this leads to 2 linear equations, and a) produce_guards() is able to solve for
               the unique solution of dx = 6 and specialize, and b) the export constraint solver will
               raise an issue due to range constraints (a unique solution means not all values in a
               range satisfy a guard) and also force specializations.
        r   )Dimc                   j                  |      xrx d| v xs d| v xrl |j                  dk  xr | j                  dd      dk(  xs |j                  | j                  dd      k(  xr# |j                  | j                  dt              k(  S )NrY  rZ  rD  )r  rY  r;  rZ  r;   )cr  rX   s     r[   _check_same_rangezDDimConstraints._process_derived_dim_roots.<locals>._check_same_range
  s     S! 4aZ-5A:4 WWq[9QUU5!_%9XcgguVW>X4
 GGquuUF33r\   r_  rY  rD  rZ  )rY  rZ  NTFr  r   )r  zMapping[str, int]r  r   r]   r   )$torch.export.dynamic_shapesr  r  r9  r   r   r  r  r  ru   r   r  r  r  r;  r  ceilr;   floorr  r.  subsr  r  r  r  r   rZ   r_   r  r0  r@   rP  r  r  r  )rX   resultsname_to_dimr  r  introduced_rootsr>  r  r  r  r  c_minmin_c_maxmax_old_rootrG  new_root_exprr  modified_rootsmodified_root_valuesmrootswapped_rootr  r   r  rY  s   `                          r[   _process_derived_dim_rootsz)DimConstraints._process_derived_dim_roots
  sX   \ 	4		* ,.) 	'DAqqyZ$<D4!5!567t9K/23$SY/).)>)>)B)B1T7D)Q&GYEE%OE99ei&77%BCDEE%0E::uy'8G&CDD15d)CGCI&-0T$-OKD	*EE%&EE%&!	'( )//1 		'HW]]_- '1AI"1T7EJJ7d4$0D0D+E&FFFG8S$+CM$:4$@M w||V],CDH&AdG'		'  $'5MMO 	.DAq#||KN+!uz""1%z!D'5::>D4!5!567'''""3t9-	. (223CD
 ;=# '	&ELENQJ%1*dGS2
 -;u- 78,U3#(L $MMO &DAq+ %a.C..-?HH--6 !A:!#(==#3D $T$*;*;%< =A'0$%1I1'Ma'P'0$%1I1'Ma'P&F $5 &E(:$ ?E 4U ; %)&''	&Z glln% 	A###KN3qN7JAJ		 	+,r\   c                T    ddl m}  j                  j                  syd d! fdt	        t
              |i }d"d}d#fd} ||      } j                  j                   j                        D ]  }	 |	      }
|
|	k(  rt        j                  d|
      \  }}}|j                         }|d	k(  r||k(  rF|j                         r |||t        |             j|j                         r || ||      t        |             |d	k(  sJ |
       	 t        j                  |      |   d
<    t#        |j%                         d       D ci c]  }|||   
 }}d}|rt'               }|D ]k  }||j                  d      d      } j)                  |      r&|j+                  |j,                  j.                         Q|j+                  |j.                         m |ddj1                  t#        |             dz  }|j3                         D ]  \  }	}|d|	 d| dz  }  j5                  |       g }g }t#        j%                         fd      D ci c]  }||   
 }}|j3                         D ]  \  }}d
|v rO|d
   }t7        |t              r|j9                  | d|        6t;        |      sB|j9                  | d|        Y|j=                  dd      }|dk(  rd}|j=                  dd      }| ||j9                  | d| d| d| d       ||j9                  | d| d| d       ||j9                  | d| d| d       |j9                  | d| d        |s|r|dz  }|dj1                  ||z         z  }|S # t         $ r Y *w xY wc c}w c c}w )$z/Format a message for constraint violation errosr   )_get_dim_name_mappingr  c                    j                   j                  j                         D ]+  \  }}|s| j                  ||      n| j                  ||      } - | S rU   )r  r}  r9  r  )r  inverser>  r?  rX   s       r[   	transformz2DimConstraints.prettify_results.<locals>.transform  sM    		;;AAC H1+2AIIaO		!QHHr\   Nc                D    | dk(  ry| dk(  ry| dk(  ry| dk(  ry| dk(  sJ | S )N<=>=<>==rh   )rF  s    r[   flipz-DimConstraints.prettify_results.<locals>.flip  s;    TzTzSySy::Ir\   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 )
Nr  rZ  r  r   r  rY  r  r  r_  rh   )r   rF  digitr  s      r[   relation_with_digitz<DimConstraints.prettify_results.<locals>.relation_with_digit  sy    Tz',e$s',qye$t',e$s',qye$Tz!z&+d#r\   z( == | <= | >= | < | > )r  r_  c                *    | j                  d      d   S )Nr  r   )splitr  s    r[   r1  z1DimConstraints.prettify_results.<locals>.<lambda>  s    aggenQ/ r\   r  r  z'Specializations unexpectedly required (, 9)! For more information, run with TORCH_LOGS="+dynamic".
z%  - solving the guards generated for z$ resulted in a specialized value of z.
c                     | d      S )NT)r
  rh   )r  r  s    r[   r1  z1DimConstraints.prettify_results.<locals>.<lambda>  s    i48 r\   rY  rD  rZ  z = Dim('z', min=z, max=r  z', max=z')z
Suggested fixes:
  
  F)r  r   r
  r   r]   r   )rF  r   r]   r   )r   r   rF  r   r  r   r]   r^   )r  r  r  r}  r   dictr  r  r  ri  r  stripisdigitr   r   r0  	TypeErrorr  r  r  r  r  r  r_   r  r9  r  r   r  r  r;  )rX   original_signaturer  constraint_violation_errorr  r  r  r  r  r  r  leftrF  rightr>  bufdebug_namesr  r   dimsothersresults2r  r   r  r  r  r  s   `                         @@r[   prettify_resultszDimConstraints.prettify_results~  s    	Fyy22	
 5@4E!N
		, ,N;%%++D,A,AB 	A!AAv hh'BAFOD"eBTzdem}}#D"c%j9#E48SY?Tz$1$z*/--*>GDM$'	, &++-/"
 %a(("
 "
 !%K+ 2!!''%."34'',OOCHH$5$56OOCLL12 9$))F;DW:X9Y ZJ JC 1668 o3>qcAefiejjmnno 	''=
 8
 wqzM
 
 NN$ 	5DAqqy$eS)MMQCs5'"23.u5MMQCs5'"23uuUD)19DuuUD)#(8KK1#XaSvVD6 KL%KK1#XaSvQ ?@%KK1#XaSvQ ?@KK1#XaS 34'	50 6++C6;;tf}--C
M ! "
>
s   NN N%	NNN)
rB  r  r  z$Mapping[sympy.Symbol, sympy.Integer]r  zset[sympy.Symbol]r}  r  r]   r^   )r  r  r   r   r]   r   r   r   rR   r]   r   )r   r   r]   r   )r  r    r   r   r]   r^   )r]   z#dict[sympy.Symbol, set[sympy.Expr]])r  r   r]   r   )r]   zdict[str, sympy.Expr])r  r   r]   z2TypeGuard[torch.export.dynamic_shapes._DerivedDim])r  r   r]   z+TypeGuard[torch.export.dynamic_shapes._Dim])r  zdict[str, dict[str, Any]]r  dict[str, Any]r]   r^   )
r!  zinspect.Signaturer  z,Union[dict[str, Any], tuple[Any], list[Any]]r"  r   r  dict[str, str]r]   r   )r_   r`   ra   r   rW   r  r  r  r  r  r  r  r  classmethodr  r  r  r  r  r*  rh   r\   r[   r  r  9	  s   
;*:;* 9;* *	;*
 $5;* 
;*zIV
<+Z?.#`RYXv   
 HH	;H


s-*s- $s- 
	s-jI-I EI %+	I
 !/I 
Ir\   r  c                  X    e Zd ZU dZded<   ded<   ded<   ded<   ded<   ded<   ded	<   y
)ShapeEnvSettingsz
    Encapsulates all shape env settings that could potentially affect
    FakeTensor dispatch. Used when creating dispatch cache keys.
    r   allow_scalar_outputsallow_dynamic_output_shape_opsassume_static_by_defaultspecialize_zero_one
duck_shape+prefer_deferred_runtime_asserts_over_guards'allow_complex_guards_as_runtime_assertsNr_   r`   ra   r   rb   rh   r\   r[   r0  r0    s3    
 $((""155-11r\   r0  c                  &    e Zd ZU dZded<   ded<   y)r   zG
    Locations of the guards that triggered lower and upper bound.
    r   r  r  Nr8  rh   r\   r[   r   r     s     KKr\   r   c              #     K   | j                          	 d  | j                          y # | j                          w xY wwrU   )_suppress_guards_enter_suppress_guards_exit)r<  s    r[   _suppress_guardsr=  '  s2     $$&*'')	'')s   >) >;>c                  T    e Zd ZU dZded<    ee      Zded<    ee      Zded<   y)	_FrameLocalResultNOptional[str]loc)default_factoryr,  localsr-  r  )	r_   r`   ra   rA  rb   r   r  rC  r  rh   r\   r[   r?  r?  0  s*    C"48FN8#D9G^9r\   r?  c            	      	   e Zd ZU ddd	 	 	 	 	 	 	 d|dZddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d}dZed~d       Zed~d	       Zed~d
       Zed~d       Z	ed~d       Z
ed~d       Zed~d       ZddZddZddZedd       Z e       dd       Z e       dd       Z e       dd       Z e       dd       Z e       	 d	 	 	 	 	 	 	 dd       Z e       dd       Z e       dd       Zd~dZ e       dd       Zedd       Z e       dd       Z e       dd       Zdd Zdd!Z dd"Z!dd#Z"dd$Z# e       	 	 	 	 	 	 dd%       Z$	 	 	 	 	 	 dd&Z%dd'Z&dd(Z'd~d)Z( e       dd*       Z) e       dd+       Z*dd,Z+dd-Z,dd.Z-	 	 	 	 	 	 	 	 dd/Z.	 	 	 	 	 	 	 	 dd0Z/dd1	 	 	 	 	 	 	 dd2Z0	 	 	 	 dd3Z1 e       dd1	 	 	 	 	 	 	 	 	 	 	 	 	 dd4       Z2	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd5Z3 e       dd6	 	 	 	 	 	 	 dd7       Z4 e       dd6	 	 	 	 	 	 	 dd8       Z5 e       	 	 	 	 	 	 	 	 dd9       Z6dd:Z7	 	 d	 	 	 	 	 	 	 	 	 	 	 dd;Z8 e       dd<       Z9 e       ddd=       Z:dd>Z; e       dd?       Z< e       e=j|                  ddf	 	 	 	 	 	 	 	 	 	 	 dd@       Z? e       e=j|                  ddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddA       Z@ddBZAddCZB	 	 	 	 	 	 ddDZCddEZDdF fddddddGdH	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddIZEdddJ	 	 	 	 	 	 	 ddKZFddLZGddMZHddNZIddO	 	 	 	 	 	 	 ddPZJddQZK	 	 	 	 	 	 ddRZLddSZMdddTZN	 d	 	 	 	 	 ddUZOeP	 	 d	 	 	 	 	 ddV       ZQ eRd      	 	 	 	 ddW       ZSePddddddX	 	 	 	 	 	 	 	 	 	 	 	 	 ddY       ZTePddZ       ZUePdd[       ZVePddd\       ZW eRd]      dd^	 	 	 	 	 dd_       ZX eRd]      dd`       ZYddda	 	 	 	 	 	 	 	 	 ddbZZ	 dddc	 	 	 	 	 	 	 	 	 dddZ[ddeZ\ddfZ]eP e       ddg              Z^ eRd]      ddh       Z_	 d	 	 	 ddiZ`ddjZaePddk       ZbddlZc	 d	 	 	 	 	 ddmZddddnZeddoZfddpZgdZhdeidq<   	 d	 	 	 	 	 ddrZj eRd]       eds      	 	 	 dddt	 	 	 	 	 	 	 	 	 	 	 ddu              Zk	 	 	 dddt	 	 	 	 	 	 	 	 	 	 	 ddvZlddwZm eRd]       eds      	 d	 	 	 	 	 	 	 ddx              ZnddyZo eRdz       e       	 	 	 	 	 	 	 	 dd{              Zpy)rl   N)should_record_eventstracked_fakesc               `    | j                   di | d|d<   ddlm}  |       | _        ||n| j                  xr t        j
                   | _        | j                  xr t        j                  | _        d| _	        || _
        | j                  rt        t        |      gng | _        i | _        y )NFrE  r   translation_validation_enabled)r)  rh   )_inittorch.fx.experimental.validatorrI  _translation_validation_enabledr/   translation_validation_no_bisectrE  check_shape_env_recorded_eventscheck_recorded_eventsis_recordingrF  r-   rl   eventsfake_tensor_cache)rX   rE  rF  r)  rI  s        r[   rW   zShapeEnv.__init__B  s     	

V */%&R/M/O, $/ ! 44 @??? 	! %%P&*P*P 	"
 "* (( 8F34 	   	r\   TF)r1  r2  r3  r4  r5  	co_fieldsr6  r7  c          	        |t         j                  }t        |||||||      | _        g | _        i | _        i | _        i | _        i | _        i | _	        i | _
        i | _        i | _        i | _        i | _        i | _        i | _        i | _        t%               | _        t%               | _        i | _        |r:t,        j.                  j0                  t,        j.                  j2                  d| _        t5        j6                         | _        t5        j6                         | _        i | _        d| _        t@        | _         | j@                  jC                  d       d| _"        d| _#        d | _$        tK        jL                         | _'        tK        jL                         | _(        |r|ni | _)        g | _*        | jW                         | _,        d| _-        d| _.        i | _/        i | _0        i | _1        ddl2m3}	  |	       | _4        | jh                  rqddl2m5}
  |
       | _6        tn        jp                  js                         | _:        | jt                  jw                  | jt                  jy                  d              i | _=        y y )	N)r1  r2  r3  r4  r5  r6  r7  r   r   r   
create_envFTrH  )TranslationValidator)>r/  use_duck_shaper0  settingsr   axiomsr  unbacked_var_to_valoblivious_var_to_valrS  var_to_range_slocr}  r  var_to_stacksource_to_varreplacementsreplacements_slocsr:  r  	divisible	size_like
val_to_varr   rO   r  r  r  rm  unbacked_symfloat_counterunbacked_symint_counterdeferred_runtime_assertsnum_deferred_runtime_assertsr   rJ  r  runtime_asserts_frozendim_constraintscollectionsr   countersymbol_guard_counterrS  r,  r'  _prev_cache_keyr(  _resimplify_floor_div_axiomsfx_node_cacherg  unbacked_alloc_orderrK  rI  rL  rW  	validatorr   r   Graphr  inserting_beforeoutputname_to_node)rX   r1  r2  r3  r4  r5  rS  r6  r7  rI  rW  s              r[   rJ  zShapeEnv._init  s;   R ..J(!5+I%= 3!8c4[

 )+46 >@ GI  HJ!
 >@FH9;&@BCE68 =?<>DF*-% -0E 46"''',,577;;?DO)2):&'0'8$>  	% -.)l#&+#9=%0%8%8%: <G;N;N;P! '0R( CE+  $}} ! -1) UW9;6 >@!R/M/O,//L13DN)DJ JJ''

(9(9$(?@ ;=D# 0r\   c                .    | j                   j                  S rU   )rY  r1  r   s    r[   r1  zShapeEnv.allow_scalar_outputsh  s    }}111r\   c                .    | j                   j                  S rU   )rY  r2  r   s    r[   r2  z'ShapeEnv.allow_dynamic_output_shape_opsl  s    }};;;r\   c                .    | j                   j                  S rU   )rY  r3  r   s    r[   r3  z!ShapeEnv.assume_static_by_defaultp  s    }}555r\   c                .    | j                   j                  S rU   )rY  r4  r   s    r[   r4  zShapeEnv.specialize_zero_onet  s    }}000r\   c                .    | j                   j                  S rU   )rY  r5  r   s    r[   r5  zShapeEnv.duck_shapex  s    }}'''r\   c                .    | j                   j                  S rU   )rY  r6  r   s    r[   r6  z4ShapeEnv.prefer_deferred_runtime_asserts_over_guards|  s    }}HHHr\   c                .    | j                   j                  S rU   )rY  r7  r   s    r[   r7  z0ShapeEnv.allow_complex_guards_as_runtime_asserts  s    }}DDDr\   c                ,    d}dd}t        | |||       y)z(Compare another ShapeEnv for equivalence)rl  r   r^  rp  r  rr  rO  rE  rP  rF  rQ  r}  rn  r(  rj  r]  ra  ro  _expr_sym_node_idc           
     h   | dv rddl m } t         ||            S | dk(  r|D cg c]  }|j                   c}S | dk(  r>|j                         D ci c]   \  }}||D cg c]  }|j                   c}" c}}}S | dk(  rt	        |j                               S | dv ry |S c c}w c c}w c c}}}w )N)re  rf  r   )r  r   rg  rv  )rm  r,  rR  )r  r  r   r9  r  r  )r  valuer  gr  rasras          r[   	map_valuez'ShapeEnv.check_equal.<locals>.map_value  s    NN%
 DK(((-.1..22AFOOvq#c2BGG22OO&5::<((   L / 3Os   B#B-!B(4B-(B-N)r  r   r  r   r]   r   )r,   )rX   r   non_state_variable_namesr  s       r[   check_equalzShapeEnv.check_equal  s     $
 <	4 	$D%1I9Ur\   c                    | j                   y ddlm dfd}| j                   D cg c]
  } ||       c}S c c}w )Nr   )TrackedFakec                    t        | j                  t        j                  t        j                  f      r| j                  nt        j                  | j                        } || j                  | j                        S rU   )	r   faker   r   r   r)   	from_faker  r  )r  
inner_faker  s     r[   maybe_transform_fakez>ShapeEnv._snapshot_tracked_fakes.<locals>.maybe_transform_fake  s[     dii%,,)GH 		#--dii8  z4;;8M8MNNr\   )r  r  r]   r  )rF  torch._dynamo.variables.builderr  )rX   r  r  r  s      @r[   _snapshot_tracked_fakesz ShapeEnv._snapshot_tracked_fakes  s=    %?
	O 8<7I7IJt$T*JJJs   ;c                2    t        | j                        dz
  S Nr   )r#  rQ  r   s    r[   _last_event_indexzShapeEnv._last_event_index  s    4;;!##r\   c              #  J   K   d| _         	 d  d| _         y # d| _         w xY wwNTF)rP  r   s    r[   
_recordingzShapeEnv._recording  s&      	& %DDs   # #	 #c                *    | j                  ||d       y )Neliminate_unbacked)_set_replacement)rX   orig_sr9  s      r[   r/  zShapeEnv._eliminate_unbacked  s    fe-ABr\   c                v    t         j                  d||       t        j                  |      | j                  |<   y)zUsed only when propagate_real_tensors; registers a value for an
        unbacked symbol, which can be used last resort to resolve hints.zset_unbacked_var_to_val %s = %sN)r   rJ  r   r0  r[  )rX   r>  r?  s      r[   r"  z ShapeEnv.set_unbacked_var_to_val  s.     	2Aq9&+mmA&6  #r\   c                   t        |t        j                        sJ |       t        |t        j                        sJ |       t        |      sJ |       t        |      sJ |       | j                  j                  |      }|t        |      rJ | d|        | j                  ||d       || j                  |<   || j                  ||d       y y )Nz -> rename_unbacked_torename_unbacked_to_dest)r   r   rR  r  r`  r;  r  r:  )rX   r  r9  dests       r[   rW  zShapeEnv._rename_unbacked_to  s    &%,,/77/%.55.$U+2U2+$V,4f4,  $$V,,T2Ivhd4&4II2fe-AB*/'!!%/HI r\   c                     y rU   rh   )rX   r  rU  s      r[   rT  zShapeEnv._constrain_is_bounded  s     	r\   Optional[int]c                    |d}|t         }||k  rt        d      | j                  |||       | j                  j	                  |       y )Nr   r\  rL  rM  )r;   r  rK  rc  r  rX   r  rY  rZ  s       r[   rQ  z"ShapeEnv._constrain_range_for_size  sc     ;C;C93 
 	## 	$ 	

 	1r\   c           	         t        |t        j                        r5|t        |      cxk  r|k  s n t	        dt        |       d| d| d      y t        |t        j
                        r| j                  |||       y y )Nr]  r^  r_  r`  r  )r   r   r   r   rF   rR  rK  r  s       r[   ra  zShapeEnv._constrain_range  s|    a'3q6(S(%s1vhl3%qQTPUUV&WXX a&''   (  'r\   c                   t        |t              st        |t              s||k(  sJ t        |j                  j                  t        j
                        sJ d       |j                  j                  | u sJ t	        j                  |      | j                  |j                  j                  <   yyt        |j                  j                  t        j
                        sJ d       |j                  j                  | u s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!)
        zconstraining non-Symbols NYIN)
r   r   r   r   r   rR  r<  r   r`  r  )rX   r  r  new_vars       r[   rd  zShapeEnv._constrain_unify+  sr    !V$a(Avv!FFKK 212  vv''4///16q1A!!!&&++.  affkk5<<8X:XX866##t+++a(16q1A!!!&&++.vv''166+;+;;;;!FFKK 212  **QVV[[118!!!&&++.r\   c                $    t        t        dd      S )Nignore_fresh_unbacked_symbolsFr  TLSr   s    r[   "_ignore_fresh_unbacked_symbols_tlsz+ShapeEnv._ignore_fresh_unbacked_symbols_tlsQ  s    s;UCCr\   c                <    | j                         }|t        _        |S rU   )r  r  r  )rX   r  prevs      r[   "_ignore_fresh_unbacked_symbols_setz+ShapeEnv._ignore_fresh_unbacked_symbols_setT  s    668,-)r\   c              #     K   | j                  d      }	 d | j                  |       y# | j                  |       w xY ww)za
        Indicates that the newly allocated unbacked SymInts are being
        discarded
        TN)r  )rX   r  s     r[   r  z&ShapeEnv.ignore_fresh_unbacked_symbolsZ  s<      66t<	:33D9D33D9s   A+ A>Ac                    d| _         y)zFreeze this ShapeEnv to stop accumulating guards

        A frozen ShapeEnv will ignore any further guards generated on it and
        only emit a warning which may lead to accuracy problems.
        TNr  r   s    r[   freezezShapeEnv.freezef  s     r\   c                    d| _         y)a_  Freeze this ShapeEnv to stop adding deferred runtime asserts.

        We will error if you try to install a new runtime assert when it is
        frozen.  This would indicate a lowering violation, or perhaps something
        we know statically is already True but we are checking it again in a way
        that is not clearly dischargeable.
        TN)ri  r   s    r[   freeze_runtime_assertszShapeEnv.freeze_runtime_assertso  s     '+#r\   c                    | j                   sy |j                         }|| j                  vr$t        j                  |d      | j                  |<   | j                  |   S )NTr  )rL  r  rg  r   rR  )rX   r  srcnames      r[   _create_symbol_for_sourcez"ShapeEnv._create_symbol_for_source{  sS    33++-...-2\\'4-PD!!'*$$W--r\   c                V    | j                   r| j                  j                  ||       y y rU   )rL  rr  add_var)rX   rG  r   s      r[   
_add_z3varzShapeEnv._add_z3var  s$    //NN""640 0r\   c                T    | j                   r| j                  j                  |       y y rU   )rL  rr  add_target_exprr;  s     r[   _add_target_exprzShapeEnv._add_target_expr  s"    //NN**40 0r\   c                T    | j                   r| j                  j                  |       y y rU   )rL  rr  add_assertionr;  s     r[   _add_assertionzShapeEnv._add_assertion  s"    //NN((. 0r\   c                R    | j                   r| j                  j                          y y rU   )rL  rr  validater   s    r[   _check_translation_validatez$ShapeEnv._check_translation_validate  s     //NN##% 0r\   c                   ||f}d}| j                   r|| j                  vrt        d |D              rt        d |D              sJ d |fS d}t        d |D              sJ d|j                   d|        | j
                  j                  ||      x}| j                  |<   || j                  |j                  <   | j                  j                  |d       |fS )NFc              3  $   K   | ]  }|d u  
 y wrU   rh   r  r  s     r[   r"  z4ShapeEnv._create_fx_call_function.<locals>.<genexpr>  s     +19+   c              3  f   K   | ])  }t        |t        j                  j                          + y wrU   )r   r   r   rj  r  s     r[   r"  z4ShapeEnv._create_fx_call_function.<locals>.<genexpr>  s"     Jz!UXX]];;Js   /1Tc              3  $   K   | ]  }|d u 
 y wrU   rh   r  s     r[   r"  z4ShapeEnv._create_fx_call_function.<locals>.<genexpr>  s      "#r  zmissing arg in FX graph (z): )
rL  rp  r  r$  r_   r  ri  rv  r  r;  )rX   rF  rY   node_keyfreshr   s         r[   _create_fx_call_functionz!ShapeEnv._create_fx_call_function  s     ://HDDVDV4V+d++ JTJJJJU{"E  '+  B*2;;-s4&AB  37**2J2J2t2TTD4%%h/+/Ddii(!!%%h5u<<r\   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  rG  )
rL  r  rB  rp  r  ri  r(  r  rv  rG  )rX   rG  r   r  rk  r   s         r[    _create_fx_placeholder_and_z3varz)ShapeEnv._create_fx_placeholder_and_z3var  s    
 33JJ**VI6
 4---OOFD)66bffWb&++&FL 37**2H2H2VVD4%%h/+/Ddii( #)DIIh!!(++r\   c                    | j                   rD|A| j                  j                  |j                         | j                  j                  |       y y y rU   )rL  rv  r  r  r  
erase_node)rX   r   s     r[   _remove_fx_nodezShapeEnv._remove_fx_node  sC    //D4D!!$)),JJ!!$' 5E/r\   c                    ddl m} | j                  r:| j                         |j                  t
        <    |       |j                  t        <   y y )Nr   )get_current_node)torch._dynamo.utilsr  rE  r  rG  ry   rz   )rX   r   r  s      r[   _add_fx_node_metadatazShapeEnv._add_fx_node_metadata  s=    8$$,0,B,B,DDII()*:*<DII&' %r\   c                $    t        t        dd      S )Nsuppress_guardsFr  r   s    r[   _suppress_guards_tlszShapeEnv._suppress_guards_tls  s    s-u55r\   c                    t        t        d      sg t        _        | j                         }t        j                  j	                  |       dt        _        y )Nsuppress_guards_stackT)r  r  r  r  r  r  rX   r0  s     r[   r;  zShapeEnv._suppress_guards_enter  s?    s34(*C%'')!!((-"r\   c                    t        t        j                        dkD  rt        j                  j                         nd}|t        _        y )Nr   F)r#  r  r  r  r  r  s     r[   r<  zShapeEnv._suppress_guards_exit  s=     3,,-1 %%))+ 	
 "r\   c                    t        |       S )z5Context manager to ignore all guards generated inside)r=  r   s    r[   r  zShapeEnv.suppress_guards  s    %%r\   c                    t        | j                        t        | j                        | j                  t        | 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`  rb  rh  r[  r   s    r[   r'  zShapeEnv._get_key  s?     !!"--(()	
 	
r\   c                    t        | j                        | j                  d   k7  rd| _        | j	                         }| j                  |k7  r|| _        | xj
                  dz  c_        y y )Nr   T)r#  rb  rn  ro  r'  r(  )rX   cur_keys     r[   _update_version_counterz ShapeEnv._update_version_counter  sa    
 t~~$"6"6q"9904D- --/7*#*D !!Q&! +r\   c                :    | j                  t        |      ||      S rU   )!_produce_dyn_sizes_from_int_tuplerN  )rX   ex_sizer  r  s       r[   _produce_dyn_sizeszShapeEnv._produce_dyn_sizes  s#     55'NF$4
 	
r\   c           	        t        d |D              s
J d|        ddlm}m} t	        |       |j
                  }|j                  }g }t        |      D ]  \  }	}
| j                  |
 |||j                  |	      ||	   ||	   t        j                  |      }t        j                  rOt        |t        j                        r5t        |t         j                        r| j"                  j%                  |       |j'                  |        |S )Nc              3  4   K   | ]  }t        |         y wrU   )r  )r  r   s     r[   r"  z=ShapeEnv._produce_dyn_sizes_from_int_tuple.<locals>.<genexpr>!  s      
%(C  
r  z0Expect size to be a plain tuple of ints but got r   TensorPropertyTensorPropertySource)do_not_specialize_zero_oner  )r$  r  r  r  r  r  r  r  create_symbolSIZEr/  backed_size_obliviousr   r   rR  rB   rC   rc  r  r  )rX   tensor_sizer  r  r  r  dynamic_dimsconstraint_dimsre  r6  r   syms               r[   r  z*ShapeEnv._produce_dyn_sizes_from_int_tuple  s     
,7
 
 	L=k]K	L 
 	N/0'55*;;, 	FAs$$$V^-@-@!DQ"+1+G+G!1 % C ,,sELL1"3		2""3'KK	  r\   r  c               `    t         fd|j                         D              }t         fd|j                         D              } j                  |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.
        c              3  @   K   | ]  }j                  |        y wrU   #_maybe_specialize_sym_int_with_hint)r  szrX   s     r[   r"  zHShapeEnv.create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>M  s!      
=?D44R8
   c              3  @   K   | ]  }j                  |        y wrU   r  )r  sdrX   s     r[   r"  zHShapeEnv.create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>P  s!      
=?D44R8
r  r  )	rN  re  rf  r  rg  -_create_symbolic_sizes_strides_storage_offsetr  r  _is_dim_dynamic)rX   exr  r  r  	ex_strideex_storage_offsetr6  s   `       r[   ,create_symbolic_sizes_strides_storage_offsetz5ShapeEnv.create_symbolic_sizes_strides_storage_offset<  s    "  
CE779
 
  
CE99;
 
	 !DD
 AA-22668_=_R#=- B 
 	
 >s   B+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.)r   r   r   r   r  r   r<  r  )rX   	maybe_syms     r[   r  z,ShapeEnv._maybe_specialize_sym_int_with_hint  sb     )c5<<%8999y!((4XWX4>>..00r\   c                  t        |      }|d g|z  }d g|z  }	g }
g }t        |      D ]g  }||   rt        j                  }n-| j                  rt        j
                  }nt        j                  }|
j                  |       |j                  |       i t        j                  g|z  }
t        j                  g|z  }t        |
|||	      }t        |       |j                  }|j                  }	|j                  }|j                  }t        d |D              rt        j
                  nt        j                  }t        d |D              }t        |      |k(  sJ t        |       d|        t        |      |k(  sJ t        |       d|        t        |      |k(  sJ t        |	      |k(  sJ ddlm}m} | j'                  |||      }| j)                  ||||||	||      }t+        t-        ||            D cg c].  \  }\  }}| j/                  || |||j0                  |            0 }}}}g }t+        |      D ]A  \  }}|J |j                  | j/                  |||    |||j2                  |                   C | j/                  | j5                  | |||j6                        |d |      | |||j6                              }t9        |      t9        |      |fS c c}}}w )	Nr  r  r  r  c              3  B   K   | ]  }|t         j                  k(    y wrU   r  r  r  r  s     r[   r"  zIShapeEnv._create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>  s     Aa1
)))A   c              3  B   K   | ]  }|t         j                  k(    y wrU   r  r  s     r[   r"  zIShapeEnv._create_symbolic_sizes_strides_storage_offset.<locals>.<genexpr>  s     M!qJ$5$55Mr  r,  r   r  r  dynamic_dimconstraint_dimr  )r#  r  r  r  r3  r  r  r  r  r   r  r  r  r  r  r$  r  r  r  r  _compute_symbolic_strider  r%  r  r  STRIDEr  STORAGE_OFFSETrN  )rX   r  r  r  is_dim_dynamicr  r  r  r  r  r  r  r6  r  r  dynamic_offsetare_sizes_staticr  r  re  rf  r  rL  	sym_sizesro  stride_exprrp  s                              r[   r  z6ShapeEnv._create_symbolic_sizes_strides_storage_offset  sN   " 'l #59FSL7;fslL O3Z 
* "!$"**A22"))A"A##A&&&q)
* 'OO,s2L)667#=O7* /!1#5	  	/0+<<-@@(66*:: A=AA  	
 M}MM=!S(JS-?,@SE*JJ(?#s*Ls=/A.B$se,LL*#$+++%&#---M!%!G!GV-"
 ..	
" #,Cg,>"?
 
 ;C ""+FN4G4GK # 
	 
 
'/ 
	NA{ ***&&"1/8M8MqQ ' 	
	 "33!$V^-J-JK*#!1   #'0M0MN 4 

 Yz!24FFF?
s   ;3K$c	           	        ddl m}	m}
 d gt        |      z  }i }t	        |      D cg c]
  \  }}|| f }}}|j                  t               |D ]  \  }}| }|t        |      dz
  k7  xr ||   ||dz      ||dz      z  k(  }|dv r|st        j                  |      }n||   }|t        j                  k(  r
||v r||   }nb|}|t        j                  k(  r"|rt        j                  nt        j                  }| j                  | |
||	j                  |      |||   |      }|||<   ||   |z  |||   |z  <    t        d |D              sJ |S c c}}w )Nr   r  r  r   rU  r
  c              3  $   K   | ]  }|d u 
 y wrU   rh   )r  r  s     r[   r"  z4ShapeEnv._compute_symbolic_stride.<locals>.<genexpr>;  s     1Q1D=1r  )r  r  r  r#  r  r  r   r   r   r  r  r  r  r  r  r$  )rX   r  re  r  r  r  r  r  r  r  r  rf  
candidatesr6  r   val_listneg_icontiguous_stride
out_stridedynamic_stride
dyn_strides                        r[   r  z!ShapeEnv._compute_symbolic_stride  s    	N.2Vc$i-?;=
 -6i,@A&!SS1"IAA01" 	@JCAS^a'' FaLGAENYq1u5E$EE  f}%6"]]3/
!0!3!Z%<%<<
AR!+CJ "0J%)@)@@1AJ--z # "&!3!3,V^5J5JAN$.'9!'<)9 "4 "J #F1I+/7Z+?JwqzC'(9	@< 1&1111E Bs   E)r  c          	        | j                   rS|Q| j                  |      }|J | j                  |t              }| j	                  t        j                  ||             nd}t        |t
        j                        r|t        |      |k(  sJ t        |      }|S t        |      rd}t        t        || t        ||            }|S )zCreate a SymInt value from a symbolic expression

        If you know what the current hint value of the SymInt to be created
        is, pass it into hint.  Otherwise, pass None and we will make our best
        guess

        Nfx_node)rL  r  r  r   r  r   rP  r   r   r  r   r.   rX   r  rL  r  rG  r   r  s          r[   r  zShapeEnv.create_symintnode>  s     //F4F33F;F%%% ;;FCHG  56G c5==)3x4'''c(C 
 %S)dCwGHC
r\   c          	        | j                   rS|Q| j                  |      }|J | j                  |t              }| j	                  t        j                  ||             nd}t        |t
        j                        r|t        |      |k(  sJ t        |      }|S t        |      r	|J |       t        t        || t        ||            }|S )z2Create a SymFloat value from a symbolic expressionNr  )rL  r  r  r  r  r   rP  r   r  r  r   r.   r!  s          r[   create_symfloatnodezShapeEnv.create_symfloatnodej  s     //F4F33F;F%%% ;;FEJG  56G c5;;'SzT)))*C 
 %S)|(S(|73eT7KLC
r\   c                N    | j                  | j                  |||      ||      S )z1Create a SymInt wrapping a new unspecified symbol)r  r  r  )r  create_unspecified_symbol)rX   r  r  r  s       r[   $create_unspecified_symint_and_symbolz-ShapeEnv.create_unspecified_symint_and_symbol  s@    
 %%**' + 
  & 
 	
r\   c                8    t        t        || t        d            S )z7Create a SymBool object from a sympy boolean expressionN)r   r.   r   rX   r  s     r[   create_symboolnodezShapeEnv.create_symboolnode  s     wsD$566r\   c           
     ^   t         j                  d uxr* t              t         j                  j                  d      v }|| j	                  |      \  }}n|j                         d}}t        j                  d|j                  j                  |||       t        dfd       y )N,r  z%s %s [%s, %s] %s%s
stack_infocreate_unbacked_symbolc                     t              t               dj                   dj                   dt	        j
                  d      t	        j                         dS )N[r  r`  r  )rG  node_idr  
user_stackr6  )r   idr  r  r$   get_user_stackget_framework_stack)r   rG  r  s   r[   r1  z6ShapeEnv._log_create_unbacked_symbol.<locals>.<lambda>  sL    f+h<"((2bhhZq1(77:#779! r\   metadata_fn)r/  extended_debug_create_symbolr   r  _get_stack_summaryr  r   rJ  r  r  r%   )	rX   prefixrG  r  r  r   is_debugslocmaybe_extra_debugs	     `` `   r[   _log_create_unbacked_symbolz$ShapeEnv._log_create_unbacked_symbol  s     66dB <sH
0066s;H< >&*&=&=h&G#D#&,kkmR#D!HHHH 	 		
 	$		
r\   c                n   t        t        j                  t        | j                              }| j
                  dxx   dz  cc<   | j                         s| j                  j                  |       t        j                  d      | j                  |<   t        j                         x}| j                  |<   |j                  sJ | j!                         }t#        ||      | j$                  |<   | j'                  |t(              }t+        || t(        d|      }| j-                  d|||       t/        |      S )z,Create a symbolic float without a hint valuer.  r   rm  Nr  create_unbacked_symfloatr   )rA   rC   r  r  re  rl  r  r,  r  rH   extractr^  rG   unknownrS  is_float	_get_slocr   r]  r  r  r.   r>  r   rX   rG  r  r<  r   r   s         r[   rA  z!ShapeEnv.create_unbacked_symfloat  s     +d&D&D!E 
 	-.!3.668//66v>$5$=$=1$E&!)4)<)<)>>Tv&{{{~~)8t)Dv& 77F64gF((&X 	) 	
 !!r\   c                l   t        t        j                  t        | j                        d      }| j                         s| j                  j                  |       | j                  dxx   dz  cc<   t        j                  d      | j                  |<   | j                         x}| j                  |<   |j                  sJ | j                         }t!        ||      | j"                  |<   | j%                  |t&              }t)        || t&        d|      }| j+                  d||||	       t-        |      S )
z.Create a symbolic integer without a hint valueTr  r.  r   r@  Nr  create_unbacked_symintrB  )rA   rC   r  r  rf  r  r,  r  rl  rH   rC  r^   _default_unspecified_value_rangerS  r  rF  r   r]  r  r   r.   r>  r   )rX   r  rG  r  r<  r   r   s          r[   rI  zShapeEnv.create_unbacked_symint  s     +tD$@$@A4 
 668//66v>-.!3.$5$=$=1$E&!)-)N)N)PPTv&yyy~~)8t)Dv& 77D64dGD(($fb&8 	) 	
 hr\   c                6    t        |t        j                        S )zJCheck if a sympy symbol matches the naming convention for unbacked symbolsrB   rC   r  )rX   rG  s     r[   rP  zShapeEnv.is_unbacked_symint  s    fd&7&788r\   c                   t        t        j                  t        | j                        d      }| j                         s| j                  j                  |       | j                  dxx   dz  cc<   t        j                  d      | j                  |<   t        dd      x}| j                  |<   |j                  sJ | j                  d      }t!        ||      | j"                  |<   | j%                  |t&              }t)        t+        j,                  |d      | t&        d|	      }| j/                  d
|||       t1        |      S )z.Create a symbolic boolean without a hint valueTr  r.  r   r@  r   z(default value range for unbacked SymBoolNr  create_unbacked_symboolrB  )rA   rC   r  r  rf  r  r,  r  rl  rH   rC  r^  rG   rS  r  rF  r   r]  r  r   r.   r   rP  r>  r   rG  s         r[   rN  z ShapeEnv.create_unbacked_symbool  s      +tD$@$@A4 
 668//66v>-.!3.$5$=$=1$E&!)4Q)::Tv&yyy~~HI)8t)Dv& 77E588FA.dD'R((%vrH 	) 	
 x  r\   c           	     2    | j                  ||||dd|      S )z
        Create a symbol with an unspecified value

        Compared to standard symbols we do not assume the value is positive,
        nor do we specialze on zero or one values.
        NT)r  r  r  )r  )rX   r   r  r  r  r  s         r[   r%  z"ShapeEnv.create_unspecified_symbol  s1    ( !!'+- " 
 	
r\   c                   t        |t              r|j                  j                  |j                  j                  k(  rt
        j                  }|j                  j                  k7  r6t        d|j                  j                   d dj                                |rTddl	m
} t        |      sJ j                  J ||j                  j                  <   d|j                  j                  <   d}j                         }	t        |t              r/t        |       |j                   vri |j                   t        |       <   t        |t              r7|	r5|	|j                   t        |          v r|j                   t        |          |	   S |t
        j"                  t
        j$                  fv r| j'                        j(                  j*                  }
| j-                  |
       t        |t              r|	r|
|j                   t        |          |	<   |t
        j$                  u r| j.                  |
<   |
S |rd}n| j0                  }t        t2              sJ t5               d        |rdk  r
J d	        |t
        j6                  }|t
        j                  u rDt9        j:                        }
t        |t              r|	r|
|j                   t        |          |	<   |
S |t
        j<                  u r| j>                  }n#|t
        j6                  u rd}ntA        d
|       | jC                         }dv r|r| jD                     }nx|r| jD                  vrt5              tF        u stI              r1tK        tL        jN                  tQ        | jR                        |d      n0tK        tL        jT                  tQ        | jR                        |d      | jV                  |	<   t        tF              r#t9        j:                        | jR                  <   n}t        tX              r#t9        jZ                        | jR                  <   nJt]        j(                  j_                         j(                  ja                               | jR                  <   g | jb                  <   | je                  tF               |r| jD                  <   t        tF              r:|ri| jg                  dkD         | ji                  |      | jj                  <   tm        | jC                  | j0                  rdnd      |      | jn                  <   n6| jq                         | jj                  <   tm        ||      | jn                  <   t        |t              r"|rJ | js                  |j                  d       | jj                     }|jt                  sJ |vr(t         d|j                   d|j                   d      d|j                   d|j                   dnt        tX              r|tw        t8        jx                   t8        jx                        x| jj                  <   }tm        ||      | jn                  <   d|j                   d|j                   d|jz                  sJ d}t|        j~                  duxr* t              t|        j~                  j                  d      v }d}|st        j                  dd      dvrd d}| j                  |      \  }}| j                  j                  dj                         ||||	       t        d fd!"       | j                  d xx   dz  cc<   nI| jD                     }|| jV                  |	<   | j                  j                  d#|j                                t        |t8        j                        rc| jb                  |   }|j                         j                         s$|d   j                         r|d$   |d   c|d<   |d$<   d| j                  |<   t        |t              r|	r||j                   t        |          |	<   |S )%z5Create a new symbol which is tracked by this ShapeEnvzStatic shape constraint of z does not match input size of z, for r   )r  NFr  z!positive set for negative value: zunhandled dynamic_dim rU  Tr   )r  r  )r)  r   zuser code shown is first use of this value--the guard itself is not due user code but due to 0/1 specialization in the framework; to avoid specialization try torch._dynamo.mark_unbacked(tensor, dim)is_constraintz not in range [r  r`  r0  r  r+  TORCHDYNAMO_EXTENDED_ADVICE1)0r  zC, for more info run with TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL="zF" or to suppress this message run with TORCHDYNAMO_EXTENDED_ADVICE="0"z&create_symbol %s = %s for %s %s %s%s%sr,  r  c            
     
   t              t               j                         t        j                  t        j                               t        j                  t        j                  d      j                               dS )Nr   r@  )rG  r   r  r  r2  r6  )
r   r   r  r$   from_tracebackr!   extract_stackrH   rC  summary)	range_strr  
sympy_exprr   s   r[   r1  z(ShapeEnv.create_symbol.<locals>.<lambda>  se    !*o9#$kkm",";";&446# (66)11q9AAC% r\   r6  zcreate_symbol %s duck sized %sr  )Nr   r  r  r  r  r  r  r   r  r  r  r  r  r  r   r3  r  r  r  rI  r   r   rQ  r\  r4  r    r   r  r   r   r  r5  r  rF  rd  r   rx   rA   rC   r  r#  r  FLOATr_  r  r  r?   
nested_intr   r  r  r  _default_value_rangerS  r   r]  rJ  _update_var_to_ranger  rG   oorE  r/  r8  r   r  osgetenvr9  r   rJ  r%   rl  r   rR  r  is_ephemeralrm  )rX   r   r  r  r  r  r  r  r  rj  r  r4  duckr<  r  r  r;  maybe_more_infor=  	r_sourcesrZ  r[  s    ``                 @@r[   r  zShapeEnv.create_symbol6  s    ~'=>!!''>+<+<+B+BB$++K  &&#-.1.2C2C2I2I1JJhilhm n!;;=/+   E!&*>???zz---=H ..vzz:@D 11&**=!N kkm')@A4 0 T TTMO@@DJ ')@A#GG4QR $GG4Q  :88*:S:STT--f5::??C**3/*,CD  !DDRXN j77714))#.J%"'"&":":&&)Ed6l^1VH+EE)qT-Nse+TT) %$,,K*+++--$C*,CD  !DDRXN JJOO+ ??DJ...D #9+!GHH~~&=0$ADOO3 CyC=#5(IIs4??3hPT
 )JJDOO 4xd
 /9D{+#s#.3mmC.@
+C'.3kk#.>
+ /;HH'')1J1J1L/
+
 /1D
+OOJ,'1$#s#''
Q7 594M4M25D%%j1 :I  $77` "& 	:D**:6 ==? %%" :It9TD**:6 n.DE#O8--"N$5$5T .  &&z2yy yb=2%rxxj288*AF   zBHH:Q7	C'5@%((EHH5UU!!*-5DT45P&&z2zBHH:Q7	{{"{ 	A::$F @3L44::3?L@H !O		*G M V !
AAK M66   '+&=&=h&G#D#HHMM8!#  
   LL)Q.) $A./D{+HHNN;QNa&++A.IV$&&(Yq\-F-F-H.7mYq\+	!im
 ,-D%%a(&(?@[  @@DJ r\   c                    t         j                  d||d       || j                  vs
J | d       t        j                  |      | j                  |<   y)z.Adds a new symbol to the symbolic environment.zadd_var_to_val %s %sTr,  z already existsN)r   r   r  r   r   )rX   r   r   s      r[   add_var_to_valzShapeEnv.add_var_to_val3  sL    		($	E4??*DtfO,DD* %c 2r\   c                Z    |j                         }| j                  j                  ||      S rU   )r  r}  r;  )rX   r  src_names      r[   _debug_namezShapeEnv._debug_name9  s&    ;;=--11(HEEr\   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 )Nr  z in the specified ranger  r  )	r   r  r  r  r  r^  rk  r  r  )rX   r  r  r  r  rn  c_renders          r[   &_render_range_for_constraint_violationz/ShapeEnv._render_range_for_constraint_violation=  s6    a/044::qttzz5E//1G%%##F+,C>UV   U%6awd4+;+;F+C*DDPP
 O	 5#4a 0 0 89eWEE O "u}awd4+;+;F+C*DEEOxxr\   c                H     | j                   |i |ddid   j                  S )z
        Like produce_guards_verbose, but only returns the non-verbose python guard expressions
        (no verbose guards produced.)
        langs)pythonr   )produce_guards_verboserr  )rX   rY   r)  s      r[   produce_guardszShapeEnv.produce_guardsS  s,    
 +t**DNFN+NqQWWWr\   c                "    | j                         S rU   r  ry  s    r[   r1  zShapeEnv.<lambda>^  s     r\   rq  verbose_python)r   input_contextsequalities_inputs_simplifiedrz  rp  c               '   	OPQRSTUVWXYZ[\]  j                   j                  d        j                  r&t         j                        }
 j                  |
       t              t        |      k(  sJ d d| d       t        j                  t        f}dJd}|$D cg c]  }t        ||      r ||      nd }}nt        |      t              k(  sJ t        t        |            D ]W  \  }\  }}t        ||      r| ||      ||<   $t        |t        t        t        t         f      sJ t        |t"              sWJ  ddlmOmP g Tt+        j,                  t"              ]t+        j,                  t.              \g Rg Wt1        ]| j2                        X	D ]Q  }|d	v rWj5                  X       |d
k(  r'Wj5                  t7        ]| j2                               Et9        d|        	 dK	 	 	 	 	 	 	 	 	 dLRfdYdMOPfdU|rRi Zt        |      D ]  \  }}|Z|j;                         <    dNZfd}|j<                  D ]  \  }} ||       ||      }} j?                  tA        jB                  ||            }|r>tE        |j;                          dt        |t              r|n|jG                   jH                         d|j;                          dt        |t              r|       |jG                   jH                                |jJ                  D ]  \  }}} ||      }t        |t@        jL                        r"| j2                  |   d   j;                         fn ||       jO                  |      f\  }} ||      } j?                  tA        jB                  ||            }|rtE        d|j;                          d |tA        jL                  |             d| d|jG                   jH                         d|jG                   jH                         
       |jP                  D ]#  }]|   jS                   j2                  |          % 	 dK	 	 	 	 	 	 	 dOTXY \]fd}dPT]fd}t        ||      D ]O  \  }} }t        | tT              rddlm+}!  |!|       } t        | tX              sJ |;t        |t        t        f      r
 || |       [t        |t        t         f      r
 || |       {t        ||      sJ t[        |      rddlm.}" t        |t^              sJ | ||j`                  |jb                  fg}#|je                         \  }$}%|$D ]M  }&tg        ||&      }'|jh                  |&   }(|#j5                   |"| |&      |'|(j`                  |(jb                  f       O n| ||j`                  |jb                  fg}#|#D ]  \  }})}*}+tk        |)      rCt        |)jm                               D ]&  \  }}, P|Ojn                  |      }- ||-|,|*|          ( Wt        |)jm                               D ]&  \  }}, P|Ojn                  |      }- ||-|,|*|          ( t        |)jq                               D ]&  \  }}, P|Ojr                  |      }- ||-|,|+|          (  | P|Ojt                        |)jw                                 R 	D %cg c]  }%g  c}%Qty        ] jH                  t/        \j{                                j|                         _?        |sTD ]  \  } S| j;                         }. j                  r@|. j                  v r2 j                  tA        jB                   j                  |.   S             t        St@        jL                        r]j                  S      r| ]S   d   k(  r|r@t        | P      r4Sj                  r( j                   j                  d ||        dS         U|       r j~                  j                  | S       t        QW	      D ]  \  }/}0}|0j                  |        d|0j                  S       }1|dk(  r~ j                  j                  |.      x}2Y|  j2                  |2   d   k7  r|1 d jH                  |2    d}1n6 j                  j                  |2      x}3|1 d|3 }1n|1 d|2 d }1n|1 d!|. d }1|/j5                  |1        t        | P      s| j                  Ojn                  u s|st        Sj                        d"k(  st        t        Sj                              [t        St@        jL                        rS\v r|j                  | ]S   d         sxd# jO                  |        d| j;                          d$ jO                  ]S   d          d]S   d   j;                          d%	}4 Y|j                   jO                  |       |4       t        St@        jL                        r[\v s|j                  | ][   d   S[fd&      r"][   d   }d# jO                  |        d| j;                          d' jO                  |       d|j;                          d( jO                  |        dSjG                  [tA        j                   jO                  |            i       d)}4 Y|j                   jO                  |       |4        t/               VdQQUV	WXY \]f
d*}5||n j                  D ]4  }6 j                  |6j                  d+|6j                  ,      	 - |5|6       6  j                  j                  dg       D ]V  }7 j                  |7j                  d+-      ! j                  |7j                        S j~                  j                  S       X ]j                         D ]1  \  [} j                  j                  [      }8|8% j                  [   }9|sJ g }: ||d         };d.}<|8j                  t@        j                   t         fvrt        Ufd/|D              r9 j~                  j                  tA        j                  [|8j                               |r'|8j                   j                         j                  k7  r1|:j5                  tA        j                  |8j                  [d01             |8j                   d2|; d|9j                   }<|8j                  t@        j                  t        fvrt        Ufd3|D              r9 j~                  j                  tA        j                  [|8j                               |:j5                  tA        j                  [|8j                  d01             |<r9|8j                   d2|; d2|8j                   d|9j                   d$|9j                   	}<n|; d2|8j                   d|9j                   }<|:rQtA        j                  |:d4d0i}=t        QW	      D ]=  \  }/}0}|dk(  r|/j5                  |<       |/j5                  |0j                  |=             ? \[   }>|>D ]  }?t        |?t              s|?j                   j                         z  j                  |8      rA|d   } tA        j                  tA        j                  |8j                  [      tA        j                  [|8j                              SXj                  S      }@ j                  | |?      }Ad5|A d6|@ }4 Y|?j                   jO                  |       |4        t        [t        j                        sd7Xj                  |d          d}1t        QW	      D ]q  \  }/}0}|dk(  r|/j5                  |1 d8       !|d9k(  r|/j5                  |1       8|d
k(  r(|/j5                  d:|0j                  |d          d       et9        d;|        4 Rrg }Bg }Ct/               }DRD ]_  \  }E}}F|Er+d<t        B      d"z    d= F        }G|Bj5                  |G       4d> F        }GCj5                  |G       Dj                  |       a t        C      dkD  r<d?j                  t        D            }Hd@j                  C      }ItE        dA|H dB|I       t        B      dkD  rt         j                  dCt        B             t        dDdi  j                   j                  t        Qd         t        dE ]j                         D              t         j                  j                         dFG      dH        j                  rVddIlumv}J  j                  j                         D ]$  }K|KD ]  }7 j                  |7j                          &  j                  j                         D ]  \  }L}M|Mj                  t@        j                   t         fvr/ j                  tA        j                  Mj                  L             Mj                  t@        j                  t        fvs| j                  tA        j                  LMj                                t        j                         5   J j                   j                        j                          ddd       | j                          g }Nt        QW	      D ]]  \  }/}0}|d
k(  r8t        |0t6              sJ Nj5                  t        |/|0j                               DNj5                  t        |/             _ NS c c}w c c}%w # 1 sw Y   xY w)Ra  
        Generates a list of guards strings which, when evaluated in a context that
        defines tensors for all the sources, returns True or False depending
        on if the guards in the list evaluated to True or not.  Primarily used by Dynamo,
        but this is also helpful for manual testing of guards (see
        evaluate_guards_for_args)

        For convenience in testing, a source is allowed to be a str,
        in which case we will assume it is a LocalSource

        simplified lets you omit duck sizing, equality and 0/1 guards.
        This is useful for testing when you don't care about the boilerplate
        guards, and it may be helpful for user output too (be careful though;
        some equality guards are nontrivial!  It would be nice to get simplified
        output to print them too).  It's private because it's not
        intended for normal use

        Returns guards in python and python with verbose comments (verbose) by
        default.
        rs  zlen(z	) != len(r  c                    t        t        j                  g| j                         z  t        j                  g| j                         z  d g| j                         z  d g| j                         z        S )Nr  )r   r  r  r  r  r  s    r[   _create_no_constraints_contextzGShapeEnv.produce_guards_verbose.<locals>._create_no_constraints_context  s]    +)112QUUW<!+!8!8 9AEEG C"&!%%'!1$(6AEEG#3 r\   Nr   r  ru  cppzUnknown lang: c                :    j                  | |fdf       y )Nc                 "     r           S S rU   rh   )rL  r5  s   r[   r1  zVShapeEnv.produce_guards_verbose.<locals>.record_constraint_violation.<locals>.<lambda>  s    D3%x0@ c r\   )r  )r  r  r5  rL  constraint_violationss     ``r[   record_constraint_violationzDShapeEnv.produce_guards_verbose.<locals>.record_constraint_violation  s     "((J(QRr\   c                P    t        |       xr | j                  j                  u S rU   )r   propr  )r  r  r  s    r[   is_dimz/ShapeEnv.produce_guards_verbose.<locals>.is_dim  s*    3 45 4HH 3 33r\   c                d   | j                   j                               }| j                  J |j                  | j                     }t	        |t
        j                        r|j                  j                  S t        |      t        u sJ dt        |              t        j                  |      S )NzExpected int, got )r  r  r  r	  r   r   r   r   r   r   r   r   r   )tensor_dim_srcr  symintplaceholderssource_indexs      r[   get_expressionz7ShapeEnv.produce_guards_verbose.<locals>.get_expression  s    #L1D1D1I1I1K$LM%))555N$6$67fell3!;;+++<3.S2DT&\N0SS. ==00r\   r  z is not equal to zExpected input z to be equal to z, where z
, but got 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                  |        |,t	        |t              s|   j                  |       nd}t	        |t              rW|j                   D ci c]  }|j"                  j%                  |d       ! }}t'        d |j)                         D              r0d}n-t	        |t              r|j*                  rt-        |      }|dvrd}|rm|J dfd}j/                  | |      }	d|	 dj1                  |        d	}
 |j2                  j1                  |       |
t5        j6                  ||      
       j                  | |f       y t        j8                  |      }j                  | |f       d}t	        |t              r8||j:                  j<                  cxk(  r|j:                  j>                  k(  sn d}nt	        |t              r|dvrd}|rU|J j/                  | |      }	d|	 dj1                  |        d| d}
 |j2                  j1                  |       |
       y y c c}w )Nztrack_symint %s %s %sFc              3  $   K   | ]  }|d u  
 y wrU   rh   )r  r  s     r[   r"  zHShapeEnv.produce_guards_verbose.<locals>.track_symint.<locals>.<genexpr>o  s     EbrTzEr  TrU  c                0    j                  |       }| dS r  )rO  )r  sexpr
py_printers     r[   rL  zCShapeEnv.produce_guards_verbose.<locals>.track_symint.<locals>.hint|  s    $.$6$6q$9E&+WA;.r\   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   r]   r   ) r   r   r#   r  r   r   r  r   maybe_as_intr   r   rR  r  r  r  r  ru   rS  r;  r  r.  r  r   rn  rk  r  r   r  r   r  r  r  )r  r   
constraintr  constraint_violatedr  sym_vrsr6  rL  var_with_ranger5  input_guardsr  r  rX   symbol_to_constraintsrB  s              r[   track_symintz5ShapeEnv.produce_guards_verbose.<locals>.track_symintW  s    II-z&++/FZX!#v.+c2BBB#v&388+@+@+B+Nhh++-#v&HHMMa.$Q'..v6!-j"$;7 .a044Z@*/'!*.DE HI~~#BCAt0044Q==# # EGNN4DEE26/#J0GH;; #AA  !6: 3*)555/ *.)T)T"J* 10@@S#//788UW  4&00 ,,V4!*!2!24!;	 ##VQK0MM#&##VQK0&+#j*@AZ]]00GJMM4G4GG.2+
,CD &(.2+&%111%)%P%P
&N -^,<<O++F344TUXTYY[]  0",,d.>.>v.F 'c#s   -$Lc                <   t         j                  dt        | j                        |       t	        |t
              rt        |      sJ t	        |t
              r4|j                  j                         |j                  j                         }t	        |t
              rX|j                  j                  }t	        |t        j                        r|   j                  |        j                  | |f       y t        j                  |      }j                  | |f       y )Nztrack_symfloat %s %s)r   r   r#   r  r   r   r  r   maybe_as_floatr   r   rR  r  r  )r  r   r  r  rB  s      r[   track_symfloatz7ShapeEnv.produce_guards_verbose.<locals>.track_symfloat  s    II,j.EsK!#x0K4DDD#x(SXX-D-D-F-Rhh--/#x(HHMMa.$Q'..v6##VQK0KK$##VQK0r\   LocalSource)
AttrSourcezSkipping guard %sr  rv  zN  # duck sizing added this equality because these variables had the same size zY (to avoid this specialization, set torch.fx.experimental._config.use_duck_shape = False)  # z  # (unknown var z, please file a bug)z  # (unknown source r   zThe values of  and z must always be equal.c                *    j                  | i      S rU   )r  )r  r   rG  s    r[   r1  z1ShapeEnv.produce_guards_verbose.<locals>.<lambda>\  s    dmmVQK&@ r\   z) must always be related to the values of z by r  c                  
 j                  | j                        }|v ry j                  |       	 d}t        fd|j                  D              r)j
                  J j
                  j                  |      }t              D ]>  \  }}}|j                  |      }|dk(  r| d| j                   }|j                  |       @ j                  |       |st        |j                        dk(  rt        t        |j                              }|   d   }|   }	|	D ]~  }
t        |
t              rNj!                  ||
      }d| dj                  |       d	} |
j"                  j%                  |      |       at        |
t&              rrt)        d
|
        y y y # t*        $ r( j,                  j/                  d| j                          w xY w)NFc              3  B   K   | ]  }|   D ]  } |         y wrU   rh   )r  r  r  r  rB  s      r[   r"  zGShapeEnv.produce_guards_verbose.<locals>.issue_guard.<locals>.<genexpr>~  s7      "21"5  6N"s   rv  r  r   r   r   satisfy the generated guard r  zunrecognized constraint zFailing guard allocated at %s)r  r   r  r  ru   rj  r%  rO  r<  r  r  r#  r  r  r   r  rn  r  rk  r  r  rC  r   r  )guardr   
is_trivialrr  printerlang
guard_exprrG  r  constraintsr  r  r5  	all_exprsr  issuedrp  printersr  r  rX   r  rB  s                r[   issue_guardz4ShapeEnv.produce_guards_verbose.<locals>.issue_guards  s   ==,D v~JJt-"
 !.. 
  //;;;!%!5!5!9!9$!?J,/	8U,K -(E7D!(!6J//(2|4

|%D
LL,	- %%d+ "c$*;*;&<&A!$t'8'8"9:F-f5a8F"7"?K( Q%a)?@ $ K KFTU V + #5^4D E??I?Q?QRV?W>XXY![   8 !T-=-=f-Es (+BC
 !"03KA31O"PP'Q	 'Bz0    !@%**Ms   E1F( (1Grh   rZ  r	  )rZ  r  c              3  .   K   | ]  } |        y wrU   rh   r  r  r  s     r[   r"  z2ShapeEnv.produce_guards_verbose.<locals>.<genexpr>       <&vf~<   Fr  r  c              3  .   K   | ]  } |        y wrU   rh   r  s     r[   r"  z2ShapeEnv.produce_guards_verbose.<locals>.<genexpr>  r  r  r  r  r  znot math.isnan(zM  # implicit guard for float input due to NaN specialization in the frameworkrq  z~std::isnan(zUnimplemented for lang: z  . z  - r  r  zConstraints violated (r  z$%s Warning only constraints violateddynamicc              3  &   K   | ]	  }|sd   ywr   Nrh   )r  r?  s     r[   r"  z2ShapeEnv.produce_guards_verbose.<locals>.<genexpr>0  s     #N!AA#Ns   T)reverse)
num_guardsru   symbol_guard_counts)PopulateValidator)r  rJ   r]   r   rU   )
r  r   r  r   r5  r   rL  zOptional[Callable[[], str]]r]   r^   )r  r   r]   zTypeGuard[TensorPropertySource])r  r    r]   r   )r  r    r   Union[SymInt, int]r  DimConstraintr]   r^   )r  r    r   Union[float, SymFloat]r]   r^   )r  r   r]   r^   )r   rJ  rO  r+   rQ  r  r#  r   rJ   r)   r   r  r%  r   r   r   r  r  r  r  r  rk  r   r  rW  r  r  rd  r  r  r  evaluate_exprr   rP  r   r  r  r  rR  rk  r  extendr   r  r    r1   r  r   r  r  r  r  r  r&   re  r  rf  r  r  rg  r  r  r}  rj  rL  rg  r  r;  r  r   r  rJ  rO  r_  ra  r  ru   r  r  r  r  r  r0  r   rB  r   r	  rg  r  r  r9  rS  r]  r  r`  r;   r  r  r^  r  r  ru  r  r  rT  rn  rB   rC   r\  r  r  r'   rS  rl  sumr.  rm  rK  r  fx_tracebackpreserve_node_metar  rr  runr  rt  rp  )^rX   r  rH  rC  r   rw  rx  ry  rz  rp  r<  
Tensorliker|  r  r6  contextr  r  r  r  r  expr1r  concrete_valsrcEqr  r  r  expr2_phantom_symbolr  r  r  r  r  sources_tensors_constraintsr%  r&  r'  inner_tinner_contextcurr_tconstraint_sizeconstraint_stridessproperty_sourcer  rr  r  r]  s0r<  r5  r  r  r  r  vr_slocboundsrfverbose_exprboundr  r  r  r  	warn_msgs
error_msgsr&  r  msg_cbstr_msgdebug_names_strerrr  r  r  r  helpersr  r  r  r  r   r  r  r  r  r  r  r  rG  r  rB  s^   ``       `                                                                     @@@@@@@@@@@@@@@r[   rr  zShapeEnv.produce_guards_verboseZ  s   H 	&' %%/<IY'< C%
 
 	4,y	3	4 
 llN3
	 ! & 6@:5N.q1TXXN 
 ~&#l*;;;;#,S~-N#O 9<Awa,,J1,Mq)%a&#x)GHHH)'48889F 	N =H=T=T>

 ##C( 	 LN-/,j$*=*=

  
	CD33
+)(*d6I6I *N4&*ABB
	C  15				 	 .		
 		 L#G, -3+,SXXZ(-1 0<< 
d-d3^D5Iu  $11%((5%2HI#299;-sJuc4J5PUP^P^_c_n_nPo*p+99;-sJuc4J5*pr  QVP^P^_c_n_nPo*pr  $5#G#G tR&u- "$5 4..t4Q7<<>?(.0@0@0FG "z
 E  $11%((5&2IJ#2)%**,7Gell:678 9!!+Ct0O/P Q##(>>$//#B"CE * #4"C"C  077''7$ RVQ	Q	!3Q	ANQ	Q	 Q	f	1  #&lG^"L E	Avw&#&<$V,ff---y!fc]+VQ'A%01vq)a,,,,Q/;!'+BCCC Q 8 8':T:TUS+ //1q! 
D%a.G$+$:$:4$@M/66&vt4#)::)<<	
 Q 8 8':T:TU/+ - ! (!*6;;=!9 N2*>!4!4a+ %_b/!:LM	N "+6;;=!9 N2*>!4!4a+ %_b/!:LM	N
 "+6==?!; P2*>!6!6+ %_b:KA:NO	P
 !,S.2O2OP--//WE	V 38%8Qb%8	-OO%**,-**	 
  , Y ++-77$"7"77--!HHT%:%:7%CTJ tU\\2(,,T2"24"8";;
 !Z8L%M~~/Jv4F3GtD61R !&>((55fdC,/	8U,K &(E7D$11&9:$wt?T>UVC//"&"4"4"8"8"AABN%)<)<R)@)CC'*e ,CCG??SUCVBW X% !$
 +/*A*A*E*Eb*I"I$!V),T$&8),->rdBV&W%(E)=gYFZ"[CLL%#&( v';<~':'::)D--.!3!$t'8'8"9:F"46 $99 1 : :"$4T$:1$=!
 -T-=-=f-E,Fc&++-X]#//0@0Fq0IJK3O_`dOefgOhOmOmOoNp q44 
 4-779I9I&9QSV
 'tU\\:"&;; 1 < <",V4Q7@! /v6q9,T-=-=f-E,Fc&++- Y--1-=-=c-B,C3sxxzlRV#//78DMM6SXS`S`aeaqaqruavSwJx<y;zz{} 
 4-779I9I&9QSVoYF 6	 6	v  &1Vt{{ 	E++JJr%:N:N ,  
 	 //33D"= 	+B**2772*>J==)D  $$T*		+  0557 K	UOFG!!%%f-Ay,,V4GN7FGAJ'BLwwy6'22<G<<((,,UXXfagg-FG #agg1J1J1L1R1R&RMM%((177FU"KL"#''$rd$w}}oFwwuxx00<G<<((,,UXXfagg-FGehhvqwwGH&'ggYd2$d177)4V[\c\i\i[j#kL&(TaggYd7==/#JL		6:E:,/	8U,K =(E7D//\2W__U%;<	= 4F;$ A!!%;< !"t'@'@'B BLLQO%,QZF#(99 %& 9588FAGG;T$D *4););D)AJ $ K KFTU V + %7~6FFcdnco"pC7 ! $ 0 0 8 #0 fdjj1'
(?(?
(K'LAN,/	8U,K 
U(E7D//"e#pq )S)|G4H4HQR4T3UUV%WX14LTF2STT
UCK	UZ !#%I$&J%K1F 0-	:v "3y>A#5"6b
CG$$W- $VXJ/G%%g.OOJ/0 :""&))F;,?"@ii
+.,_,= >Ne 
 Y!#		@#i.Q
..
,,
 ")A,/ ##N/?/F/F/H#N N (.--446(
	
  //I
 44;;= 3 3B))"''233  ,,224 CR88UXXIw#77))%((288S*AB88EHHf#55))%((3*AB	C 002 D!$**dnn=AACD >,,.,.$'	8U$C 	: E7Du}!'+@AAA4UG<T<TUV1%89	: }N &9R
D Ds   %AM9&	AM>K,ANNANr   rz  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  r  r  N)r  r  r  r#  rs  r  )	rX   r  r   rz  r  r6  	arg_namesr  produced_guardss	            r[   produce_guards_expressionz"ShapeEnv.produce_guards_expression^  s|     	5&+C,=&>?qW?	?--%./[^/'	 . 
 <<00 @ 0s
   A(A-
c                    | j                   j                         D ci c]  \  }}t        |      | }}}t        |t        |      S c c}}w )z?
        To be used by compile_fx to evaluate symexprs
        )r  r9  r   evalrt   rX   coder  r   rY   s        r[   evaluate_symexprzShapeEnv.evaluate_symexprw  sE     +///*?*?*AB3ABBD,-- Cs   Ac                    | j                   j                         D ci c]5  \  }}t        |      t        t	        || t
        t        |      d            7 }}}t        |t        |      S c c}}w )zB
        To be used by compile_fx to deserialize symexprs
        Nr  )r  r9  r   r   r.   r   r  rt   r  s        r[   deserialize_symexprzShapeEnv.deserialize_symexpr~  sg     ////1
3 FF71dCS4HII
 
 D,--	
s   :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#  r  rt   r  r%  )rX   r  rY   r6  r  s        r[   evaluate_guards_expressionz#ShapeEnv.evaluate_guards_expression  sK    
 ',CI&67qW7	7D,d3y$3G.H(IJJ 8s   Ary  c               R    | j                  ||      }|r| j                  ||      S y)zRGenerate guards for a graph's placeholder values and evaluate the guards with argsry  T)r  r  )rX   r  rY   rz  r  s        r[   r|  z!ShapeEnv.evaluate_guards_for_args  s2     --l--X224>>r\   c                F   D ch c]G  }t        |j                  j                  t        j                        s2|j                  j                  I c}| j
                  D cg c]-  }t        fd|j                  j                  D              s,|/ }}|S c c}w c c}w )z
        Get a list of guards, but pruned so it only provides guards that
        reference symints from the passed in input
        c              3  &   K   | ]  }|v  
 y wrU   rh   )r  r  symintss     r[   r"  z-ShapeEnv.get_pruned_guards.<locals>.<genexpr>  s     )T1!w,)Ts   )r   r   r   r   rR  r   r$  ru   )rX   r  r  r  r   s    `   r[   get_pruned_guardszShapeEnv.get_pruned_guards  s     ")
Jqvv{{ELL,QAFFKK
 {{
c)T@S@S)T&TA
 
 

s   3BB#-BBc                   i dfd}t        ||      D ]  \  }}|	t        |t              r
 |||       #t        |t        j                        sJ t        |j                               D ]  \  }} ||j                  |      |        t        |j                               D ]  \  }} ||j                  |      |         ||j                         |j                                 S )a5  
        Given a paired list of placeholders (fake tensors with
        symbolic sizes) and concrete arguments (regular tensors
        with real sizes), returns a dictionary mapping each
        symbol to its real value.  So for example, if you
        have a placeholder with size (s0, s1), binding
        (2, 4) to it will give you {s0: 2, s1: 4}.  This is
        not guaranteed to bind ALL symbols in the ShapeEnv;
        we can't bind a symbol if it doesn't occur in any placeholder,
        and symbols that already have replacements won't get bindings.

        This is a little duplicative with evaluate_guards but
        it's different enough that it seemed cleanest to make
        another copy.  This assumes the guards are already checked,
        though if it's cheap we'll check for shenanigans
        c                x   t        |t              rt        | t              sJ |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 )Nr,  )r   r   r   r   r   r   rR  )r  r   r  r=  s      r[   bind_symintz*ShapeEnv.bind_symbols.<locals>.bind_symint  s    #v&!#s+++HHMMa.H}'{c1Lhqk]$se3LL1&)  2  ELL1rX~'|t3P!~T3$5PP3(+t!	 2 'r\   )r  r   r   r   r]   r^   )	r%  r   r   r   rJ   r  re  rf  rg  )	rX   r  rY   r  r  r  r6  r  r=  s	           @r[   r  zShapeEnv.bind_symbols  s    & -/	,  ,- 	BFAsy!V$C#a...!!&&(+ ,1CHHQK+,!!((*- .1CJJqM1-.**,a.>.>.@A	B r\   c                    | j                   D cg c]F  }| j                  |j                  d|j                        	 | j	                  |j                        H c}S c c}w )zSReturns a list of guard expressions that aren't statically known (i.e. not trivial)rh   r  )r   rB  r   r	  r  )rX   r  s     r[   get_nontrivial_guardszShapeEnv.get_nontrivial_guards  sc     
**

2e6J6J +   MM%**%
 	
 
s   AAc                L    dj                  fd| j                  D              S )zQFormat this shape env's guard expressions with optional traceback info if verboser  c              3  t   K   | ]/  }d |j                    rdt        |j                        z   nd  1 yw)z - r  r  N)r   r   r<  )r  r  verboses     r[   r"  z)ShapeEnv.format_guards.<locals>.<genexpr>  s:      
 %**wcC

O3BGH
s   58)r  r   )rX   r  s    `r[   format_guardszShapeEnv.format_guards  s'     yy 

 
 	
r\   c                   |j                   D ci c]  }|| j                  j                  |d      ! }}|r;| j                  |j	                         z  D ]  }||   	t        dt              ||<    t        ||      S c c}w )zPGiven a sympy expression, computes a ValueRanges bound for what values it can beNrD  )ru   rS  r;  rc  r  rG   r;   rD   )rX   r   r	  r  rS  s        r[   rD   zShapeEnv.bound_sympy  s    
 DHCTCTUa4,,00D99UU ^^l&7&7&99 =?. '2!V&<LO= 4.. Vs   $A>c                &    |"d  j                   j                         D        }n fd|D        }d  j                  D        }t        j                  ||      }|r fd|D        }t        t        j                  |      j                               S )z
        Given the symbols in an expression, it returns all the runtime asserts that have those symbols
        concatenated with all the guards.
        If symbols is None, it returns all the runtime asserts (and all the guards)
        c              3  B   K   | ]  }|D ]  }|j                      y wrU   r  )r  rsr  s      r[   r"  z&ShapeEnv.get_axioms.<locals>.<genexpr>  s,      QSLMr  c              3     K   | ]?  }|j                   vr/j                  j                  |d       D ]  }|j                    A yw)rh   N)r  rg  r;  r   )r  r  r  rX   s      r[   r"  z&ShapeEnv.get_axioms.<locals>.<genexpr>  sQ      DOO+66::1bA	  s   AAc              3  4   K   | ]  }|j                     y wrU   r  )r  r  s     r[   r"  z&ShapeEnv.get_axioms.<locals>.<genexpr>  s     )FQ!&&)Fr  c              3  f   K   | ](  }t        |j                  j                               * y wrU   )rr   r  r  )r  r  rX   s     r[   r"  z&ShapeEnv.get_axioms.<locals>.<genexpr>  s)      HI&qzz$//'BCs   .1)	rg  r.  r   r  chainrN  r  fromkeysr  )rX   r  compute_hintruntime_assertsr   rZ  s   `     r[   
get_axiomszShapeEnv.get_axioms  s     ?!%!>!>!E!E!GO O *G$++)F)2)QMSF T]]6*//122r\   c                   i dfd} ||       t        |t        j                        rf |t        j                  |j                  |j
                  d              |t        j                  |j                  |j
                  d             n/t        |t        j                        r |t        j                  |j                  |j
                  d              |t        j                  |j                  |j
                  d             |j                  j                  r|j
                  j                  r |t        j                  |j                  |j
                  dz
  d             nOt        |t        j                        r5 |t        j                  |j                  |j
                  dz   d             t        j                               S )zGGiven a expression, it returns a list of predicates that follow from itc                   t        |       } t        | t        j                  t        j                  f      rt        | t        j                        rt        j                  nt        j                  }t        j
                   t        |       | j                  | j                  d      <   t        j
                   t        |       | j                  | j                  d      <   t        j                   || j                  | j                  d      <   t        j                   || j                  | j                  d      <   y t        j
                  | <   t        j                  t        t        j                  |             <   y )NFr  )rr   r   r   rP  rx  r  r   rQ  rU  r  rw  )r   r  equivs     r[   add_exprz+ShapeEnv.get_implications.<locals>.add_expr(  s    )$/D$588 45 (2$'A588uxxHM

jd4j488eDEHM

jd4j488eDEFKkkhtxxEBCFKkkhtxxEBC $jjd BG,UYYt_=>r\   Fr  r   r   r   r]   r^   )r   r   rP  r  rQ  rU  r  r  rx  
is_integerrN  r9  )rX   r  r  r  s      @r[   get_implicationszShapeEnv.get_implications!  s%   
 FH	M& 	a"UXXaeeQUUU;<UXXaeeQUUU;<588$UXXaeeQUUU;<UXXaeeQUUU;<uuAEE$4$4!%%UCD588$UXXaeeQUUQY?@U[[]##r\   )r  r  r	  rZ  rS  c          
         |r|rJ  j                  ||      }|r4|j                   j                        j                   j                        }t	        |      }d fd}| | j
                          j
                  }noi }|D ]`  }	|	j                  j                  |j                        s)|j                  t         j                   j                  |	                         b  ||       |j                  |      }|j                  }
|
s|j                  s|j                  r|S | j                  nt        |      t         fdt        |
t               D              }t#        ||||      }|S )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 and unbacked SymInts,
        e.g., if s0 happens to be 3 this run, compute_hint will subsitute s0 with 3.
        c                    j                   sy d_         i }| j                         D ]=  \  }}|j                  t              s|j	                  j                  |      |i       ? | j	                  |       y r  )ro  r9  r  r5   r  r  )rZ  	new_itemsr>  r?  rX   s       r[   resimplify_floor_divz=ShapeEnv._maybe_evaluate_static.<locals>.resimplify_floor_divk  sl    4405D-I <1 55?$$dmmA&6%:;< MM)$r\   c              3     K   | ]F  }t        |j                  |      j                  j                  |      |j                  v        H y wrU   )r  r;  r  rc  )r  r  rX   
var_rangess     r[   r"  z2ShapeEnv._maybe_evaluate_static.<locals>.<genexpr>  sM      
  q!##A&T^^#	
s   AAr  )rZ  zdict[sympy.Expr, sympy.Expr]r]   r^   )r  r  r  r[  rr   rZ  ru   rT  r  r  r  r  
is_BooleanrS  rN  r  r   r  )rX   r   r  r  r	  rZ  rS  r  substr  r3  r  r  r  s   `            @r[   rB  zShapeEnv._maybe_evaluate_staticJ  sT   2  v--}}T>2==1::4;S;STD%d+	%  > -KKEE P>>**4+<+<=LLd&;&;DMM!<L&M!NOP !'}}U# t~~K**Jl+J 
 BC(
 
 *+}n
 r\   c                    i }|j                   D ]*  }| j                  |      }|j                  r||k7  s&|||<   , |rt        |j	                  |            S |S )z@Apply symbol replacements to any symbols in the given expression)ru   r  r  r  r  )rX   r   r`  r  r  s        r[   r  zShapeEnv.replace  sa     "" 	$A

1A ;;!q&"#Q	$ t}}\:;;Kr\   c                    t               }| j                  D ]1  }| j                  |      }|j                  r!|j	                  |       3 || _        | j                          y rU   )r  rb  r  r  r  r  )rX   new_divisibler>  r]  s       r[   _update_divisiblezShapeEnv._update_divisible  sS     	%A,,q/C==!!!$	%
 '$$&r\   c                
    t        |      } j                  |      }|r|j                  t              ri }|j	                  t              D ]  }|j
                  \  }}|dk(  s|dk(  r||}}|dk(  s|dk(  s+t        |t              s<t        |j                        dk(  sU|j                  t        |j	                               k(  s|t         fd|j                  D              s|||<    |r|j                  |      }t        |      }|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|||<    |r|j                  |      }t        |      }|j                  t              rxi }|j	                  t"        j$                        }|j	                  t"        j&                        j)                  |j	                  t"        j*                              }|j	                  t              D ]H  }|j
                  \  }}	 j                  t        ||	             j                   v s:t-        ||	      ||<   J |r|j                  |      }t        |      }|j	                  t"        j$                        }|j	                  t"        j&                        j)                  |j	                  t"        j*                              }|j/                  |      r|j/                  |      r|}|S )zAUse known constraints and replacements to simplify the given exprr   r   rD  c              3  :   K   | ]  }|j                   v   y wrU   )rc  )r  r  rX   s     r[   r"  z$ShapeEnv.simplify.<locals>.<genexpr>  s     LT^^ 3Ls   )r  r  r  r8   r  rY   r   rN   r#  ru   r  r$  r  r5   r  r9   rb  r   PowRationalr  r   r4   rT  )rX   r   r	  max_replacementsatomr  r  div_replacementsr  r   base1divisor1pows	rationalsfdr  new_powsnew_rationalss   `                 r[   r  zShapeEnv.simplify  s    4 ||D!dhhsm!

3 3yy16Q!VaqA6Q!V"1c*/14NNc!'')n<LQ^^LL12(.3  }}%56"4( 88H""$!

8, 	: $		ggx0&-llOE8Sw%78DNNJ EM LLUH)=>$..P19(.	:  }}%56"4(88H!::eii(D

5>>2==djj>WXIjj* C "g<<D' 23t~~E+3D'+B$R(C  ==)9:&x0#>>%))4 (u~~ > I INN5==1! $$T*}/E/Ei/P#Dr\   r  
allow_nonec                 
 t              j                  | j                        }|j                  sddlm} t        ||      ry| j                  |d      }||S |ry| j                  r|j                  | j                        }|j                  | j                  j                         D ci c]  \  }}|t        |d       c}}      }	|j                  sC|	j                  s7||	k(  rt        j                  d|       |S t        j                  d||	       nt        j                  d	||	       | j                  r}|j                  | j                        

j                  sVt        j                  d

       t!        d
fd       | j#                  t%        j&                  |
      d| d
        
S | j)                  |      |S c c}}w )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)
        r   r>   NT)r  rD  zoblivious_size hit %s -> %sz3oblivious_size counterfactual failed %s -> %s != %sz1oblivious_size miss %s -> %s (counterfactual: %s)z*propagate_real_tensors size_hint(%s) -> %spropagate_real_tensorsc                     t               t              t        j                  t        j                  d      j                               dS Nr   r@  )r   rY  r6  r   r$   rW  rH   rC  rY  )r   unsound_exprs   r[   r1  z$ShapeEnv.size_hint.<locals>.<lambda>9  s>    $(J&*<&8%/%>%> 1 9 9q A I I K&- r\   r6  propagate_real_tensors: r  )r  r  r  r   torch.utils._sympy.singleton_intr?   r   rB  r\  r9  rZ  ru   r   rJ  r[  r  r%   defer_runtime_assertr   rP  _make_data_dependent_error)rX   r   r-  result_exprr?   r  correct_hintr>  r?  counterfactual_hintr3  s    `        @r[   	size_hintzShapeEnv.size_hint   s    "$'00A$$E+|4++Kd+KA}((*33D4M4MN&1&:&:.2.G.G.M.M.OPdaQAq	\P'# %11/<<#'::!>lS++Q (/	 HHK$+	 ''*33D4L4LM#00KKDdL %0%	 --l;2;-tL>R ('11+tDD_ Qs   0G
c                    t        |      j                  | j                        }|j                  xs | j	                  |      d uS rU   )r  r  r  r  rB  )rX   r   r8  s      r[   r  zShapeEnv.has_hintK  sB    !$'00A!! D**;7tC	
r\   size_oblivious_resultexpr_sym_node_idc               ^    g }j                   D ]k  }dj                   j                  |   j                               } j                  j                  d||       | j                  v s[|j                  |       m d}|d| d} j                  d      \  }	}
j                  rd}nd}| d d	 d
dj                  t        t        |            xs d d| d|	 ddj                  t        t        j                                d|
z   }t        d fd       t        |      S )Nr  z-Data dependent variable '%s' allocated at:
%szNATTENTION: guard_size_oblivious would fix the error, evaluating expression to zb.
Maybe you need to add guard_size_oblivious to framework code, see doc below for more guidance.

TzDCould not extract specialized integer from data-dependent expressionz,Could not guard on data-dependent expressionr  z (unhinted: z).  (Size-like symbols: r  nonez)

zCaused by: z
For more information, run with TORCH_LOGS="dynamic"
For extended logs when we create symbols, also add TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL="r+  z"
If you suspect the guard was triggered from C++, add TORCHDYNAMO_EXTENDED_DEBUG_CPP=1
For more debugging help, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit?usp=sharing
guard_on_data_dependent_errorc                     t               t              j                  t        j                  t	        j
                  d      j                               dS )Nr   r@  )r   unhinted_exprexpr_idr6  )r   r  r$   rW  rH   rC  rY  )r   rX   rD  s   r[   r1  z5ShapeEnv._make_data_dependent_error.<locals>.<lambda>  sG    T
!%m!411#22%--15==?	! r\   r6  )ru   r  r^  formatr   r   rc  r  r9  r  r  r   r"   rQ   )rX   r   rD  r>  r?  size_like_symbolsr  
stacktracesize_oblivious_result_msgr<  r=  descr5  s   ```          r[   r7  z#ShapeEnv._make_data_dependent_errorS  so    "" 	,A!2!21!5!<!<!>?JHHNN@!Z DNN"!((+	, %'! ,`av`w xu u & #'"9"9$"???V  BDfAdV< 7##'99S6G-H#I#SV"TTY()$  : ;>((3sDL]L]C^:_9` aq	q  
  	  	+
	
 +455r\   rQ  c               n   |j                   |j                  }}|dk  r|| j                  v rt        |d      }|| j                  vrZ| j
                  j                  d||       || j                  |<   || j                         }t        ||      }|| j                  |<   n| j                  |   }||z  }	|	|k7  r|| j                         }t        ||      }|	j                   |j                   k7  r|j                   | j                  |   _         |	j                  |j                  k7  r|j                  | j                  |   _        |	| j                  |<   | j
                  j                  d||	       | j                  j                  |      x}
(| j                  |   }|
|vr|s|
|v sJ |
 d|        y y y y )NrD  z"_update_var_to_range %s = %s (new)z%_update_var_to_range %s = %s (update)z not in )r  r  rc  rG   rS  r   r   rF  r   r]  r  r;  )rX   rG  r  r  rR  r  r  r<  r0  r/  r?  r  s               r[   r_  zShapeEnv._update_var_to_range  s    xxu 194>>1UA&B ***HHNN?L(*Df%~~')$5-4D""6*##F+C(Ccz?>>+D-dD9G99		);B==D**62899		);B==D**628,/!!&)FPST$$V,,A9!!&)Az %64aS#446 %	  :r\   c                `     j                   j                  d      k(  ryj                  v ryt        t        j
                        sJ  j                  rt              syd} j                  v rq j                     } j                        } j                  |       |j                  |      st        j                        dk(  rt        t        j                              }t        t	        j                         |d      }| j"                  j%                  d||        j                  |d         }t'        t)        |j*                        t-        |j.                              }	 j                  ||	 j0                             j                        }|j                  |      sJ d|d|        j2                  v r6t        t        j
                        r j2                  j5                         nCt        t        j
                        r) j2                  v r j2                  j5                         |j                  |      s! j"                  j%                  d||       y j2                  v rX j                  d	
      }
 j                  d	
      }|
j                  |      s! j"                  j%                  d|
|       yt        t        j6                  t        j8                  f      rt;        j<                         t?        d fd       t@        jB                  rX j"                  jE                  d jF                     d   jI                                 j"                  j%                  dd	       t"        jK                  d|        j                   <    jL                  vr jO                          jL                  <    jQ                           jS                  t	        j                   d             y)zw
        Adds or updates a replacement for a symbol.
        Use this instead of `self.replacements[a] = tgt`.
        Nr   Ffloordiv_inequalityz2set_replacement: solve for %s in %s == %s gives %sz
tgt_bound=z not a subset of src_bound=z:skipped set_replacement %s = %s (%s) [%s not subset of %s]Tr	  zVskipped set_replacement %s = %s (%s) [%s not subset of %s (size-oblivious conditions)]symbolic_shape_specializationc            	     L   t              j                  j                  g       D  cg c]  } | j                          c} t              t	        j
                  t        j                  d      j                               rt	        j
                        dS d dS c c} w )Nr   r@  )rG  rH  r  reasonr6  r2  )	r   r  r;  r  r$   rW  rH   rC  rY  )r  r  r5  rX   tgtuser_tbs    r[   r1  z+ShapeEnv._set_replacement.<locals>.<lambda>G  s    "1g262E2E2I2I!R2PQQQ!#Y!'66)11q9AAC ?F
11':%  LP% Qs   B!r6  zSpecializing %s to %sr   SPECIALIZATIONr,  zset_replacement %s = %s (%s) %sr  )*r`  r;  ru   r   r   rR  r7  r  rS  rD   r_  rT  r#  r  r  r@   rP  r   r   rG   r3   r  r6   r  r]  rc  r  r   r  r!   rX  r%   r/  print_specializationsr  r  r  rJ  ra  rF  r  r  )rX   r  rS  r5  	tgt_bound	src_boundr  r  rat_b_boundb_boundtgt_bound_sosrc_bound_sorT  s   ````        @r[   r  zShapeEnv._set_replacement  s   
 $##''400    !U\\*** 88-c2 	!!!))!,I ((-I%%a3 %%i0S9I9I5Ja5Oc../0ehhq#.uM=HHNNL #'"2"21Q4"8K)!+"3"34jARAR6SG --a$:P:PQR:ST $ 0 0 5I$--! D$)%AylCD , DNN"z#u||'D""3'C.3$..3H""1% %%i0P dnn$#//D/I#//$/G#,,\:HHNNL$$ cEMM5;;78 %224G/  ++  +T-@-@-CA-F-K-K-Ms /DA2AsCK"! D+++)-)9D##A&$$& 	ehhq#>?r\   c                Z    | j                   j                  |       | j                          y rU   )rb  r  r  r;  s     r[   _add_divisiblezShapeEnv._add_divisibleg  s     4 $$&r\   c                &   || j                   vr|S | j                   |   }|j                  D ci c]  }|| j                  |       }}| j                   |   j                  |      \  }}|r| j	                  ||d       | 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
        find)r`  ru   r  	_xreplacer  )rX   r  r]  r  cur_replacereplacedchangeds          r[   r  zShapeEnv._findk  s     D%%%H"141A1ABAq$**Q-'BB --a0::;G'!!!Xv6  ##	 Cs   Bc           	         t        |t        j                        sJ t        |t        j                        ryt	        |j
                        }t        |      dkD  s
J d|        t        |      dkD  ryd fd}t        ||d      }|j                  }|j                  } j                  |       t        |t        j                        sy|j                  t              s8	 |j                  t              j!                  |j                  t                    }t        |      dkD  rt#        d |D              rt$        dd	} |||      r# j'                  | j)                  |      d
       n |||      r# j'                  | j)                  |      d       n~t+        ||d   d      }|kt-        d t        j.                  |d         D              rC j)                  |d         }	t        t1        |	            dk(  }
|
r j'                  |d   |	d       |j                  t              rt3        t5        |j                  t                          }	 t+        ||d      }||d   dk(  r j7                  |       |j8                  \  }}t        |t        j:                        r|t        |t        j<                        rat        |j8                        dk(  rH|j8                  \  }}t        |t        j:                        rt        |t        j>                        r jA                  |      r|t        jB                  ||      z  } jE                         jF                  jH                  } jK                  |tM        jN                   jP                  |   tS        jT                  |                   | jV                  v r" jY                  | jV                  |   |z         | jZ                  v r jZ                  j]                  |        j'                  |||z  d       yy# t$        $ r Y w xY w# t$        $ r Y yw xY w)z
        The relational guard is guarded to be true.  Use this information to
        simplify shapes (i.e. a == b or a % 5 == 0)
        Nr   z3The expression should not be static by this point: r  c                   | j                   v xr t        d j                   |    D              }j                  | d      }|t        j                  }nRt        | t        j                        r(t        |t        j                        sJ t        |      }nt        j                  }| j                  }|rd||fS d||fS )Nc              3  <   K   | ]  }|j                           y wrU   )rc  r  s     r[   r"  zHShapeEnv._maybe_guard_rel.<locals>._smart_symbol_sort.<locals>.<genexpr>  s      J%& Js   Tr,  r   r   )r  r$  r;  r   r   rB   rC   r  r   r   r  r   r  )r  has_only_ephemeral_sources	hint_sizere  r  rX   s        r[   _smart_symbol_sortz5ShapeEnv._maybe_guard_rel.<locals>._smart_symbol_sort  s    )*d.A.A)A *c J*.*=*=a*@J G& qT:I {{499-!)UZZ8889~{{66D3AD$GGD$GGr\   T)r  r  c              3  :   K   | ]  }|j                   d k7    ywr  r  r  s     r[   r"  z,ShapeEnv._maybe_guard_rel.<locals>.<genexpr>  s      4'(AIIN4s   c                    t        | t        j                        r2t        |       rt        |      syt	        | t
        j                        ryyr  )r   r   rR  r  rB   rC   r\  )rQ  rU  s     r[   trivial_solvez0ShapeEnv._maybe_guard_rel.<locals>.trivial_solve  s>    !#u||405>S? $()#tzz:#' !r\   trivial_lhstrivial_rhsFrM  c              3  4   K   | ]  }|j                     y wrU   )r  )r  r  s     r[   r"  z,ShapeEnv._maybe_guard_rel.<locals>.<genexpr>  s      -)*-r  r   r  rD  divisibility)r  r  r]   ztuple[int, int, str])rQ  r   rU  r   r]   r   )/r   r   rt  rx  r  ru   r#  r  rQ  rU  _refine_rangesrP  r  r9   r  r5   r  r  r  r  r  r@   r$  preorder_traversalr  r  r  r^  rY   Numberr  rR  rP  r  rI  r   r   r_  rE   floordivrS  rG   wrapr[  r"  rc  r  )rX   r   freerj  rQ  rU  floor_div_atomsrm  r  r  okmod_exprpqr  i0di1s   `                 r[   _maybe_guard_relzShapeEnv._maybe_guard_rel~  s    $		***
 dEHH%D%%& IM	H@G	H t9q=	H" d 2DAhhhhD! $)xx}0"%))H"5";";CIIh<O"P'!+ 4,;4 1 .- 
! !c*))#tzz#N"3,))#tzz#N!$QUKA} -.3.F.Fqt.L- * #'**QqT"2 !6w!?@AE 11$q'7GL 88C=DC12H+dH%H=QqTQY''1 $==DAq"1ell3&q%))4K1, !2 'q%,,7 *2u|| < $ 7 7 ; !"EIIaO 3A!%!<!<!>!C!C!H!HB !55 " 7 @ @$($5$5b$9;;K;KA;N!"  "T%=%== $ < <$&(@(@(D(I!"  "T^^3 $ 2 22 6 11"a"fnM 	a ' \ ' s&   $D7P, GP< ,	P98P9<	QQc                F    |s| j                   sdnd}t        |t              S )Nr   rD  )r4  rG   r;   )rX   r  r  s      r[   r^  zShapeEnv._default_value_range  s#     18P8PWX5&))r\   c                *    t        j                         S rU   )rG   unknown_intr   s    r[   rJ  z)ShapeEnv._default_unspecified_value_range  s    &&((r\   c                   t        |j                  t                    }t        |      D ]D  }|j                  \  }}t        ||      }t        j                  |d      }| j                  |       F | j                  |      S r  )
rN  r  r5   r  rY   r9   r   rP  r  r  )rX   r   
floor_divsr)  r  r   rz  eq_exprs           r[   _simplify_floor_divzShapeEnv._simplify_floor_div   ss    4::h/0
 :& 	(BGGMD'4)Hhhx+Gw'	( }}T""r\   c                   | j                   r{| j                  dxx   dz  cc<   t        ddi | j                  | d| dd       t        j                  d||t        j                         t        j                  k  rd	nd
       y y )Nignored_backward_guardr   r  evaluate_expr_frozenr  rD  )ignored_guardversionz>Ignored guard %s == %s, this could result in accuracy problemsTFr,  )	r  rl  r'   rS  r   rJ  getEffectiveLevelr   WARNING)rX   r   r  s      r[   _check_frozenzShapeEnv._check_frozen0  s    ;;LL12a72&nn(,vT,%@  !
 HHP#&#8#8#:W__#L4RW   r\   c                H   |}|t        j                         }	 |y|j                  j                  t	               vrJt        j                  |j                  j                  |j                  |j                  j                        }n|j                  }|y~d }t        j                         }|r`t        |      dz
  }|dkD  r=||   j                  t	               v r$|dz  }|dkD  r||   j                  t	               v r$t        ||   d      }d}|r)|r'ddj                  t        j                   |            z   }|rLt"        j$                  r<t'        j(                  d      }	|ddj                  |	j+                               z   z  }n|r|d	z  }t-        ||      |fS # ~w xY w)
Nr   r   T)liner  zM
User Stack (most recent call last):
  (snipped, see stack below for prefix)
)r}  z
C++ stack trace:
z?
For C++ stack trace, run with TORCHDYNAMO_EXTENDED_DEBUG_CPP=1)r   rg  rj  rk  r   	tracebackFrameSummaryrl  co_namerh  r!   rX  r#  filenamerI   r  format_listr/  extended_debug_cpprH   rC  rF  r   )
rX   r;  framework_locflocrn  maybe_user_locrT  r  r=  	cpp_stacks
             r[   r9  zShapeEnv._get_stack_summaryF  s    >K<((*E'||//7J7LL(55!LL44!NN!LL00 
 !LLE '   ..0g,"C'gcl337J7LLq 'gcl337J7LL)'#,TBN>'')//89: 
 11)11d;I!7"'')BRBRBT:U!UUR D.)+<<<7 s   A:F F!c                0    | j                  |      \  }}|S )N)r  )r9  )rX   r  r<  r&  s       r[   rF  zShapeEnv._get_slocu  s    )))Far\   c                    i }i t               x}	 |j                  j                  dk(  r
t               S t	        t        j                  |j                              }t        j                  |j                        \  }}d\  }}}t        |      D ]6  \  }	}
|
j                  |
j                  }||j                  k7  r.||	x}}5|	}8 ||
t               S d	 fd|j                  }|||dz    D ]  }
|
j                  x}t        ||      }t        |
j                  t              s8|
j                  |j                   v sQt#        j$                  |j                   |
j                           ||
j                  <    ||j                  |z
  |dz   |z
   }t'        |d         t'        |d   j)                               z
  }dj+                  |D cg c]  }||d 	 c}      j-                         }t        ||      S c c}w )
z
        Given the current user code frame, finds the relevant lines of code,
        values of symbolic locals, and free symbols involved.
        Nr   )NNNc                n   t        | t        j                        r| j                         D ]
  } |        | j	                         D ]
  } |         | j                                d| j                          d| j	                          d| j                          dS t        | t        t        t        f      ry| j                  j                  j                  D ]K  }t        |      v r|j                  v s j                  |   d   j                         t        |      <   M t        |       S y )NzTensor(shape: z
, stride: z, storage_offset: r  r   )r   r   rJ   re  rf  rg  r   r   r   r   r   ru   r   r  r  )r  rH  r  frame_symbolsr$  rX   s      r[   r$  z'ShapeEnv._find_frame_locals.<locals>.go  s   !U\\* AqE AqE1##%&$QVVXJ / xxzl +''('7'7'9&:!=
 A:;11 QA1v. D///040C0CA0Fq0I0N0N0Pc!f-	Q
 1vr\   r   r   r  )rA  rC  r  )r  r   r]   r@  )_find_user_code_framerj  rk  r?  r  disBytecoder   getsourcelinesr  starts_linerl  rZ  r   argvalr   f_localsrH  tree_mapr#  lstripr  r  )rX   frame_localsrn  instructionsco_linesr  startendr   r6  instrlast_linenolinenolocsindentrA  	frame_locr  r$  s   `                @@r[   _find_frame_localszShapeEnv._find_frame_localsy  s   
 (*(* +,,E\\--;$&& CLL67"11%,,?&*sC!,/ 	HAu  ,''enn$}	 =CK$&&	, nn!%#'2 	E+++8!+v6%,,,1O-3__u||4.U\\*		 /+/F2JKT!WDGNN$4 55GGT:cS\:;AAC	 ,
 	
 ;s   Hc           	         t        d fd       t        dfd        j                  j                  t        j
                        rzt              }t        j                  d uxr |t        j                  k(  } j                  |      \  }}d}|sd| d} j                  j                  d	|s|n| d
|||||       y y )Nguard_addedc            	     N   t              t        j                  t        j                  d      j                               j                  j                         D  ci c]  \  } }|j                  v rt        |      | ! c}} t        j                               dS c c}} w )Nr   r@  )r   r6  symbol_to_sourcesr  )r   r$   rW  rH   rC  rY  r_  r9  ru   r   r  )r>  r?  r  rX   s     r[   r1  z%ShapeEnv._log_guard.<locals>.<lambda>  s    A#22%--15==?
 !% 2 2 8 8 :&1ANN* FAI&
 !'t'>'>'@ A! 
&s   $B!
r6  guard_added_fastc                     t               t        j                  t        j                               t        j                  t        j                  d      j                               dS )Nr   r@  )r   r2  r6  )r   r$   rW  r!   rX  rH   rC  rY  )r  s   r[   r1  z%ShapeEnv._log_guard.<locals>.<lambda>  sM    A(778T8T8VW#22%--15==?! r\   r  zA, for more info run with TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED=""z%s %s [guard added] %s%s%sz (forcing_spec)r,  )r"   r%   r   r   r   INFOr   r/  extended_debug_guard_addedr9  rJ  )	rX   r:  r  forcing_specstr_gr;  r<  r=  re  s	   ` `      r[   
_log_guardzShapeEnv._log_guard  s    	
 			
 88  .FE11= ?V>>>  '+&=&=h&G#D# O??DgQH   HHMM,*6(/0J!#   /r\   r  c                    t        |      | _        | j                  |j                  |j                  |j
                  |      S )zY
        Given a a SymNode, evaluates sym_node.expr, adding guards if necessary.
        )r3  r  r  r   rL  r   )rX   r   r	  s      r[   evaluate_sym_nodezShapeEnv.evaluate_sym_node  s:     "$H!!MM8==(*:*:N
 	
r\   )save_tracked_fakesr  c                   	 | j                  |||||      S # t        $ r! | j                  j                  d||||        w xY w)Nr  zKfailed during evaluate_expr(%s, hint=%s, size_oblivious=%s, forcing_spec=%s)_evaluate_exprrC  r   r  )rX   r  rL  r   r	  r  s         r[   r  zShapeEnv.evaluate_expr  se    	&&) '    	HH] 	s	    *Ac                   t        t        j                  j                  j                  t        j                  j                  j
                  f      rS t        j                  d      d fd       }d}d} j                  r,|) j                         s|st        d j                  D              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}	 j*                  re j,                  j/                  d       Et        t0              rk(  sJ  d        S t        j2                        sJ  d        S } j5                  ||      }|L j,                  j/                  d|rd	 d
n||       |s#t6        j8                  r|k(  sJ | d        |S d}d}	|j                   j:                  j=                         k  sȉ j5                  |d      }|J |j                   j:                  j=                         k  sd}|s j5                  |d      }d} j>                  rjA                   j>                        x}j                  ssjA                   j>                  jC                         D ci c]  \  }}|tE        d|       c}}      x}j                  s ||k(  rt,        jG                  d|       |}	d}|s jH                  rjA                   jH                        jA                   j:                        xj                  s@t,        jK                  d       tM        dfd       tO        d fd       d}}	d}|s: jQ                  |jA                   j:                        || jR                        |}|	 |       }	 jU                  ||	       t6        jV                  rOt        t0              r?t        |t        j2                  t        jX                  f      rt        jZ                  |      }|	t        j                  u rt]        t^        |      }n>|	t        j                   u rt        jZ                  |      }nt        j2                  ||	      }|r ja                  |d d|	        |	S  j                         sۉ jc                  d||       t        |t        jd                        r jg                  |        jh                  sztk        | jm                         |      } jn                  jq                  |        jr                  ju                  tw         jy                   j{                  |                         n* ja                  |d        n jc                  d||        j                         s||j                  D ]  } j|                  |xx   dz  cc<   |rt6        j~                  . j|                  |   t6        j~                  kD  sO j,                  jG                  dt6        j~                  |        j                  |d        |	S c c}}w # t        $ r |r j                  |        w xY w)zO
        Given an expression, evaluates it, adding guards if necessary
        Nc                 `    j                        } | J | S t        j                        S rU   )r;  r   r0  )r  rL  r  rX   s    r[   compute_concrete_valz5ShapeEnv._evaluate_expr.<locals>.compute_concrete_val6  s6    | NN9-}$}}}T**r\   Fc              3  P   K   | ]  }t        |t        j                           y wrU   )rB   rC   r\  r  s     r[   r"  z*ShapeEnv._evaluate_expr.<locals>.<genexpr>S  s     V!q$**5Vs   $&zeval %s [trivial]r,  rO  z eval %s == %s [statically known]zsize_oblivious(r  Tr  rD  z/oblivious_size %s -> %s (passed counterfactual)z.propagate_real_tensors evaluate_expr(%s) -> %sr/  c                     t               t              t        j                  t        j                  d      j                               dS r1  r2  )r  unsound_results   r[   r1  z)ShapeEnv._evaluate_expr.<locals>.<lambda>  s>    (,Y*.~*>)3)B)B$5$=$=1$E$M$M$O*"1 r\   r6  !propagate_real_tensors_provenancec                 \   t              t              j                  t        j                  d      t        j                  d      j
                  j                         D  ci c]  \  } }|j                  v rt        |      | ! c}} t        j                               dS c c}} w )Nr  )r   rY  expr_node_idr2  r6  r  r  )r   r  r$   r4  r5  r_  r9  ru   r   r   r  )r>  r?  r  rX   r  s     r[   r1  z)ShapeEnv._evaluate_expr.<locals>.<lambda>  s    (,Y*.~*>040F0F.8.G.G.J)3)G)G)J 150B0B0H0H0J6"(,1'(I,B,B'B %(FAI6"
 17t7N7N7P0Q1 6"s   &$B(r=  r4  r  r  r  zevaluate_expr: zeval [guard suppressed]r   z6symbol_guard_limit_before_specialize=%s exceeded on %s)r]   rR   )Cr   r   ry  rz  r  r  r   r   rL  r  r  ru   r  r  r   _assertr  rF  not_r_  r  r  r   r   r   rP  rB  r/  r  r  r  r\  r  r9  rZ  rJ  r[  r  r%   r"   r7  r  r  /inject_EVALUATE_EXPR_flip_equality_TESTING_ONLYrx  rw  r   r   r6  r  rt  r  r7  r   rF  r   r  rZ  r  r  r  r  rm  $symbol_guard_limit_before_specializer  rC  r  )rX   r  rL  r   r	  r  r  r   r  r  r  r&  eqlr  r   static_exprtransmute_into_runtime_assertr  r>  ry  r9  r>  r?  r:  r  r  r  s   ```                       @r[   r  zShapeEnv._evaluate_expr   s    [[  ,,ekk.A.A.N.NO
  
		T	"	+ 
#	+* 00#--/"Vy?U?UVV 01Luzz)";;EMMG:Ve,66x}}wjQQ";;EMMC6Re66KK'<!8Q #;;EMMC6Re###
 **40 R	E""2I>#!$-(D0JYKtD62JJ0 !   %xx	48RYKtD6:RR8  D55^ 6 K &6% &i[2' '44( '$.J;-tD60JJ."",1)L%%)=)=)??  66t46P+++ --1E1E1GG,0))040K0K  1L 1- B 11,5,>,> $ 9 9- L ',	!' 4=3E3E 150I0I0O0O0Q!"(,1 %&s1ayL!"4 / ',!' ),?? M%(
 (4!  44.7.@.@ $ 8 8/&ht78N ',	!' L%*
 )4)	 *?)  9=5'5!"== MM$//: 2G-1-C-C	 >   $D#35t\2 FFtT*tehh%9:yy uzz)t,,IIdOHHT<0,))1)DO $#,,.Ea+ ))!,CC '4>>+NE KK&&u-KK&&tD,A,A$--PQBR,S'TU
 --a?9+1NO 91<X ,,.$^^ E11!494 !- & K K W $ 9 9! <$II!J !HHMM X & K K !
 !..qt.DE" q!"@  	$$T*	s;   9A\, #\, *A"\, C\, ,\&
G4\, 8C?\, &\, ,]
c                    | j                   j                         D ]  }|j                           | j                  j                         D ]#  }|D ]  }|j                  j                           % y)z
        Break reference cycles.

        This destroys the stacks. If you really want to keep them, we
        just need some way to break references on code objects.
        N)r^  r.  cleanuprg  r6  )rX   r  r  r  s       r[   r  zShapeEnv.cleanupI  sh     ""))+ 	AIIK	00779 	#C #  "#	#r\   c           	        |}| j                  |      }|(| j                  j                  d||       t        |      S | j                  |d      }|J | j                  s:|j
                  | j                  j                         k  r| j                  ||      S | j                  rM|K| j                         s;| j                  t        j                  |f      \  }}|J |r| j                  |       | j                         sl| j                  d|d       | j                   rt        j#                  d	|       | j%                  |t&        j(                         t+        |t&        j,                        r| j/                  |       |}t1        |      }t3        j4                  d
      }	t7        |||	      }
t9        d |j
                  D        d       }|r|d   nd}| j:                  j=                  |g       j?                  |
       | j@                  jC                  tE        | jG                  | jI                  |                         | xjJ                  d
z  c_%        | jM                          y| j                  d|d       y)aQ  Create an assert that is checked at runtime

        Args:
            orig_expr (sympy.Expr): Boolean expression to assert is true
            msg (str): Message to display on assertion failure
            fx_node (Optional, torch.fx.Node): node in ``self.graph`` corresponding
                to the expression, if applicable

        Nz*runtime_assert %s == %s [statically known]Tr  r  runtime_assertFr  z&runtime_asserts_frozen but then got %sr   r@  c              3  V   K   | ]!  }t        |t        j                        s| # y wrU   rL  r  s     r[   r"  z0ShapeEnv.defer_runtime_assert.<locals>.<genexpr>  s     Vq4CTCT1UVr  c                2    t        | j                  dd        S r  )r   r  r  s    r[   r1  z/ShapeEnv.defer_runtime_assert.<locals>.<lambda>  s    c!&&*o r\   r  r  z!runtime_assert [guard suppressed])'rB  r   r   r   r6  ru   r  r  r  rL  r  r  r   r  r  r  ri  r  r  r   r  r   rt  r  rr   rH   rC  r4  r  rg  
setdefaultr  rZ  r  r  r  r  rh  r  )rX   r  r5  r   r   r  r  r   r  r6  r  candsixs                r[   r6  zShapeEnv.defer_runtime_assertV  sI     11$7"HHNN<i $$ ..t4.H###@@%%)=)=)?? %%h%@@
 00#--/77zRKD%###**40((*OO,ieOL **DdKtUZZ0$		*%%d+ I)$/D%--15EtS%0BVD--V-E $rB))44R<CCBGKKtD$9$9$--:M$NOP--2-((* 	 OO3YU   r\   c                   | j                  |      }|j                  D ]4  }t        |t        j                        sJ t        | j
                  j                  |d       t              rKt        ||      }||j                  r|d   j                  su|\  }}| j                  |   }|j                  |j                  }}t        || j                        }	||	j                  k  rit        |t        j                  t        j                  t        j                   f      r0|	j                  t#        t        |t        j                               z   }||	j                  kD  rit        |t        j                  t        j$                  t        j&                  f      r0|	j                  t#        t        |t        j&                              z
  }|t)        ||      k(  r| j+                  |t)        ||             | j                  |   j-                         r*| j/                  || j                  |   j                  d       | j0                  j3                          7 y )Nr   range_refined_to_singleton)r  ru   r   r   rR  r  r;  r?   r@   r  rS  r  r  rD   rP  r  r  r   r  r  rG   r_  r  r  rB  r   )
rX   r   rG  r  r_exprrU  r  r  r  rhs_vrs
             r[   rr  zShapeEnv._refine_ranges  s   }}T"'' 9	6Ffell333$//--fd;\J $'Ay!2!2qt KFC""6*B88RXX5E d&7&78F v||#
588UXX6)
 s:fehh+G'HHv||#
588UXX6) s:fehh+G'HH [.. %%fk%.GH  (557%%%%f-330 ''335s9	6r\   )r   c                   t        ||      }| j                  j                  |t        j                               }| j	                  ||       | j                  |   x}|k7  r-t
        j                  d||j                  |j                         y y )Nz"constrain_symbol_range %s [%s, %s])	rG   rS  r;  rD  r_  r   rJ  r  r  )rX   r  rL  rM  upd_vrold_vrnew_vrs          r[   rK  zShapeEnv.constrain_symbol_range  s{    
 \<8""&&q+*=*=*?@!!!V,''**Fv5HH4av|| 6r\   )rE  Optional[bool]rF  Optional[list[Any]]r)  r   r]   r^   )r1  r   r2  r   r3  r   r4  r   r5  r  rS  zOptional[dict[str, str]]r6  r   r7  r   r]   r^   )r]   r   )r   rl   r]   r^   )r]   r  r   )r]   Iterator[None])r  r  r9  r   r]   r^   )r>  r  r?  r   r]   r^   )r  r  r9  r  r]   r^   )r  r  rU  r   r]   r^   NN)r  r  rY  r  rZ  r  r]   r^   )r  r   rY  r   rZ  r   r]   r^   )r  r   r  r   r]   r^   )r  r   r]   r   r   )r  r    r]   Optional[sympy.Symbol])rG  r  r   r   r]   r^   r  )rF  r   rY   rN  r]   z$tuple[Optional[torch.fx.Node], bool])rG  r  r   r   r]   Optional[torch.fx.Node])r   r  r]   r^   )r   torch.fx.Noder]   r^   )r]   z_GeneratorContextManager[None])r]   ztuple[int, int, int, int])r  Sequence[Union[int, SymInt]]r  r    r  r~   r]   list[sympy.Expr])r  r  r  r    r  r~   r]   r  )r  torch.Tensorr  r    r  r  r]   Ytuple[tuple[Union[int, SymInt], ...], tuple[Union[int, SymInt], ...], Union[int, SymInt]])r  r  r]   r  )r  r  r  r  r  r  r  zSequence[bool]r  r    r  r  r]   r  )r  r    re  zSequence[sympy.Expr]r  r  r  r  r  zSequence[DimDynamic]r  zJSequence[Optional[Union[StrictMinMaxConstraint, RelaxedUnspecConstraint]]]r  r   r  r~   r]   r  )r  r   rL  r  r  Optional[Source]r]   r  )r  r   rL  r  r  r  r]   r  )r  r   r  r    r  r  r]   r  )r  r   r]   r   )r:  r   rG  r  r  rG   r  r  r   zOptional[SymNode]r]   r^   )r]   r   rU   )r  r  r]   r   )rG  r  r]   r   )r]   r   )r   z#Union[int, SymInt, float, SymFloat]r  r    r  r  r  r  r  "Optional[StatelessSymbolicContext]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    r  z6Union[StrictMinMaxConstraint, RelaxedUnspecConstraint]r]   r   )rY   r   r)  r   r]   rq  )r  Sequence[FakeTensor]rH  zSequence[Source]rC  rQ  r   Optional[list[ShapeGuard]]rw  z"Optional[DimList[SymbolicContext]]rx  zOptional[EqualityConstraint]ry  r   rz  r   rp  ztuple[str, ...]r]   zlist[_ShapeGuardsHelper])r  z#Sequence[Union[SymInt, FakeTensor]]r   r  rz  r   r]   r@  )r  r   r]   zUnion[int, float, bool])r  r   r]   r  )r  r   rY   zSequence[object]r]   r   )r  r  rY   Sequence[Tensor]rz  r   r]   r   )r  zSequence[torch.SymInt]r]   zlist[ShapeGuard])r  r  rY   r  r]   dict[sympy.Symbol, int])r]   zlist[SympyBoolean]r  )r  r   r]   r   )r   r   r	  r   r]   rG   r  )r  zOptional[tuple[sympy.Symbol]]r  r   r]   ztuple[SympyBoolean, ...])r  r   r]   z@tuple[tuple[SympyBoolean, sympy.logic.boolalg.BooleanAtom], ...])r   rR   r  r   r  r   r	  r   rZ  zOptional[tuple[SympyBoolean]]rS  z1Optional[tuple[tuple[sympy.Symbol, ValueRanges]]]r]   Optional[sympy.Basic]r   r   r]   r   )r   r   r	  r   r]   r   )r   rR   r-  r   r]   r  r   r   r]   r   )
r   rR   rD  rR   r>  r  r?  r  r]   rQ   )
rG  r  r  rG   r  zOptional[ValueRangesSLoc]rR  r   r]   r^   )r  r  rS  r   r5  r   r]   r^   )r   r   r]   r^   )r  r  r]   r   )r   z	sympy.Relr]   r^   )r  r   r]   rG   )r]   rG   r   r   r]   r   )r   rR   r  rR   r]   r^   )FN)r;  r   r  r@  r]   ztuple[SLoc, str])r  r@  r]   r   )r]   r?  )r:  r   r  r   r  r   r]   r^   )r   r.   r	  r   r]   rR   )NNF)r  rR   rL  z!Optional[Union[int, bool, float]]r   r  r	  r   r  r   r]   rR   )r  rR   rL  z!Optional[Union[bool, int, float]]r   r  r	  r   r  r   r]   rR   )r  r   r5  r   r   r  r]   r   )r  r  rL  r   rM  r   r]   r^   )qr_   r`   ra   rW   rJ  propertyr1  r2  r3  r4  r5  r6  r7  r  r  r  r
   r  r*   r/  r"  rW  rT  rQ  ra  rd  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  r#  r&  r)  r>  rA  rI  rP  rN  r  r  r%  r  rh  rk  rn  rs  rr  r  r  r  r  r|  r  r  r  r  rD   r2  r
  r   r  rB  r  r  r  r;  r  r7  r_  r  r^  r  r  r^  rJ  r  r  r9  rF  r  r  r  rb   r  r  r  r  r6  rr  rK  rh   r\   r[   rl   rl   7  s    04-1	8 -8 +	8
 8 
8D &*/3
 */ %) &*.2 =B 9>Ke= #e= )-	e= #'e=( ")e=. #/e=2 ,3e=B 6:Ce=J 26Ke=P 
Qe=N 2 2 < < 6 6 1 1 ( ( I I E E?VBK($ & & C C 7 7 J J   OS$1?L	 *  " #9 #9JD  
 	: 	:   	+ 	+.11/& == = 
.	= =<,, , 
!	,8(
=6 # # " "&

'&
-
 
 *	

 

1  *	
 
L 7;"
"
 "

 4"

"
L	+			  7;tG .	tG
 0tG .tG 'tG tG 4tG
tG tGl88 #8 .	8
 08 .8
8 8 *8 
8t  $()) 	)
 !) 
) )V  $("" 	"
 !" 
 " "H 

"(
7A
	
 
7 $(&*#
#
 #
 	#

 !#
 $#
 
#
J " "0    09 ! !0 
 #-//(,?C
0
 
  	

 &
 =
 

 
: 
 #-//(,#'+0?Czz z  	z
 &z !z %)z =z 
z zx3F  !W 	 ,X /A	B .2=A ;?!"!=B*B "B ,	B +B ;B 8B B B B 
"BP .2"9 +	
  
2..K #* 
  
2028H2	 2h	

 8=//04/	/$  26"3.3 3 
"	3 3: t_&$&$	I&$ &$P 
 $"$04JNUU 	U
 U U .U HU 
U Un   ' ' ? ?D s^7<GG04G	G GT s^
 
 8<*.:6:6 #:6
  5:6 (:6 
%:6@ .2	15 $1515 15 +	15 15 
15fc@J' $  $" s^U Ur 27**.*	*) # #. FJ,=,=5B,=	,=^D
L/h (,}+
  %

 
 
	
 s^d3 37+/$ # 0 )	
   
 4 < 37+/$g #gg 0g )	g
 g g 
gR	# s^d3TXO%O,/O:QO	O 4 Ov<6| t		-0	@C			  	r\   c                f    t        | t              xr  | j                  j                  j                  S rU   )r   r   r   r   r  r  s    r[   _is_intr     s"    dF#@		(@(@@r\   c                :    t        | d      xr || j                  v S )N_dynamo_dynamic_indices)r  r  )r  r~  s     r[   r  r    s     1/0SQ!:S:S5SSr\   c                        e Zd Zd fdZ xZS )PropagateUnbackedSymIntsc                j    ddl m} t        |   |      }t	         |       j
                  ||       |S )z]
        Run an FX node, propagating unbacked Symbol bindings to the new fake tensor
        r   )detect_fake_mode)torch._guardsr  rV   run_noder   r<  )rX   rX  r  rY  rZ   s       r[   r  z!PropagateUnbackedSymInts.run_node	  s2     	3!!$(*44a@r\   )rX  r  r]   r@  )r_   r`   ra   r  rc   rd   s   @r[   r  r    s     r\   r  c                 >   t        j                         } | | j                  j                  j	                  t
        j                  j                  t        j                  t                    t
        j                  j                  z         s	 | S | j                  } | | S rU   )r   rg  rj  rk  
startswithra  r[  dirnamer   r   seprh  )rn  s    r[   r  r    sx      "E

||''22GGOOGOOE23bggkkA
 L  
 Lr\   c                J   t        j                  |j                  j                  |j                  |j                  j
                        }| j                  d   }|ddj                  t         j                  j                  |g      j                               z   z  }|f| _        y )Nr   z(

The following call raised this error:
r  )r  r  rj  rk  rl  r  rY   r  StackSummary	from_listrF  )r  rn  frame_summaryr5  s       r[   _blame_user_coder    s    **  M
 &&)C8277((-9@@B<  C VAFr\   c                  ,     e Zd ZdZd fdZddZ xZS )_PythonMsgPrinterz
    Util printer that replaces sympy symbols with their source-level names
    and renders sympy relational operators (e.g., Eq, Ne, Ge, Le) inline
    (i.e., as ==, !=, >, <).
    c                0    t         |           || _        y rU   )rV   rW   src_map)rX   r  rZ   s     r[   rW   z_PythonMsgPrinter.__init__3  s    r\   c                :    | j                   |j                     d   S r  )r  r  r(  s     r[   rK  z_PythonMsgPrinter._print_Symbol7  s    ||CHH%a((r\   )r  zdict[str, list[str]]r]   r^   )r  r  r]   r   r  rd   s   @r[   r  r  ,  s    )r\   r  c                "   | j                   }dj                  fd|j                  D              }|rt        j	                  d|       y t              }| j                  d   }|dz  }d|j                  |       dd|j                  t        j                  |             dg}t        |      D ]  \  }}|d|d	z    d
| z  } dj                  fdt        d |j                  D              D              }	|d|	 d| dz  }|f| _        y )Nr  c              3  T   K   | ]  }|j                   vs|j                    ! y wrU   r  r  r  r  s     r[   r"  z(_suggest_torch_checks.<locals>.<genexpr>@  s      P!&&:OQVVPs   ((z.Unable to find user code corresponding to {%s}r   zG
To fix the error, insert one of the following checks before this call:ztorch._check(r  r  r   r  c              3  R   K   | ]  }d | ddj                  |             yw)`z` with z or N)r  r  s     r[   r"  z(_suggest_torch_checks.<locals>.<genexpr>O  s4       A3gfkk'!*-./s   $'c              3  4   K   | ]  }|j                     y wrU   r  r  s     r[   r"  z(_suggest_torch_checks.<locals>.<genexpr>Q  s     :1:r  z3

(These suggested fixes were derived by replacing z in z and its negation.))rS   r  ru   r   r  r  rY   rO  r   rw  r  r  )
r  r  rS   diffr  r5  suggested_fixesr6  fix
src_mappeds
    `        r[   _suggest_torch_checksr!  ;  s%    66D99PT%6%6PPDDdK(G
&&)CUUC -.a0
		$89;O O, %3a!eWBse$$% :(9(9:: J B:,dSWRXXkllCVAFr\   c           	     2   t               }|Zt        | |       t        t              }|j                  j                         D ]  \  }}	 t        j                  |      }|D ]  \  }}|t        j                  |      z   }t        |t        j                        r2|t!        |j"                  j$                           j'                  |       jt        |t        j(                        st+        |j,                        D ]W  \  }	}
t        |
t        j                        s!|t!        |
j"                  j$                           j'                  | d|	 d       Y   t/        | |       yy# t        $ r$ t        j                  dt        |      |       Y Rw xY w)z
    Given a raised data-dependent error, add the following to the error message:
    1. the closest user code location that raised the error;
    2. suggested fixes for the error in terms of live variables at that location.
    NzQpytree.tree_leaves_with_path failed for value of type {%s} in local variable {%s}z.shape[r`  )r  r  r   r  r  r9  rH  tree_leaves_with_pathr  r   r  r   keystrr   r   r   r   r   r   r  rJ   r  r	  r!  )r  rn  r  varr   r#  r[  leafr  r6  r  s              r[   2_suggest_fixes_for_data_dependent_error_non_strictr'  W  s`    "#EE" d#,,. 	UHC(.(D(DS(I% 4 U
dV]]400dELL1C		/077=ell3"+DJJ"7 U3%c5<<8#C$67>>$wqcQR?STUU	U, 	a)9   gI
 s   E)))FF)r   z$functools._lru_cache_wrapper[object]r]   r^   )r   ztuple[Union[SymInt, int], int]r]   z#tuple[int, Union[SymInt, int], int])r   r  r]   z?Callable[[Callable[..., _T]], functools._lru_cache_wrapper[_T]])r]   zset[str])r  r  r]   r   )r	  zSequence[Int]r]   z	list[Int]rU   )r  r   r  r  r]   r   )r  r  r]   r   )r  r  r]   r   )r  r  r]   r   )r   zUnion[torch.SymBool, bool]r]   r   )r&  #Sequence[Union[torch.SymInt, bool]]r'  r(  r]   r   )r/  r   r0  r   r]   r^   )r<  Optional[ShapeEnv]r=  ,Optional[dict[sympy.Symbol, pytree.KeyPath]]r]   r*  )r<  r)  rX  r  rY  r@  r]   r^   )r   r  r]   r   )r   r   r]   r   )TN)
r  z!type[Union[sympy.Add, sympy.Mul]]rY   r  r  r   r  r  r]   r   )r   r   r]   r   r  )r  Union[bool, SymBool]r]   r   )r  r  r]   zTypeGuard[SymInt])r   r  r]   zIterator[sympy.Basic])r   r  r]   OrderedSet[sympy.Symbol])r   r  r]   r   )r  r  r]   r   )r  r  r]   r,  )r   r  r]   r  )r  ztorch.fx.Graphr]   z!dict[sympy.Symbol, torch.fx.Node])NNNF)r  r   r[  zpytree.KeyPathr  Optional[object]r<  r)  r  zOptional[set[sympy.Symbol]]r  r   r]   z"dict[sympy.Symbol, pytree.KeyPath]r  )
r<  r)  rd  r   r1  r-  r2  r   r]   r*  )r  rM   r]   r   )r  r+  r]   r   )r  r   rH  r   r]   r+  )r  z2Union[SymBool, SymInt, SymFloat, int, bool, float]r]   zUnion[bool, int, float])
r<  rl   r  r  rL  r   rM  r   r]   r^   )r  r   r]   r^   )r  r   rU  r  r]   r^   r  )r  r   rY  r  rZ  r  r]   r^   )r  torch.SymIntr  r.  r]   r^   )r   )r  Union[SymBool, bool]rm  r   r]   r   )r  r/  r]   r   )r  r  r]   r   )r  zUnion[SymFloat, float]r]   r  )ru  torch.fx.GraphModuler]   zlist[object])ru  r0  r]   rq  )ru  r0  rY   rJ   rz  r   r]   r   )ru  r0  rY   rJ   r]   r  )r  r   r]   zTypeGuard[SymbolicContext]r  r+  )r   z2Union[int, SymInt, float, SymFloat, bool, SymBool]r]   z+TypeGuard[Union[SymInt, SymFloat, SymBool]])rY   r  r]   ztuple[sympy.Expr, bool]r  )r  r   r]   r   )
r   r   r  ztuple[_SymbolInfo, ...]r  r   r	  r   r]   zOptional[_SympyT])r]   r   )r  Sequence[int]r
  r1  r]   r   )r  r1  r
  r1  r]   r   )r  r   r]   r   )r#  zUnion[bool, torch.SymBool]r]   zUnion[int, torch.SymInt])r  r   r   r  r]   r   )r<  rl   r]   r  )r   r   r]   r   )r  r  r~  r   r]   r   )r]   zOptional[types.FrameType])r  rC  rn  ztypes.FrameTyper]   r^   )r  rQ   r  zdefaultdict[str, list[str]]r]   r^   )r  rQ   r]   r^   (  
__future__r   rT  r   rk  r  r   r   r  r   r  rF  ra  ri  r   	threadingr  r   r   collections.abcr   r   r   
contextlibr	   r
   dataclassesr   r   r   enumr   typingr   r   r   r   r   r   r   r   r   typing_extensionsr   r   r   r   torch.fxtorch.fx.tracebackr   r  torch.utils._pytreer  _pytreerH  r   r   r   r  r   r   r    r!   r   r"   r#   r$   r%   r   r&   torch._utils_internalr'   torch.fx.experimentalr(   r/  torch.fx.experimental.recordingr)   r*   r+   r,   r-   torch.fx.experimental.sym_noder.   r/   torch.utils._ordered_setr0   torch.utils._python_dispatchr1   torch.utils._sympy.functionsr2   r3   r4   r5   r6   r7   r8   r9   r:   torch.utils._sympy.numbersr;   torch.utils._sympy.printersr<   r=   r5  r?   torch.utils._sympy.solver@   torch.utils._sympy.symbolrA   rB   rC   torch.utils._sympy.value_rangesrD   rE   rF   rG   torch.utils._tracebackrH   rI   typesrJ   r   rL   torch.typesrM   r  	InputListDimList	getLoggerr_   r   r   rN   rO   RuntimeErrorrQ   rf   _opsrk  rl  __all__ry   rz   r   r   rb   r   r  rO  r   r   r   r   r   r   rj   r   r  rk   rs   r  r   r  r  rm   rn   r   r(  r   r   rN  r@  r   r   rr   r  r|  r  rw   rx   r  r  r  ru   r{   r|   r  rv   r  r   r  r  r  r  r   r>  r@  r   r}   rq   rN  rR  rV  rQ  rb  re  ri  r=  ro   rp   rv  rx  r}  r  r  r  r  r  r  r  r  r  r  r~   r   r   r   r  IndicatorTypesr  r  r  r  r  r  r  r  rV  r  rt   r2  r4  r8  ABCr@  rW  FutureWarningrb  rd  rp  rt  rv  r{  r  localr  r0  r   r=  r?  rl   r   r  Interpreterr  r  r  r  r!  r'  rh   r\   r[   <module>rX     sM
   "    
       	 	 
   , 7 7 ? 0 0 
 
 
 ? >   ) ) $ $ , + B B V V 6 0 3  = / F
 
 
 . A 9 . G G  C 8( 	
g!  , 	L 	 zz~~#L & ! ( 8i 7 T]
)UZZu{{
C$% $%N		'	(	##D#P 4   F	| 	, u||S()Y )#	 %,,sESWWX	 X(& 22 
I:T!T:T 2T %,,ellC.?(@@A	 Ar:!r:&3r:=Cr:	r:r0.< %)	C	*C
C C #	C
 CB*'Z-`,B $
HgsE4ellJ )    0(;K2L LMi MY8I=

& $3 3 3 $' ' ' $+ + + $! ! ! "$(+/YY
Y Y "	Y
 )Y Y (Y~ +/	N!NN (N 	N
 2Nb4 2O"
99
9
9DD(D8;DKND	D'%TI @DFF!F/<F	F$ <@+=+=$+=+8+=	+=\%dLG DH%+<@	D! !j $   $HZ H H8 $;j ; ;6 ,.EtKL $gC gC gCT* $	 	 	 $#
 #
 #
x $P6 P PD $%5 % %"	;"0" 45G "J 3 (*  4_/
_/ )_/ 	_/
 _/ _/ _/D-
OO#0OO#0	<.' *K(H	 5944$14%4v $1 1 1 ]  
' 'T0- $ Z
	/ 	
	..
 .4 $  
 $1. 1 1M6 M
5- 54N Nb ioo $2 2 2    * * : : :E? E?P~A
T	uxx33 	
) )"-H	8'*"'*	'*r\   