a
    h\                     @   s  d Z ddlZddlmZmZmZmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZ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rddlmZ d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*e$dd d!Z+G d"d# d#e,Z-G d$d% d%e.Z/G d&d' d'e/d(Z0d)d* Z1d+d,lm2Z2 dS )-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                   @   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      N)__name__
__module____qualname____doc__ExistingNew r"   r"   J/var/www/auris/lib/python3.9/site-packages/torch/_dynamo/variables/base.pyr   $   s   r   c                   @   s    e Zd ZdZedd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.
    N)typreturnc                 C   sV   |t ju rd| _n@|t ju r&t | _n,tdd|  d| d| ddgtjd d S )	Nr   zUnsupported SourceTypezMutationType.__init__  z"Dynamo does not support the type ``z,This branch is not supposed to be reachable.Zgb_typecontextZexplanationhints)r   r    scoper!   r   r   r   Z
DYNAMO_BUGselfr%   r"   r"   r#   __init__?   s    



zMutationType.__init__)r   r   r   r   r   r/   r"   r"   r"   r#   r$   7   s   r$   c                       s6   e Zd ZdZd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.
    Nr&   c                    s   t  tj d S N)superr/   r   r!   r.   	__class__r"   r#   r/   s   s    zValueMutationNew.__init__c                 C   s   t | S r2   )idr4   r"   r"   r#   __hash__v   s    zValueMutationNew.__hash__c                 C   s   | |u S r2   r"   )r.   otherr"   r"   r#   __eq__y   s    zValueMutationNew.__eq__)r   r   r   r   r/   r8   r:   __classcell__r"   r"   r5   r#   r0   g   s   r0   c                       s2   e Zd ZU dZeed< ded 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_modifiedF)r=   c                    s   t  tj || _d S r2   )r3   r/   r   r    r=   )r.   r=   r5   r"   r#   r/      s    zValueMutationExisting.__init__)F)r   r   r   r   bool__annotations__r/   r;   r"   r"   r5   r#   r<   }   s   
r<   c                       s&   e Zd ZdZed 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 r2   )r3   r/   r-   r5   r"   r#   r/      s    zAttributeMutation.__init__)r   r   r   r   r   r/   r;   r"   r"   r5   r#   r@      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                    s   t  tj d S r2   )r3   r/   r   r    r4   r5   r"   r#   r/      s    z"AttributeMutationExisting.__init__)r   r   r   r   r/   r;   r"   r"   r5   r#   rA      s   rA   c                       s,   e Zd ZdZdee d 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                    s   t  tj || _d S r2   )r3   r/   r   r!   rC   )r.   rC   r5   r"   r#   r/      s    zAttributeMutationNew.__init__)N)r   r   r   r   r	   r   r/   r;   r"   r"   r5   r#   rB      s   rB   c                 C   s   | dkS )Nr   r"   )scope_idr"   r"   r#   _is_top_level_scope   s    rE   )mc                 C   s   t  }t|rdS | j|kS )NT)r   rE   r,   )rF   rD   r"   r"   r#   is_side_effect_safe   s    rG   c                       s,   e Zd ZU ded< dd fddZ  ZS )#AsPythonConstantNotImplementedErrorVariableTrackervt)rJ   c                    s   t  | d || _d S )Nz is not a constant)r3   r/   rJ   )r.   rJ   r5   r"   r#   r/      s    z,AsPythonConstantNotImplementedError.__init__)r   r   r   r?   r/   r;   r"   r"   r5   r#   rH      s   
rH   c                       s4   e Zd Zg ZedddZdd fddZ  ZS )VariableTrackerMetar1   c                 C   s0   t |tju r$| ttjfvr$| }t | |S )z-Make isinstance work with LazyVariableTracker)typer   LazyVariableTrackerrI   realize__instancecheck__)clsinstancer"   r"   r#   rO      s
    z%VariableTrackerMeta.__instancecheck__Nc                    s    t  ||| tj|  d S r2   )r3   r/   rK   all_subclassesappend)rP   namebasesattrsr5   r"   r#   r/      s    zVariableTrackerMeta.__init__)r   r   r   rR   r>   rO   r/   r;   r"   r"   r5   r#   rK      s   
rK   c                       s  e Zd ZdZh dZdd ZedXed gdf ee	e
eef  ddddZed	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eedddZded dddZd d! Zd"d# Zd$d% Zd&d'd(d)Zed  d	d*d+Zed  d	d,d-Zed	d.d/Z ed	d0d1Z!dd	d2d3Z"ee d	d4d5Z#ded dd6d7Z$de%d  d8d d9d:d;Z&d<d8d d=d>d?Z'd@dA Z(d d	dBdCZ)d d	dDdEZ*dFdG Z+dHdI Z,dJdK Z-dLdM Z.dNdO Z/e0dYdPee	e1 edQdRdSZ2dddTe1e3ddU fdVdWZ4  Z5S )ZrI   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__().
    >   mutation_typevalueZparents_trackerguardssourceZuser_code_variable_namec                 K   s$   t | j}|| | jf i |S )z)Shallow copy with some (optional) changes)dict__dict__updater6   )r.   kwargsargsr"   r"   r#   clone   s    

zVariableTracker.cloneN)fnrX   cacher&   c                 C   s   |du ri }t |}||v r dS |||< t|tr|| }|| | }|j}|j D ]\}}||vrZ| ||| qZnTt|t	t
fr|D ]}| ||| qn,t|ttjfr| D ]}| ||| qdS )zM
        Walk value and call fn on all the VariableTracker instances
        N)r7   
isinstancerI   unwrap_nonvar_fieldsr\   itemsvisitr   listtupler[   collectionsOrderedDictvalues)rP   ra   rX   rb   idxZnonvarskeyZsubvaluer"   r"   r#   rg     s(    

zVariableTracker.visitr1   c                 C   s   | j j dS )Nz())r6   r   r4   r"   r"   r#   __repr__'  s    zVariableTracker.__repr__c                 C   s.   zt |  W S  ty(   t |  Y S 0 d S r2   )repras_python_constantNotImplementedErrorr4   r"   r"   r#   
debug_repr*  s    zVariableTracker.debug_reprc                 C   s6   zt |  W S  ty0   t|  ddY n0 dS )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)rL   rq   rr   r4   r"   r"   r#   python_type1  s    zVariableTracker.python_typec                 C   s&   z|   jW S  ty    Y dS 0 d S )Nz<unknown type>)rt   r   rr   r4   r"   r"   r#   python_type_nameN  s    z VariableTracker.python_type_namec                 C   s   t | dS )zFor constantsN)rH   r4   r"   r"   r#   rq   T  s    z"VariableTracker.as_python_constantc              	   C   s@   z
|   W S  ty:   tdd|  d|  dg d Y n0 dS )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.r)   N)rq   rr   r   r4   r"   r"   r#   guard_as_python_constantX  s    

z(VariableTracker.guard_as_python_constantc                 C   s(   z|    W dS  ty"   Y dS 0 d S NTF)rq   rr   r4   r"   r"   r#   is_python_constantd  s
    z"VariableTracker.is_python_constantc                 C   s   | j r| j |S td S r2   )rZ   
make_guardrr   )r.   ra   r"   r"   r#   ry   k  s    zVariableTracker.make_guardr   )txrT   r&   c                 C   s   t dS )z/getattr(self, name) returning a python constantNrr   r.   rz   rT   r"   r"   r#   const_getattrp  s    zVariableTracker.const_getattrc                 C   sR   |  ||}tj|st| jo,t| j|}|rBt|t	j
 tjj||dS )z,getattr(self, name) returning a new variable)rZ   )r}   r   ConstantVariableZ
is_literalrr   rZ   r   r   ry   r   ZCONSTANT_MATCHcreate)r.   rz   rT   rX   rZ   r"   r"   r#   var_getattrt  s    zVariableTracker.var_getattrc                 C   s(   z|    W dS  ty"   Y dS 0 d S rw   )as_proxyrr   r4   r"   r"   r#   is_proxy~  s
    zVariableTracker.is_proxyc                 C   s   t t| d S r2   )rr   strr4   r"   r"   r#   r     s    zVariableTracker.as_proxyc                 C   sF   z,|   }dd l}t||jjr(|jW S W d S  ty@   Y d S 0 d S )Nr   )r   Ztorch.fxrc   ZfxZProxynoderr   )r.   proxyZtorchr"   r"   r#   maybe_fx_node  s    zVariableTracker.maybe_fx_noder   )codegenc                 C   s   t d S r2   r{   )r.   r   r"   r"   r#   reconstruct  s    zVariableTracker.reconstructc                 C   s   t d S r2   r{   r.   rz   r"   r"   r#   unpack_var_sequence  s    z#VariableTracker.unpack_var_sequencec                 C   s
   |  |S r2   )r   r   r"   r"   r#   force_unpack_var_sequence  s    z)VariableTracker.force_unpack_var_sequencec                 C   s*   z|  | W dS  ty$   Y dS 0 d S rw   )r   rr   r   r"   r"   r#   has_unpack_var_sequence  s
    
z'VariableTracker.has_unpack_var_sequencec                 C   s
   |  |S r2   )r   r   r"   r"   r#   has_force_unpack_var_sequence  s    z-VariableTracker.has_force_unpack_var_sequencec                 C   s*   |  |sJ | |D ]}|| qd S r2   )r   r   )r.   rz   ra   vr"   r"   r#   force_apply_to_var_sequence  s    z+VariableTracker.force_apply_to_var_sequencec                 C   s&   t dd|  d|   dg d d S )NzUnsupported inspect callzinspect_parameter_names 0Dynamo does not know how to trace the function `r(   r)   r   rs   r4   r"   r"   r#   inspect_parameter_names  s    z'VariableTracker.inspect_parameter_namesc              	   C   sF   t dd|  d| d|   dd| jj d| dgtjd	 d S )
NzUnsupported hasattr callzcall_obj_hasattr r'   r   r(   zAvoid calling `hasattr(, z)` in your code.r)   )r   rs   r6   r   r   ZSUPPORTABLEr|   r"   r"   r#   call_obj_hasattr  s    z VariableTracker.call_obj_hasattrzdict[str, VariableTracker])rz   r_   r^   r&   c                 C   sB   t dd|  d| d| d|   dd|   ddgd	 d S )
NzUnsupported function callzcall_function r'   r   r(   Avoid calling `` in your code."Please report an issue to PyTorch.r)   r   )r.   rz   r_   r^   r"   r"   r#   call_function  s    zVariableTracker.call_functionzlist[VariableTracker])r_   r^   r&   c              
   C   s8  |dkr4|  |r4|s|rJ tjt| |S |dkrlt|dkrl|d  rl|sl| ||d  S |t	v rt|dkr|s|d }t
| t|st
| tjst
|tjstjtS |  r| r|jj| s|jj|r4tdd|  d| d| d| d|  d	| d
d| d g d z tjt	| |  | W S  ty } z0tt||tttjj|jgd W Y d }~n
d }~0 0 d|   d| ddg}t
| tjr|dv rt
| jtttfr|d |d tdd|  d| d| d| d| d|   d|d d S )N__len____getattr__r   r   z;Builtin `operator.*` comparison with constant `self` failedzcall_method r'   zFailed to compare z with r   zbecause z6 is not a Python constant or its mutation check fails.r)   )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.zUnsupported method callz*Dynamo does not know how to trace method `z` of class `r(   )r   r   r~   r   lenr   rx   r   rq   r   rc   rL   ZGetAttrVariableNotImplementedoutputZside_effectsZhas_pending_mutationr   	Exceptionr   rh   mapr_   ru   ZUserDefinedObjectVariablerX   r   r   r   rS   )r.   rz   rT   r_   r^   r9   er+   r"   r"   r#   call_method  s    




zVariableTracker.call_methodc                 C   s   d S r2   r"   )r.   rT   r"   r"   r#   set_name_hint-  s    zVariableTracker.set_name_hintc                 C   s   | S )z=Used by LazyVariableTracker to build the real VariableTrackerr"   r4   r"   r"   r#   rN   0  s    zVariableTracker.realizec                 C   s   | S )zSUsed by LazyVariableTracker to return the real VariableTracker if it already existsr"   r4   r"   r"   r#   rd   4  s    zVariableTracker.unwrapc                 C   s   dS )z:Used by LazyVariableTracker to indicate an unrealized nodeTr"   r4   r"   r"   r#   is_realized8  s    zVariableTracker.is_realizedc                 C   s*   t dd|  dd|  dg tjd d S )NzUnsupported next() callznext()z@Dynamo does not know how to trace calling `next()` on variable `z`.r)   )r   r   Z
USER_ERRORr   r"   r"   r#   next_variable<  s    

zVariableTracker.next_variablec                 C   s   |j o| | S r2   )Zstrict_checks_fnr   r"   r"   r#   is_strict_modeD  s    zVariableTracker.is_strict_modec                 C   s
   |    S )z0Whether Dynamo allows mutation on this variable.)is_immutabler4   r"   r"   r#   
is_mutableG  s    zVariableTracker.is_mutablec                 C   s
   | j du S )z.Whether Dynamo bans mutation on this variable.N)rW   r4   r"   r"   r#   r   K  s    zVariableTracker.is_immutabler   )rz   rX   rZ   r&   c                 C   s(   |du rt j| |S tj||S dS )z=Create a new VariableTracker from a value and optional SourceN)builderZSourcelessBuilderr   r   rM   )rz   rX   rZ   r"   r"   r#   buildO  s    zVariableTracker.build)rZ   rW   )rZ   rW   r&   c                   s\   t    || _|| _|d urXt|ttfr:|d u sXJ nt|ttfsLJ |d usXJ d S r2   )	r3   r/   rZ   rW   rc   r0   rB   r<   rA   )r.   rZ   rW   r5   r"   r#   r/   [  s    
zVariableTracker.__init__)N)N)6r   r   r   r   re   r`   classmethodr   r   r	   r[   intrg   r   ro   rs   rt   ru   rq   rv   rx   ry   r}   r   r   r   r   r   rh   r   r   r>   r   r   r   r   r   r   r   r   r   rN   rd   r   r   r   r   r   staticmethodr   r   r$   r/   r;   r"   r"   r5   r#   rI      s   
	 !
		S rI   )	metaclassc                  G   sD   t | dkr0| \}t|tr$t|S t|jS ndtt| S d S )Nr   r'   )	r   rc   rI   r   rL   r   joinr   typestr)objsobjr"   r"   r#   r   w  s    
r   r   )r   )3r   rj   collections.abcr   r   r   r   enumr   typingr   r   r	   r
    r   r   r   excr   r   rY   r   r   rZ   r   r   utilsr   r   r   r   Zsymbolic_convertr   r   r   r$   r0   r<   r@   rA   rB   rE   rG   rr   rH   rL   rK   rI   r   r   r"   r"   r"   r#   <module>   s<   0
   