o
    ߗi5B                     @   sJ  d dl Z d dlmZ d dlmZmZmZmZmZm	Z	 ddl
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 e	rLddlmZmZ G dd deZG dd dZG dd deZG dd deZG dd deZG dd deZG dd deZ dd Z!defddZ"G d d! d!e#Z$G d"d# d#e$d$Z%d%d& Z&dS )'    N)Enum)AnyCallableDictListOptionalTYPE_CHECKING   )	variables)current_scope_idunimplemented)GuardBuilderinstall_guard)
AttrSourceSource)istype   )InstructionTranslatorInstructionTranslatorBasec                   @   s   e Zd ZdZdZdZdS )
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 r   r   Z/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/torch/_dynamo/variables/base.pyr      s    r   c                   @   s"   e Zd ZdZdeddfddZdS )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                 C   s<   |t ju r
d| _d S |t ju rt | _d S td|  d S )Nr   zUnsupported SourceType: )r   r   scoper   r   r   selfr    r   r   r   __init__.   s
   


zMutationType.__init__)r   r   r   r   r   r%   r   r   r   r   r   &   s    r   c                       s2   e Zd ZdZd
 fddZdd Zdd	 Z  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.
    r!   Nc                       t  tj d S N)superr%   r   r   r$   	__class__r   r   r%   Z      zValueMutationNew.__init__c                 C   s   t | S r(   )idr*   r   r   r   __hash__]      zValueMutationNew.__hash__c                 C   s   | |u S r(   r   )r$   otherr   r   r   __eq__`   r0   zValueMutationNew.__eq__r!   N)r   r   r   r   r%   r/   r2   __classcell__r   r   r+   r   r&   N   s
    r&   c                       s2   e Zd ZU dZeed< ddef fddZ  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_modifiedFc                       t  tj || _d S r(   )r)   r%   r   r   r6   )r$   r6   r+   r   r   r%   u      
zValueMutationExisting.__init__)F)r   r   r   r   bool__annotations__r%   r4   r   r   r+   r   r5   d   s   
 r5   c                       s&   e Zd ZdZdef fddZ  ZS )AttributeMutationz
    This case of VariableTracker.mutation_type marker indicates that Dynamo
    allows mutation on the value's attributes.
    r    c                    s   t  | d S r(   )r)   r%   r#   r+   r   r   r%         zAttributeMutation.__init__)r   r   r   r   r   r%   r4   r   r   r+   r   r;   z   s    r;   c                       s    e Zd ZdZ fddZ  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                    r'   r(   )r)   r%   r   r   r*   r+   r   r   r%      r-   z"AttributeMutationExisting.__init__)r   r   r   r   r%   r4   r   r   r+   r   r=      s    r=   c                       s,   e Zd ZdZddee f fddZ  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.
    N
cls_sourcec                    r7   r(   )r)   r%   r   r   r?   )r$   r?   r+   r   r   r%      r8   zAttributeMutationNew.__init__r(   )r   r   r   r   r   r   r%   r4   r   r   r+   r   r>      s     r>   c                 C   s   | dkS )Nr   r   )scope_idr   r   r   _is_top_level_scope   r0   rA   mc                 C   s   t  }t|r	dS | j|kS )NT)r   rA   r"   )rB   r@   r   r   r   is_side_effect_safe   s   
rC   c                       s0   e Zd Zg ZdefddZd fddZ  ZS )VariableTrackerMetar!   c                 C   s0   t tj|r| ttjfvr| }t | |S )z-Make isinstance work with LazyVariableTracker)type__instancecheck__r
   LazyVariableTrackerVariableTrackerrealize)clsinstancer   r   r   rF      s   z%VariableTrackerMeta.__instancecheck__Nc                    s    t  ||| tj|  d S r(   )r)   r%   rD   all_subclassesappend)rJ   namebasesattrsr+   r   r   r%      s   zVariableTrackerMeta.__init__r3   )r   r   r   rL   r9   rF   r%   r4   r   r   r+   r   rD      s    rD   c                       s
  e Zd ZdZh dZdd Ze	dUded gdf dede	e
eef  d	dfd
dZd	efddZdd Zdd Zdd Zdd Zdd Zdd Zddded	efddZddded	d fdd Zd!d" Zd#d$ Zd%d& Zd'd( Zd	ed  fd)d*Zd	ed  fd+d,Zd	efd-d.Zd	efd/d0Z d	ee fd1d2Z!ddded	d fd3d4Z"			5	6	7	8			 dVd9d:Z#	5	6	7	8			 dWd;d<Z$d=d> Z%dXd?d@Z&dXdAdBZ'dCdD Z(dEdF Z)dGdH Z*dIdJ Z+dKdL Z,e-	dUddMdedNe	e. d	efdOdPZ/dddQdNe.dRe0d	df fdSdTZ1  Z2S )YrH   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                 K   s$   t | j}|| | jdi |S )z)Shallow copy with some (optional) changesNr   )dict__dict__updater,   )r$   kwargsargsr   r   r   clone   s   

zVariableTracker.cloneNfnrQ   cacher!   c                 C   s   |du ri }t |}||v rdS |||< t|tr?| }|| | }|j}|j D ]\}}||vr<| ||| q-dS t|t	t
frT|D ]	}| ||| qHdS t|ttjfrj| D ]}| ||| q`dS dS )zM
        Walk value and call fn on all the VariableTracker instances
        N)r.   
isinstancerH   unwrap_nonvar_fieldsrX   itemsvisitr   listtuplerW   collectionsOrderedDictvalues)rJ   r]   rQ   r^   idxnonvarskeysubvaluer   r   r   rc      s2   

zVariableTracker.visitc                 C   s   | j j dS )Nz())r,   r   r*   r   r   r   __repr__  s   zVariableTracker.__repr__c                 C   s*   zt |  W S  ty   t |  Y S w r(   )repras_python_constantNotImplementedErrorr*   r   r   r   
debug_repr  s
   zVariableTracker.debug_reprc                 C   s.   zt |  W S  ty   t|  dd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)rE   ro   rp   r*   r   r   r   python_type  s
   zVariableTracker.python_typec                 C   s   t |  d)zFor constantsz is not a constantrp   r*   r   r   r   ro   +  s   z"VariableTracker.as_python_constantc              
   C   s>   z|   W S  ty } ztt| W Y d}~dS d}~ww )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsN)ro   rp   r   str)r$   er   r   r   guard_as_python_constant/  s   
z(VariableTracker.guard_as_python_constantc                 C   $   z|    W dS  ty   Y dS w NTF)ro   rp   r*   r   r   r   is_python_constant6     z"VariableTracker.is_python_constantc                 C   s   | j r	| j |S tr(   )rS   
make_guardrp   )r$   r]   r   r   r   r{   =  s   zVariableTracker.make_guardtxr   rN   c                 C      t )z/getattr(self, name) returning a python constantrs   r$   r|   rN   r   r   r   const_getattrB     zVariableTracker.const_getattrc                 C   sR   |  ||}tj|st| jot| j|}|r!t|t	j
 tjj||dS )z,getattr(self, name) returning a new variable)rS   )r   r
   ConstantVariable
is_literalrp   rS   r   r   r{   r   CONSTANT_MATCHcreate)r$   r|   rN   rQ   rS   r   r   r   var_getattrF  s   zVariableTracker.var_getattrc                 C   rw   rx   )as_proxyrp   r*   r   r   r   is_proxyP  rz   zVariableTracker.is_proxyc                 C   s   t t| r(   )rp   rt   r*   r   r   r   r   W  s   zVariableTracker.as_proxyc                 C   sB   z|   }dd l}t||jjr|jW S W d S  ty    Y d S w )Nr   )r   torch.fxr_   fxProxynoderp   )r$   proxytorchr   r   r   maybe_fx_nodeZ  s   zVariableTracker.maybe_fx_nodec                 C   r}   r(   rs   )r$   codegenr   r   r   reconstructe     zVariableTracker.reconstructc                 C   r}   r(   rs   r$   r|   r   r   r   unpack_var_sequenceh  r   z#VariableTracker.unpack_var_sequencec                 C   
   |  |S r(   )r   r   r   r   r   force_unpack_var_sequencek  s   
z)VariableTracker.force_unpack_var_sequencec                 C   s&   z|  | W dS  ty   Y dS w rx   )r   rp   r   r   r   r   has_unpack_var_sequencet  s   
z'VariableTracker.has_unpack_var_sequencec                 C   r   r(   )r   r   r   r   r   has_force_unpack_var_sequence|  s   
z-VariableTracker.has_force_unpack_var_sequencec                 C   s   t d|   d S )Nzinspect_parameter_names: r   r*   r   r   r   inspect_parameter_names  r-   z'VariableTracker.inspect_parameter_namesc                 C   s   t d| jj d|  d S )Nzhasattr  )r   r,   r   r~   r   r   r   call_hasattr  s   zVariableTracker.call_hasattrr[   List[VariableTracker]rZ   Dict[str, VariableTracker]c                 C   s   t d|  d| d|  d S )Nzcall_function r   r   )r$   r|   r[   rZ   r   r   r   call_function  s   zVariableTracker.call_functionc              	   C   s   |dkr|  |r|s|rJ tjt| |S |dkr6t|dkr6|d  r6|s6| ||d  S t	d|  d| d| d|  d S )N__len____getattr__r   r   zcall_method r   )
r   r
   r   r   lenr   ry   r   ro   r   )r$   r|   rN   r[   rZ   r   r   r   call_method  s   
$zVariableTracker.call_methodc                 C   s   d S r(   r   )r$   rN   r   r   r   set_name_hint  r   zVariableTracker.set_name_hintc                 C      | S )z=Used by LazyVariableTracker to build the real VariableTrackerr   r*   r   r   r   rI     r   zVariableTracker.realizec                 C   r   )zSUsed by LazyVariableTracker to return the real VariableTracker if it already existsr   r*   r   r   r   r`     r   zVariableTracker.unwrapc                 C   s   dS )z:Used by LazyVariableTracker to indicate an unrealized nodeTr   r*   r   r   r   is_realized  r   zVariableTracker.is_realizedc                 C   s   t d|  d d S )Nznext()r   r   r   r   r   next_variable  s   zVariableTracker.next_variablec                 C   s   |j o| | S r(   )strict_checks_fnr   r   r   r   is_strict_mode  r<   zVariableTracker.is_strict_modec                 C   s
   |    S )z0Whether Dynamo allows mutation on this variable.)is_immutabler*   r   r   r   
is_mutable     
zVariableTracker.is_mutablec                 C   s
   | j du S )z.Whether Dynamo bans mutation on this variable.N)rT   r*   r   r   r   r     r   zVariableTracker.is_immutabler   rS   c                 C   s2   ddl m} |du r|j| |S || ||S )z=Create a new VariableTracker from a value and optional Sourcer   )builderN) r   SourcelessBuilderr   VariableBuilder)r|   rQ   rS   r   r   r   r   build  s   zVariableTracker.build)rS   rT   rT   c                   sb   t    || _|| _|d ur-t|ttfr|d u sJ d S t|ttfs'J |d us/J d S d S r(   )	r)   r%   rS   rT   r_   r&   r>   r5   r=   )r$   rS   rT   r+   r   r   r%     s   
zVariableTracker.__init__r(   )r|   r   r[   r   rZ   r   r!   rH   )r[   r   rZ   r   r!   rH   )r!   rH   )3r   r   r   r   ra   r\   classmethodr   r   r   r   intrc   rt   rm   rq   rr   ro   rv   ry   r{   r   r   r   r   r   r   r   r   r   r9   r   r   r   r   r   r   r   rI   r`   r   r   r   r   r   staticmethodr   r   r   r%   r4   r   r   r+   r   rH      s    
	!
	



rH   )	metaclassc                  G   s>   t | dkr| \}t|trt|S t|jS dtt| S )Nr   r   )	r   r_   rH   rt   rE   r   joinmaptypestr)objsobjr   r   r   r     s   

r   )'rf   enumr   typingr   r   r   r   r   r   r   r
   r   excr   rR   r   r   rS   r   r   utilsr   symbolic_convertr   r   r   r   r&   r5   r;   r=   r>   rA   rC   rE   rD   rH   r   r   r   r   r   <module>   s2    (
  !