
    9iL_                        S r SSKrSSKJrJrJrJr  SSKJr  SSK	J
r
JrJrJr  SSKJrJr  SSKJr  SS	KJrJr  SS
KJrJr  SSKJrJr  SSKJrJr  \(       a  SSKJr  SSK J!r!J"r"   " S S\5      r# " S S5      r$ " S S\$5      r% " S S\$5      r& " S S\$5      r' " S S\'5      r( " S S\'5      r)S r*S\$4S jr+ " S  S!\,5      r- " S" S#\.5      r/ " S$ S%\/S&9r0S' r1S(S)KJ2r2  g)*a  
Core variable tracking functionality for Dynamo. This module defines the fundamental
classes and systems used to track and manage variables during Dynamo's operation.

The module provides:
1. VariableTracker - The base class for tracking variables during compilation
2. MutationType system - Classes for tracking and managing mutations to variables
3. Source type management - Utilities for tracking variable origins and scope
4. Variable state management - Tools for managing variable state and transformations

These components form the foundation of Dynamo's variable handling system,
enabling accurate tracking and transformation of Python code into optimized
computations.
    N)	ItemsViewKeysViewSequence
ValuesView)Enum)AnyCallableOptionalTYPE_CHECKING   )graph_break_hints	variables)current_scope_id)raise_observed_exceptionunimplemented_v2)GuardBuilderinstall_guard)
AttrSourceSource)cmp_name_to_op_mappingistype)	PyCodegen)InstructionTranslatorInstructionTranslatorBasec                        \ rS rSrSrSrSrSrg)
SourceType$   av  
This Enum divides VariableTracker into 2 cases, depending on the variable
it represents:
- already existed that Dynamo began tracking while introspection (Existing)
- is a new variable that is created during Dynamo introspection (New)

In general, we have these invariants:
1. for `VariableTracker` associated with `Existing`, its `source` field must not be None.
2. for `VariableTracker` associated with `New`, most of the time its
   `source` field is None, except for cases like side effect codegen for
   `AttributeMutationNew`, during which we generate a
   `LocalSource('tmp...')` for such variable, to facilitate codegen.
r       N)__name__
__module____qualname____firstlineno____doc__ExistingNew__static_attributes__r       \/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/torch/_dynamo/variables/base.pyr   r   $   s     H
Cr(   r   c                   *    \ rS rSrSrS\SS4S jrSrg)MutationType7   z
Base class for Variable.mutation_type. It encodes information about
1. The type of mutation Dynamo allows on the variable.
2. Whether the value represented by this variable already existed before
Dynamo tracing.
typreturnNc                     U[         R                  L a  SU l        g U[         R                  L a  [	        5       U l        g [        SSU  SU 3SU S3S/[        R                  QS9  g )	Nr   zUnsupported SourceTypezMutationType.__init__  z"Dynamo does not support the type ``z,This branch is not supposed to be reachable.gb_typecontextexplanationhints)r   r%   scoper&   r   r   r   
DYNAMO_BUG)selfr-   s     r)   __init__MutationType.__init__?   sl    0 *%%%DJJNN")+DJ00au=@QGB&11	r(   )r7   )r    r!   r"   r#   r$   r   r:   r'   r   r(   r)   r+   r+   7   s    %J %4 %r(   r+   c                   <   ^  \ rS rSrSrSU 4S jjrS rS rSrU =r	$ )ValueMutationNewg   a  
This case of VariableTracker.mutation_type marker indicates
1. Dynamo allows mutation on the value itself (rather than its attributes).
2. The value is created by the bytecode Dynamo is tracing through.

For instance, Dynamo could model a newly created list with this marker,
indicating that while we need to model mutations to this list, we don't have
to emit bytecode for these mutations if the list doesn't escape into the
Python world.
c                 @   > [         TU ]  [        R                  5        g N)superr:   r   r&   r9   	__class__s    r)   r:   ValueMutationNew.__init__s   s    (r(   c                     [        U 5      $ r@   )idr9   s    r)   __hash__ValueMutationNew.__hash__v   s    $xr(   c                     XL $ r@   r   )r9   others     r)   __eq__ValueMutationNew.__eq__y   s
    }r(   r   r.   N)
r    r!   r"   r#   r$   r:   rH   rL   r'   __classcell__rC   s   @r)   r=   r=   g   s    	) r(   r=   c                   D   ^  \ rS rSr% Sr\\S'   SS\4U 4S jjjrSrU =r	$ )ValueMutationExisting}   a  
This case of VariableTracker.mutation_type marker indicates
1. Dynamo allows mutation on the value itself (rather than its attributes).
2. The value exists before Dynamo tracing started.

For instance, Dynamo could model a pre-existing list with this marker,
indicating that if we encounter mutations to this list, we need to buffer
and re-apply those mutations after the graph runs, since the list might be
used afterwards in Python.
is_modifiedc                 L   > [         TU ]  [        R                  5        Xl        g r@   )rA   r:   r   r%   rT   )r9   rT   rC   s     r)   r:   ValueMutationExisting.__init__   s    ,,-&r(   )rT   )F)
r    r!   r"   r#   r$   bool__annotations__r:   r'   rO   rP   s   @r)   rR   rR   }   s!    	 'D ' 'r(   rR   c                   4   ^  \ rS rSrSrS\4U 4S jjrSrU =r$ )AttributeMutation   zt
This case of VariableTracker.mutation_type marker indicates that Dynamo
allows mutation on the value's attributes.
r-   c                 $   > [         TU ]  U5        g r@   )rA   r:   )r9   r-   rC   s     r)   r:   AttributeMutation.__init__   s    r(   r   )	r    r!   r"   r#   r$   r   r:   r'   rO   rP   s   @r)   rZ   rZ      s    
J  r(   rZ   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )AttributeMutationExisting   a  
This case of VariableTracker.mutation_type marker indicates
1. Dynamo allows mutation on the value's attributes.
2. The value exists before Dynamo tracing started.

For instance, Dynamo could model a pre-existing object with this marker,
indicating that if we encounter mutations to this object, we need to buffer
then re-apply those mutations after the graph runs, since the object might
be used afterwards in Python.
c                 @   > [         TU ]  [        R                  5        g r@   )rA   r:   r   r%   rB   s    r)   r:   "AttributeMutationExisting.__init__   s    ,,-r(   r   )r    r!   r"   r#   r$   r:   r'   rO   rP   s   @r)   r_   r_      s    	. .r(   r_   c                   >   ^  \ rS rSrSrSS\\   4U 4S jjjrSrU =r	$ )AttributeMutationNew   a  
This case of VariableTracker.mutation_type marker indicates
1. Dynamo allows mutation on the value's attributes.
2. The value is created by the bytecode Dynamo is tracing through.

For instance, Dynamo could model a newly created object with this marker,
indicating that while we need to model mutations to this object, we don't
have to emit bytecode for these mutations if the object doesn't escape into
the Python world.

cls_sourcec                 L   > [         TU ]  [        R                  5        Xl        g r@   )rA   r:   r   r&   rf   )r9   rf   rC   s     r)   r:   AttributeMutationNew.__init__   s    ($r(   )rf   r@   )
r    r!   r"   r#   r$   r
   r   r:   r'   rO   rP   s   @r)   rd   rd      s    	%8F#3 % %r(   rd   c                     U S:H  $ )Nr   r   )scope_ids    r)   _is_top_level_scoperk      s    q=r(   mc                 V    [        5       n[        U5      (       a  gU R                  U:H  $ )NT)r   rk   r7   )rl   rj   s     r)   is_side_effect_safern      s)    !H
 8$$77hr(   c                   8   ^  \ rS rSr% S\S'   SU 4S jjrSrU =r$ )#AsPythonConstantNotImplementedError   VariableTrackervtc                 6   > [         TU ]  U S35        Xl        g )Nz is not a constant)rA   r:   rs   )r9   rs   rC   s     r)   r:   ,AsPythonConstantNotImplementedError.__init__   s    B4123r(   )rs   )rs   rr   )r    r!   r"   r#   rX   r:   r'   rO   rP   s   @r)   rp   rp      s     r(   rp   c                   >   ^  \ rS rSr/ rS\4S jrSU 4S jjrSrU =r	$ )VariableTrackerMeta   r.   c                     [        U5      [        R                  L a*  U [        [        R                  4;  a  UR	                  5       n[         R                  X5      $ )z-Make isinstance work with LazyVariableTracker)typer   LazyVariableTrackerrr   realize__instancecheck__)clsinstances     r)   r}   %VariableTrackerMeta.__instancecheck__   sH     Ni;;;)F)FGG'')H%%c44r(   c                 d   > [         TU ]  XU5        [        R                  R	                  U 5        g r@   )rA   r:   rw   all_subclassesappend)r~   namebasesattrsrC   s       r)   r:   VariableTrackerMeta.__init__   s&    e,**11#6r(   r   rN   )
r    r!   r"   r#   r   rW   r}   r:   r'   rO   rP   s   @r)   rw   rw      s    N5D 57 7r(   rw   c                   0  ^  \ rS rSrSr1 SkrS r\ S7S\S /S4   S\	S\
\\\	4      S	S4S
 jj5       rS	\4S jrS rS rS rS rS rS rS rSSS\S	\	4S jrSSS\S	S 4S jrS rS rS rS8S jrS	\S    4S jrS	\S    4S jrS	\ 4S jr!S	\ 4S jr"S9S  jr#S	\\   4S! jr$SSS\S	S 4S" jr%SSS#\&S    S$S%S	S 4S& jr'      S:S' jr(S( r)S;S) jr*S;S* jr+S+ r,S, r-S- r.S. r/S/ r0\1 S7SS0S\	S1\
\2   S	\	4S2 jj5       r3SSS3.S1\2S4\4S	S4U 4S5 jjjr5S6r6U =r7$ )<rr      z
Base class for tracked locals and stack values

VariableTracker instances are immutable and should be copied in
order to change them.

Prefer the factory function VariableTracker.build() over VariableTracker.__init__().
>   valueguardssourcemutation_typeparents_trackeruser_code_variable_namec                 r    [        U R                  5      nUR                  U5        U R                  " S0 UD6$ )z)Shallow copy with some (optional) changesr   )dict__dict__updaterC   )r9   kwargsargss      r)   cloneVariableTracker.clone   s.    DMM"F~~%%%r(   Nfnr   cacher.   c                 P   Uc  0 n[        U5      nXC;   a  gX#U'   [        U[        5      (       aq  UR                  5       nU" U5        UR                  5       nUR                  nUR
                  R                  5        H  u  pgXe;  d  M  U R                  XU5        M      g[        U[        [        45      (       a  U H  nU R                  XU5        M     g[        U[        [        R                  45      (       a*  UR                  5        H  nU R                  XU5        M     gg)z=
Walk value and call fn on all the VariableTracker instances
N)rF   
isinstancerr   unwrap_nonvar_fieldsr   itemsvisitr   listtupler   collectionsOrderedDictvalues)r~   r   r   r   idxnonvarskeysubvalues           r)   r   VariableTracker.visit  s     =Ei<c
e_--LLNEuILLNE**G!&!5!5!7%IIbE2 "8 ED%=))!		". "ED+"9"9:;;!LLN		". + <r(   c                 4    U R                   R                   S3$ )Nz())rC   r    rG   s    r)   __repr__VariableTracker.__repr__'  s    ..))*"--r(   c                 l     [        U R                  5       5      $ ! [         a    [        U 5      s $ f = fr@   )repras_python_constantNotImplementedErrorrG   s    r)   
debug_reprVariableTracker.debug_repr*  s4    	//122" 	:	s    33c                 p     [        U R                  5       5      $ ! [         a    [        U  S35      Sef = f)a  
Abstract method to be implemented by subclasses of VariableTracker.

This method should return the type represented by the instance of the subclass.
The purpose is to provide a standardized way to retrieve the Python type information
of the variable being tracked.

Returns:
    type: The Python type (such as int, str, list, etc.) of the variable tracked by
        the subclass. If the type cannot be determined or is not relevant,
        leaving it undefined or invoking super() is always sound.

Note:
    This is an abstract method and may be overridden in subclasses.

Example:
    class SetVariable(VariableTracker):
        def python_type(self):
            return set

Raises:
    NotImplementedError: If the method is not implemented in a subclass.
z has no typeN)rz   r   r   rG   s    r)   python_typeVariableTracker.python_type1  sA    0	G//122" 	G%l&;<$F	Gs    5c                 X     U R                  5       R                  $ ! [         a     gf = f)Nz<unknown type>)r   r    r   rG   s    r)   python_type_name VariableTracker.python_type_nameN  s.    	$##%..." 	$#	$s    
))c                     [        U 5      e)zFor constants)rp   rG   s    r)   r   "VariableTracker.as_python_constantT  s    1$77r(   c                 j     U R                  5       $ ! [         a    [        SSU  3SU  S3/ S9   gf = f)zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantszNot a Python constantzguard_as_python_constant zFailed to convert z into a Python constant.r2   N)r   r   r   rG   s    r)   guard_as_python_constant(VariableTracker.guard_as_python_constantX  sJ    	**,," 	/3D6:06NO		s    22c                 F     U R                  5         g! [         a     gf = fNTF)r   r   rG   s    r)   is_python_constant"VariableTracker.is_python_constantd  s(    	##%" 		    
  c                 f    U R                   (       a  U R                   R                  U5      $ [        er@   )r   
make_guardr   )r9   r   s     r)   r   VariableTracker.make_guardk  s$    ;;;;))"--!!r(   txr   r   c                     [         e)z/getattr(self, name) returning a python constantr   r9   r   r   s      r)   const_getattrVariableTracker.const_getattrp  s    !!r(   c                    U R                  X5      n[        R                  R                  U5      (       d  [        eU R
                  =(       a    [        U R
                  U5      nU(       aG  [        U [        R                  5      (       d(  [        UR                  [        R                  5      5        [        R                  R                  X4S9$ )z,getattr(self, name) returning a new variable)r   )r   r   ConstantVariable
is_literalr   r   r   r   r   r   r   CONSTANT_MATCHcreate)r9   r   r   r   r   s        r)   var_getattrVariableTracker.var_getattrt  s    ""2,))44U;;%%>DKK!>*T9+E+EFF &++L,G,GHI))000FFr(   c                 F     U R                  5         g! [         a     gf = fr   )as_proxyr   rG   s    r)   is_proxyVariableTracker.is_proxy  s%    	MMO" 		r   c                 *    [        [        U 5      5      er@   )r   strrG   s    r)   r   VariableTracker.as_proxy  s    !#d),,r(   c                      U R                  5       nSS Kn[        XR                  R                  5      (       a  UR
                  $ g ! [         a     g f = f)Nr   )r   torch.fxr   fxProxynoder   )r9   proxytorchs      r)   maybe_fx_nodeVariableTracker.maybe_fx_node  sG    	MMOE%00zz!" 		s   AA 
AAc                     [         er@   r   )r9   codegens     r)   reconstructVariableTracker.reconstruct      !!r(   c                     [         er@   r   r9   r   s     r)   unpack_var_sequence#VariableTracker.unpack_var_sequence  r   r(   c                 $    U R                  U5      $ r@   )r   r   s     r)   force_unpack_var_sequence)VariableTracker.force_unpack_var_sequence  s     ''++r(   c                 H     U R                  U5        g! [         a     gf = fr   )r   r   r   s     r)   has_unpack_var_sequence'VariableTracker.has_unpack_var_sequence  s*    	$$R(" 		s    
!!c                 $    U R                  U5      $ r@   )r   r   s     r)   has_force_unpack_var_sequence-VariableTracker.has_force_unpack_var_sequence  s    ++B//r(   c                 t    U R                  U5      (       d   eU R                  U5       H  nU" U5        M     g r@   )r   r   )r9   r   r   vs       r)   force_apply_to_var_sequence+VariableTracker.force_apply_to_var_sequence  s5    11"5555))"-AqE .r(   c                 F    [        SSU  3SU R                  5        S3/ S9  g )NzUnsupported inspect callzinspect_parameter_names 0Dynamo does not know how to trace the function `r1   r2   r   r   rG   s    r)   inspect_parameter_names'VariableTracker.inspect_parameter_names  s/    ..tf5J4??K\J]]^_		
r(   c           
          [        SSU  SU 3SU R                  5        S3SU R                  R                   SU S3/[        R
                  QS	9  g )
NzUnsupported hasattr callzcall_obj_hasattr r0   r   r1   zAvoid calling `hasattr(, z)` in your code.r2   )r   r   rC   r    r   SUPPORTABLEr   s      r)   call_obj_hasattr VariableTracker.call_obj_hasattr  se     	.'vQtf5J4??K\J]]^_)$..*A*A)B"TFJZ["..		
r(   r   r   dict[str, VariableTracker]c           	      z    [        SSU  SU SU 3SU R                  5        S3SU R                  5        S3S/S	9  g )
NzUnsupported function callzcall_function r0   r   r1   Avoid calling `` in your code."Please report an issue to PyTorch.r2   r   )r9   r   r   r   s       r)   call_functionVariableTracker.call_function  sV     	/$TF!D66(;J4??K\J]]^_!$//"3!4OD4		
r(   c                    US:X  a]  U R                  U5      (       aG  U(       d  U(       a   e[        R                  R                  [	        U R                  U5      5      5      $ US:X  aP  [	        U5      S:X  aA  US   R                  5       (       a)  U(       d"  U R                  XS   R                  5       5      $ U[        ;   Ga  [	        U5      S:X  Gav  U(       Gdn  US   n[        U [        U5      5      (       da  [        U [        R                  5      (       dB  [        U[        R                  5      (       d#  [        R                  R                  [        5      $ U R                  5       (       ai  UR                  5       (       aT  UR                  R                  R!                  U 5      (       d*  UR                  R                  R!                  U5      (       a&  [#        SSU  SU SU SU 3SU  S	U S
3SU S3-   / S9   [        R                  R                  [        U   " U R                  5       UR                  5       5      5      $ SU R/                  5        SU S3S/n[        U [        R0                  5      (       ac  US;   a]  [        U R2                  [4        [6        [8        45      (       a  UR;                  S5        UR;                  S5        UR;                  S5        [#        SSU  SU SU SU 3SU SU R/                  5        S3US9  g ! [$         aU  n['        [        U5      U[)        [+        [        R                  R                  UR,                  5      5      /S9   S nAGN#S nAff = f)N__len____getattr__r   r   z;Builtin `operator.*` comparison with constant `self` failedzcall_method r0   zFailed to compare z with r   zbecause z6 is not a Python constant or its mutation check fails.r2   )r   r  .r  r  )__iter____next__zConsider moving the creation of dict view object (e.g. `dict.keys()`, `dict.items()`,) to the compiled region, instead of passing it as an input to the compiled region.a   Dynamo does not fully support tracing builtin iterators (e.g. `map`, `zip`, `enumerate`) passed in from uncompiled to compiled regions (e.g. `torch.compile(fn)(enumerate(...))`). This can happen unintentionally if a previous graph break happens with a builtin iterator in the local scope.aF  List/dict comprehensions in Python <= 3.11 result in implicit function calls, which Dynamo cannot trace as a top level frame. Possible workarounds are (1) use a loop instead of a comprehension, (2) fix any graph breaks in the function above the comprehension, (3) wrap the comprehension in a function, or (4) use Python 3.12+.zUnsupported method callz*Dynamo does not know how to trace method `z` of class `r1   )r   r   r   r   lenr   r   r   r   r   r   rz   GetAttrVariableNotImplementedoutputside_effectshas_pending_mutationr   	Exceptionr   r   mapr   r   UserDefinedObjectVariabler   r   r   r   r   )r9   r   r   r   r   rK   er6   s           r)   call_methodVariableTracker.call_method  s    9!=!=b!A!A''--44S9Q9QRT9U5VWWM!D	QQ**,,##BQ(B(B(DEE++D	QvGEdDK004!:!:;;eY%>%>?? !1188HH ++--//1199))>>tDD99))>>uEE Y*4&$qaxH"4TF&r J ']^!_ 1188*40//153K3K3M  d3356av_M0

 dI??@@T N
 F
 $**xJ&GHHh LL& LL5 	-"4&$qax@DTF,W[WlWlWnVoopq		
A  (Gs9#=#=#D#DaffMNO s   AL 
M3A
M..M3c                     g r@   r   )r9   r   s     r)   set_name_hintVariableTracker.set_name_hint5  s    r(   c                     U $ )z=Used by LazyVariableTracker to build the real VariableTrackerr   rG   s    r)   r|   VariableTracker.realize8      r(   c                     U $ )zSUsed by LazyVariableTracker to return the real VariableTracker if it already existsr   rG   s    r)   r   VariableTracker.unwrap<  r!  r(   c                     g)z:Used by LazyVariableTracker to indicate an unrealized nodeTr   rG   s    r)   is_realizedVariableTracker.is_realized@  s    r(   c                 L    [        SSU  S3SU  S3/ [        R                  QS9  g )NzUnsupported next() callznext()z@Dynamo does not know how to trace calling `next()` on variable `z`.r2   )r   r   
USER_ERRORr   s     r)   next_variableVariableTracker.next_variableD  s6    -D6OZ[_Z``bc1%001		
r(   c                 J    UR                   =(       a    UR                  U 5      $ r@   )strict_checks_fnr   s     r)   is_strict_modeVariableTracker.is_strict_modeL  s    ""@r':':4'@@r(   c                 ,    U R                  5       (       + $ )z0Whether Dynamo allows mutation on this variable.)is_immutablerG   s    r)   
is_mutableVariableTracker.is_mutableO  s    $$&&&r(   c                     U R                   SL $ )z.Whether Dynamo bans mutation on this variable.N)r   rG   s    r)   r1  VariableTracker.is_immutableS  s    !!T))r(   r   r   c                     Uc  [         R                  R                  X5      $ [        R                  R                  X5      $ )z=Create a new VariableTracker from a value and optional Source)builderSourcelessBuilderr   r   r{   )r   r   r   s      r)   buildVariableTracker.buildW  s7     >,,33B>>0077FFr(   )r   r   r   c                   > [         TU ]  5         Xl        X l        UbD  [	        U[
        [        45      (       a  Ub   eg [	        U[        [        45      (       d   eUc   eg g r@   )	rA   r:   r   r   r   r=   rd   rR   r_   )r9   r   r   rC   s      r)   r:   VariableTracker.__init__c  sy     	* $-*:<P)QRR ~%~!!$9;T#U    ))) %r(   )r   r   r@   )r   r   rN   )r   zlist[VariableTracker]r   r  r.   rr   )r.   rr   )8r    r!   r"   r#   r$   r   r   classmethodr	   r   r
   r   intr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rW   r   r   r   r   r  r   r  r  r  r|   r   r%  r*  r.  r2  r1  staticmethodr   r9  r+   r:   r'   rO   rP   s   @r)   rr   rr      sV   N& 
 +/	/'($.// / S#X'	/
 
/ /B.# .G:$8
"
" 7 "s "s "
G5 
GS 
GEV 
G-	"".?)@ ",t4E/F ,T 04 0

c 

)
14
	

#
 ()
 -	

 

 W
 &	W

 -W
 
W
r
A'*  $(	G'	G	G  	G 
		G 	G &*	* * $	*
 
* *r(   rr   )	metaclassc                      [        U 5      S:X  a9  U u  n[        U[        5      (       a  [        U5      $ [	        U5      R
                  $ SR                  [        [        U 5      5      $ )Nr   r0   )	r  r   rr   r   rz   r    joinr  typestr)objsobjs     r)   rC  rC    sP    
4yA~c?++s8O9%%%xxGT*++r(   r   )r7  )3r$   r   collections.abcr   r   r   r   enumr   typingr   r	   r
   r    r   r   r   excr   r   r   r   r   r   r   r   utilsr   r   r   r   symbolic_convertr   r   r   r+   r=   rR   rZ   r_   rd   rk   rn   r   rp   rz   rw   rr   rC  r7  r   r(   r)   <module>rM     s     E E  9 9 + / < 0 ' 2 #S &- -`| ,'L ', . 1 . %, %"	< 	*= 7$ 7$Q* 3 Q*h, r(   