
    Vh\P                        d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZmZ ddlmZmZ e
rddlmZmZ  G d de      Z G d d      Z G d de      Z G d de      Z  G d de      Z! G d de!      Z" G d de!      Z#d Z$defdZ% G d  d!e&      Z' G d" d#e(      Z) G d$ d%e)&      Z*d' Z+dd(lm,Z, y))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)Sequence)Enum)AnyCallableOptionalTYPE_CHECKING   )	variables)current_scope_id)unimplementedunimplemented_v2)GuardBuilderinstall_guard)
AttrSourceSource)cmp_name_to_op_mappingistype   )InstructionTranslatorInstructionTranslatorBasec                       e Zd ZdZdZdZy)
SourceTypea  
    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   r   N)__name__
__module____qualname____doc__ExistingNew     L/home/dcms/DCMS/lib/python3.12/site-packages/torch/_dynamo/variables/base.pyr   r   #   s     H
Cr    r   c                        e Zd ZdZdeddfdZy)MutationTypez
    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                     |t         j                  u rd| _        y |t         j                  u rt	               | _        y t        d|        y )Nr   zUnsupported SourceType: )r   r   scoper   r   r   )selfr$   s     r!   __init__zMutationType.__init__>   s?    0 *%%%DJJNN")+DJ4SE:;r    )r   r   r   r   r   r)   r   r    r!   r#   r#   6   s    <J <4 <r    r#   c                   0     e Zd ZdZd fdZd Zd Z xZS )ValueMutationNewa  
    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         |   t        j                         y N)superr)   r   r   r(   	__class__s    r!   r)   zValueMutationNew.__init__j   s    (r    c                     t        |       S r-   )idr(   s    r!   __hash__zValueMutationNew.__hash__m   s    $xr    c                 
    | |u S r-   r   )r(   others     r!   __eq__zValueMutationNew.__eq__p   s    u}r    r%   N)r   r   r   r   r)   r4   r7   __classcell__r0   s   @r!   r+   r+   ^   s    	)r    r+   c                   6     e Zd ZU dZeed<   ddef fdZ xZS )ValueMutationExistinga  
    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                 N    t         |   t        j                         || _        y r-   )r.   r)   r   r   r=   )r(   r=   r0   s     r!   r)   zValueMutationExisting.__init__   s    ,,-&r    )F)r   r   r   r   bool__annotations__r)   r9   r:   s   @r!   r<   r<   t   s!    	 'D ' 'r    r<   c                   (     e Zd ZdZdef fdZ xZS )AttributeMutationz
    This case of VariableTracker.mutation_type marker indicates that Dynamo
    allows mutation on the value's attributes.
    r$   c                 $    t         |   |       y r-   )r.   r)   )r(   r$   r0   s     r!   r)   zAttributeMutation.__init__   s    r    )r   r   r   r   r   r)   r9   r:   s   @r!   rB   rB      s    
J  r    rB   c                   "     e Zd ZdZ fdZ xZS )AttributeMutationExistinga  
    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         |   t        j                         y r-   )r.   r)   r   r   r/   s    r!   r)   z"AttributeMutationExisting.__init__   s    ,,-r    )r   r   r   r   r)   r9   r:   s   @r!   rE   rE      s    	. .r    rE   c                   0     e Zd ZdZddee   f fdZ xZS )AttributeMutationNewa  
    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                 N    t         |   t        j                         || _        y r-   )r.   r)   r   r   rI   )r(   rI   r0   s     r!   r)   zAttributeMutationNew.__init__   s    ($r    r-   )r   r   r   r   r   r   r)   r9   r:   s   @r!   rH   rH      s    	%8F#3 % %r    rH   c                     | dk(  S )Nr   r   )scope_ids    r!   _is_top_level_scoperM      s    q=r    mc                 L    t               }t        |      ry| j                  |k(  S )NT)r   rM   r'   )rN   rL   s     r!   is_side_effect_saferP      s&    !H
 8$77hr    c                   ,     e Zd ZU ded<   d fdZ xZS )#AsPythonConstantNotImplementedErrorVariableTrackervtc                 :    t         |   | | d       || _        y )Nz is not a constant)r.   r)   rT   )r(   rT   r0   s     r!   r)   z,AsPythonConstantNotImplementedError.__init__   s!    "%789r    )rT   rS   )r   r   r   r@   r)   r9   r:   s   @r!   rR   rR      s     r    rR   c                   0     e Zd Zg ZdefdZd fdZ xZS )VariableTrackerMetar%   c                     t        |      t        j                  u r(| t        t        j                  fvr|j	                         }t         j                  | |      S )z-Make isinstance work with LazyVariableTracker)typer
   LazyVariableTrackerrS   realize__instancecheck__)clsinstances     r!   r\   z%VariableTrackerMeta.__instancecheck__   sJ     Ni;;;)F)FGG'')H%%c844r    c                 f    t         |   |||       t        j                  j	                  |        y r-   )r.   r)   rW   all_subclassesappend)r]   namebasesattrsr0   s       r!   r)   zVariableTrackerMeta.__init__   s(    ue,**11#6r    r8   )r   r   r   r`   r?   r\   r)   r9   r:   s   @r!   rW   rW      s    N5D 57 7r    rW   c                       e Zd ZdZh dZd Ze	 d4ded gdf   dede	e
eef      ddfd	       Zdefd
Zd Zd Zd Zd Zd Zd Zd ZdddedefdZdddedd fdZd Zd Zd Zd Zded    fdZded    fdZdefdZ defdZ!dee   fdZ"dddedd fd Z#ddd!e$d    d"d#dd fd$Z%	 	 	 	 	 	 d5d%Z&d& Z'd6d'Z(d6d(Z)d) Z*d* Z+d+ Z,d, Z-d- Z.e/	 d4dd.ded/e	e0   defd0       Z1ddd1d/e0d2e2ddf fd3Z3 xZ4S )7rS   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    t        | j                        }|j                  |        | j                  di |S )z)Shallow copy with some (optional) changesr   )dict__dict__updater0   )r(   kwargsargss      r!   clonezVariableTracker.clone   s0    DMM"Ft~~%%%r    Nfnrf   cacher%   c                 (   |i }t        |      }||v ry|||<   t        |t              ro|j                         } ||       |j                         }|j                  }|j
                  j                         D ]  \  }}||vs| j                  |||        yt        |t        t        f      r|D ]  }| j                  |||        yt        |t        t        j                  f      r)|j                         D ]  }| j                  |||        yy)zM
        Walk value and call fn on all the VariableTracker instances
        N)r2   
isinstancerS   unwrap_nonvar_fieldsrn   itemsvisitr   listtuplerm   collectionsOrderedDictvalues)r]   rs   rf   rt   idxnonvarskeysubvalues           r!   rz   zVariableTracker.visit   s    =Ei%<c
e_-LLNEuILLNE**G!&!5!5!7 3Xg%IIb(E23 ED%=)! /		"h./ED+"9"9:;!LLN /		"h./ <r    c                 4    | j                   j                   dS )Nz())r0   r   r3   s    r!   __repr__zVariableTracker.__repr__  s    ..))*"--r    c                 j    	 t        | j                               S # t        $ r t        |       cY S w xY wr-   )repras_python_constantNotImplementedErrorr3   s    r!   
debug_reprzVariableTracker.debug_repr!  s4    	//122" 	:	s    22c                 n    	 t        | j                               S # t        $ r t        |  d      dw xY w)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)rY   r   r   r3   s    r!   python_typezVariableTracker.python_type(  sA    0	G//122" 	G%l&;<$F	Gs    4c                 V    	 | j                         j                  S # t        $ r Y yw xY w)Nz<unknown type>)r   r   r   r3   s    r!   python_type_namez VariableTracker.python_type_nameE  s.    	$##%..." 	$#	$s    	((c                     t        |       )zFor constants)rR   r3   s    r!   r   z"VariableTracker.as_python_constantK  s    1$77r    c                 x    	 | j                         S # t        $ r}t        t        |             Y d}~yd}~ww xY w)zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsN)r   r   r   str)r(   es     r!   guard_as_python_constantz(VariableTracker.guard_as_python_constantO  s5    	"**,," 	"#a&!!	"s    	949c                 D    	 | j                          y# t        $ r Y yw xY wNTF)r   r   r3   s    r!   is_python_constantz"VariableTracker.is_python_constantV  s(    	##%" 		    	c                 \    | j                   r| j                   j                  |      S t        r-   )rh   
make_guardr   )r(   rs   s     r!   r   zVariableTracker.make_guard]  s$    ;;;;))"--!!r    txr   rb   c                     t         )z/getattr(self, name) returning a python constantr   r(   r   rb   s      r!   const_getattrzVariableTracker.const_getattrb  s    !!r    c                 N   | j                  ||      }t        j                  j                  |      st        | j
                  xr t        | j
                  |      }|r(t        |j                  t        j                               t        j                  j                  ||      S )z,getattr(self, name) returning a new variable)rh   )r   r
   ConstantVariable
is_literalr   rh   r   r   r   r   CONSTANT_MATCHcreate)r(   r   rb   rf   rh   s        r!   var_getattrzVariableTracker.var_getattrf  s    ""2t,))44U;%%>DKK!>&++L,G,GHI))00v0FFr    c                 D    	 | j                          y# t        $ r Y yw xY wr   )as_proxyr   r3   s    r!   is_proxyzVariableTracker.is_proxyp  s%    	MMO" 		r   c                 *    t        t        |             r-   )r   r   r3   s    r!   r   zVariableTracker.as_proxyw  s    !#d),,r    c                     	 | j                         }dd l}t        ||j                  j                        r|j
                  S y # t        $ r Y y w xY w)Nr   )r   torch.fxrv   fxProxynoder   )r(   proxytorchs      r!   maybe_fx_nodezVariableTracker.maybe_fx_nodez  sF    	MMOE%0zz!" 		s   ?A 	AAc                     t         r-   r   )r(   codegens     r!   reconstructzVariableTracker.reconstruct      !!r    c                     t         r-   r   r(   r   s     r!   unpack_var_sequencez#VariableTracker.unpack_var_sequence  r   r    c                 $    | j                  |      S r-   )r   r   s     r!   force_unpack_var_sequencez)VariableTracker.force_unpack_var_sequence  s     ''++r    c                 F    	 | j                  |       y# t        $ r Y yw xY wr   )r   r   r   s     r!   has_unpack_var_sequencez'VariableTracker.has_unpack_var_sequence  s*    	$$R(" 		s    	  c                 $    | j                  |      S r-   )r   r   s     r!   has_force_unpack_var_sequencez-VariableTracker.has_force_unpack_var_sequence  s    ++B//r    c                      t        d|         y )Nzinspect_parameter_names: r   r3   s    r!   inspect_parameter_namesz'VariableTracker.inspect_parameter_names  s    1$89r    c                 N    t        d| j                  j                   d|        y )Nzhasattr  )r   r0   r   r   s      r!   call_obj_hasattrz VariableTracker.call_obj_hasattr  s$     	!8!8 94&ABr    rq   rp   dict[str, VariableTracker]c           	          t        dd|  d| d| d| j                          dd| j                          ddg	       y )
NzUnsupported function callzcall_function r   z0Dynamo does not know how to trace the function ``Avoid calling `` in your code."Please report an issue to PyTorch.gb_typecontextexplanationhints)r   r   )r(   r   rq   rp   s       r!   call_functionzVariableTracker.call_function  sV     	/$TF!D66(;J4??K\J]]^_!$//"3!4OD4		
r    c                 p   |dk(  rN| j                  |      r=|s|rJ t        j                  j                  t	        | j                  |                  S |dk(  rFt	        |      dk(  r8|d   j                         r%|s#| j                  ||d   j                               S |t        v rt	        |      dk(  r| j                         r|j                  j                  j                  |       s|s|d   }t        | t        |            s#t        j                  j                  t              S |j                         r%|j                  j                  j                  |      rt!        d|  d| d| d|        t        j                  j                  t        |   | j                         |j                                     S d| j#                          d| d	d
g}t        | t        j$                        r|dv r|j'                  d       t)        dd|  d| d| d| d| d| j#                          d|       y )N__len____getattr__r   r   zcall_method r   r   .r   r   )__iter____next__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.zUnsupported method callz*Dynamo does not know how to trace method `z` of class `r   r   )r   r
   r   r   lenr   r   r   r   r   outputside_effectshas_pending_mutationrv   rY   NotImplementedr   r   UserDefinedObjectVariablera   r   )r(   r   rb   rq   rp   r6   r   s          r!   call_methodzVariableTracker.call_method  s$    9!=!=b!A''--44S9Q9QRT9U5VWWM!D	QQ**,##BQ(B(B(DEE**D	Q'')II**??E GEdDK0 1188HH,,.99))>>uETF!D64&&JK--44&t,++-u/G/G/I  d3356av_M0

 dI??@T N
 F
 LL& 	-"4&$qax@DTF,W[WlWlWnVoopq		
r    c                      y r-   r   )r(   rb   s     r!   set_name_hintzVariableTracker.set_name_hint  s    r    c                     | S )z=Used by LazyVariableTracker to build the real VariableTrackerr   r3   s    r!   r[   zVariableTracker.realize      r    c                     | S )zSUsed by LazyVariableTracker to return the real VariableTracker if it already existsr   r3   s    r!   rw   zVariableTracker.unwrap  r   r    c                      y)z:Used by LazyVariableTracker to indicate an unrealized nodeTr   r3   s    r!   is_realizedzVariableTracker.is_realized   s    r    c                 "    t        d|  d       y )Nznext()r   r   s     r!   next_variablezVariableTracker.next_variable  s    dV1o&r    c                 @    |j                   xr |j                  |       S r-   )strict_checks_fnr   s     r!   is_strict_modezVariableTracker.is_strict_mode  s    ""@r':':4'@@r    c                 $    | j                          S )z0Whether Dynamo allows mutation on this variable.)is_immutabler3   s    r!   
is_mutablezVariableTracker.is_mutable
  s    $$&&&r    c                     | j                   du S )z.Whether Dynamo bans mutation on this variable.N)ri   r3   s    r!   r   zVariableTracker.is_immutable  s    !!T))r    r   rh   c                 ~    | t         j                  j                  | |      S  t        j                  | |      |      S )z=Create a new VariableTracker from a value and optional Source)builderSourcelessBuilderr   VariableBuilder)r   rf   rh   s      r!   buildzVariableTracker.build  s<     >,,33B>>67**2v6u==r    )rh   ri   ri   c                    t         |           || _        || _        |8t	        |t
        t        f      r|J y t	        |t        t        f      sJ |J y y r-   )	r.   r)   rh   ri   rv   r+   rH   r<   rE   )r(   rh   ri   r0   s      r!   r)   zVariableTracker.__init__  su     	* $-*:<P)QR ~%~!!$9;T#U   ))) %r    r-   )rq   zlist[VariableTracker]rp   r   r%   rS   )r%   rS   )5r   r   r   r   rx   rr   classmethodr   r   r   rm   intrz   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[   rw   r   r   r   r   r   staticmethodr   r   r#   r)   r9   r:   s   @r!   rS   rS      sK   N& 
 +/	/'($.// / S#X'	/
 
/ /B.# .G:$8""
" 7 "s "s "G5 GS GEV G-	"".?)@ ",t4E/F ,T 04 0:c :C)C14C	C

#
 ()
 -	

 

 <
 &	<

 -<
 
<
|'A'*  $(	>'	>	>  	> 
		> 	> &*	* * $	*
 
* *r    rS   )	metaclassc                      t        |       dk(  r4| \  }t        |t              rt        |      S t	        |      j
                  S dj                  t        t        |             S )Nr   r   )	r   rv   rS   r   rY   r   joinmaptypestr)objsobjs     r!   r   r   :  sM    
4yA~c?+s8O9%%%xxGT*++r    )r   )-r   r}   collections.abcr   enumr   typingr   r   r   r    r
   r   excr   r   rg   r   r   rh   r   r   utilsr   r   symbolic_convertr   r   r   r#   r+   r<   rB   rE   rH   rM   rP   r   rR   rY   rW   rS   r   r   r   r    r!   <module>r     s     $  9 9  / 1 0 ' 2 R &%< %<P| ,'L ', . 1 . %, %"	< 	*= 7$ 7$U* 3 U*p
, r    