o
    ei                    @  s,  U d Z 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ZddlZddlZddlZddlZddlmZ ddlmZmZmZmZmZmZmZ ddl m!Z! ddl"Z"ddl#Z"ddl$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l0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7mZ8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO ddlPmPZP ddlQmRZR ddl6mSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ ddl\m]Z] ddl^m_Z_m`Z` ddlambZbmcZcmdZd ddlemfZfmgZgmhZhmiZimjZj ddlkmlZlmmZm ddlnmoZompZpmqZqmrZr ddlsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{ ddl9m|Z|m}Z} ddl~mZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZmZ ddlmZ dd lmZmZ dd!lmZmZmZmZ dd"lmZmZ dd#lmZmZmZmZmZmZmZ dd$lmZ dd%lmZ dd&lmZmZmZmZmZmZ dd'lmZmZmZmZmZmZmZ dd(lmZmZ dd)lmZ dd*lmZmZ dd+lmZmZ dd,lmZmZmZmZmZ er2dd-lmZmZmZ dd.lmZ dd/lmZ eeѡZe"jӠed0Ze"jӠed1Ze"jӠed2Ze"jӠed3Ze١ Zd4d5 eۡ D Zd6ed7< eejރjZeejjZd8d9 ed:< d;d9 ed<< ee:jeef Zd=ed>< e	jddCdDZejG dEdF dFZejG dGdH dHZejG dIdJ dJZejG dKdL dLZG dMdN dNZe	jddPdQZejddUdVZejddWdXZejG dYdZ dZZG d[d\ d\eZG d]d^ d^eZG d_d` d`eZddddeZddidjZe	jddmdnZe	jddodpZe	jddrdsZejG dtdu duZddzd{Zd|Zdd~dZdddZdddZ G dd deZejG dd dZG ddS dSedZG dd deZejdkrwdd ejD ZejdddZ	G dd deZ
G dd de
ZdS )a  
Core module responsible for converting Python bytecode into TorchDynamo's symbolic execution format.

This module implements the bytecode-level tracing system that allows TorchDynamo to analyze
and transform Python code. It converts Python bytecode instructions into a symbolic format
that tracks the flow of tensors and other values through the program.

Key components:
- InstructionTranslatorBase: Base class for converting bytecode to symbolic execution
- InstructionTranslator: Main translator for function bytecode
- InliningInstructionTranslator: Handles inlining of called functions
- SpeculationLog: Manages state for speculative execution and rollback

The symbolic conversion process handles:
- Control flow (loops, conditionals, etc.)
- Function inlining and call stack management
- Tracking of program values and side effects
- Graph breaks and resumption points
- Exception handling and stack frame management

This is a core part of TorchDynamo's tracing system that enables ahead-of-time
optimization of PyTorch programs.
    )annotationsN)deque)AnycastNoReturnOptionalTYPE_CHECKING	TypeAliasUnion)TypeIs)DynamoProfilerStateFunctionTraceTiming)ObservedExceptionTensorifyScalarRestartAnalysis)InlinedCodeCachetracingTracingContext)	dump_file)
guard_bool)cache_method   )configexcgraph_break_hintsloggingtrace_rules	variables)get_indexofJUMP_OPNAMESlivevars_analysispropagate_line_nums)cleaned_instructionscreate_binary_slicecreate_call_functioncreate_call_function_excreate_copycreate_dup_topcreate_instructioncreate_jump_absolutecreate_rot_ncreate_swapget_code_keysInstructionis_generatoris_jump_absolute	unique_id)code_context)	PyCodegen)	!augment_exc_message_with_hop_nameBackendCompilerFailedcollapse_resume_framesformat_frame_infoget_stack_above_dynamoResumePrologueTracingErrorStepUnsupportedunimplementedUnsupported)get_funcname)GuardBuilderinstall_guard)GraphCompileReasonOutputGraphStackLocalsMetadata)impl_CONTAINS_OP_fallbackimpl_IS_MAPPINGimpl_MATCH_CLASSimpl_MATCH_KEYSimpl_MATCH_SEQUENCE)DummyModuleExecutionRecorder)ContinueExecutionCache"IS_TRACING_RESUME_PROLOGUE_VARNAMEReenterWithTORCH_DYNAMO_RESUME_IN_PREFIX)
AttrSourceDictGetItemSourceGlobalSourceGlobalWeakRefSourceLocalCellSourceLocalSourceSkipGuardSourceSource)is_builtin_constantis_forbidden)	_get_error_on_graph_breakcountersget_fake_valueget_instruction_source_311get_metrics_contextgraph_break_dup_warning_checkeristype
LazyStringproxy_args_kwargs)typestrValueMutationNewVariableTracker)FrameStateSizeEntryVariableBuilderwrap_fx_proxy)BuiltinVariable)CONSTANT_VARIABLE_NONEConstantVariable)ContextWrappingVariableGenericContextWrappingVariableWithEnterFunctionVariableWithExitFunctionVariable)ConstDictVariableSetVariable)BaseUserFunctionVariableLocalGeneratorFunctionVariableLocalGeneratorObjectVariableNestedUserFunctionVariableSkipFunctionVariableUserFunctionVariableUserMethodVariable)MAX_ITERATOR_LIMIT)LazyVariableTracker)BaseListVariableIteratorVariableListIteratorVariableListVariableSliceVariableTupleVariable)CellVariableExceptionVariableGetAttrVariableNullVariablePythonModuleVariableTracebackVariableUnknownVariable)NNModuleVariableUnspecializedNNModuleVariable)SymbolicStreamState)supported_comparison_opsSymNodeVariable)SymbolicTorchFunctionStateTorchFunctionModeVariable)RemovableHandleVariableUserDefinedClassVariable!UserDefinedExceptionClassVariable"UserDefinedExceptionObjectVariableUserDefinedObjectVariable)Callable	GeneratorSequence)FakeTensorMode)CompilePackagegraph_breaks
trace_calltrace_sourcetrace_bytecodec                 C  s   i | ]
\}}|t |jqS  )re   call_function.0kvr   r   h/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py
<dictcomp>   s    r   dict[str, Any]compare_op_handlersc                 C  s   t | g t|i S N)handle_containsreversedtxargs_r   r   r   <lambda>   s    r   inc                 C  s   t | t| g t|i gi S r   )
handle_notr   r   r   r   r   r   r      s    znot inr	   ExceptionValsnamestrreturntypes.ModuleTypec                 C  s
   t | S )z
    Import the named module and cache the result. importlib.import_module()
    seems to do some filesystem checking to validate the name so not caching
    this can be slow.
    )	importlibimport_module)r   r   r   r   _import_module   s   
r   c                   @  sf   e Zd ZU ded< ded< ded< ded< dZd	ed
< dZded< dZded< dddZdddZdS )SpeculationEntryr   filenameintlinenoinstruction_pointerr,   instFbool_failedNzOptional[bool]error_on_graph_breakzOptional[GraphCompileReason]reasonr   Nonec                 C  s0   d| _ || _| jdur| jj}nd}tj|d)z\
        Start tracing of the current frame over again, and don't take this branch.
        TNz!Unknown fail_and_restart_analysis)restart_reason)r   r   r   r   SpeculationRestartAnalysis)selfr   r   r   r   r   fail_and_restart_analysis   s   

z*SpeculationEntry.fail_and_restart_analysisr   InstructionTranslatorBasec                 C  s$   | j r| jd us
J | j|_dS dS NTF)r   r   )r   r   r   r   r   failed  s
   zSpeculationEntry.failed)r   r   r   r   )r   r   r   r   )	__name__
__module____qualname____annotations__r   r   r   r   r   r   r   r   r   r      s   
 
r   c                   @  s\   e Zd ZU dZejedZded< dZ	ded< dZ
d	ed
< dddZdddZdddZdS )SpeculationLoga3  
    SpeculationLog replaces the prior copy_graphstate/restore_graphstate
    checkpointing.  Rather than saving/restoring state, we restart the
    dynamo conversion process over from the beginning -- but when we
    hit the start of the speculation that failed, we instead generate
    a graph break.
    default_factoryzlist[SpeculationEntry]entriesr   r   indexFr   graph_break_on_autograd_gradr   r   c                 C  s
   d| _ d S Nr   )r   r   r   r   r   restart     
zSpeculationLog.restartc                 C  s   | j   d| _d S r   )r   clearr   r   r   r   r   r   "     

zSpeculationLog.clearr   r   r   r   r   r,   r   c                 C  s  t | j| jkr| jt|||| | j| j }d}| jdkr<| j| jd  }d|j d|j d|jj d|j	 d	}|j	|krK|j|krK|j|ks{t
d	| j d
t | j d|j d|j d|jj d|j	 d| d| d|j d| d| d|  jd7  _|S )z
        Lookup or create a SpeculationEntry() that is shared across
        RestartAnalysis calls.  Args are used only for debug checks.
         r   r   zPrevious instruction: :(z @ z)
z"
SpeculationLog diverged at index z
 (log had z entries):
- Expected:  (z at ip=z)
- Actual: a  
There are two usual reasons why this may have occurred:
- When Dynamo analysis restarted, the second run took a different path than
  the first.  If this occurred, the previous instruction is the critical instruction that
  behaved differently.
- Speculation entries are only added under certain conditions (as seen in
  step()), e.g., there must exist operators in the graph; those conditions may
  have changed on restart.

If this divergence was intentional, clear the speculation log before restarting (do NOT
do this for graph breaks, you will infinite loop).

Otherwise, please submit a bug report, ideally including the contents of TORCH_LOGS=+dynamo
)lenr   r   appendr   r   r   r   opnamer   SpeculationLogDivergence)r   r   r   r   r   entryprev_entry_msg
prev_entryr   r   r   next&  sX   



zSpeculationLog.nextNr   r   )
r   r   r   r   r   r   r   r,   r   r   )r   r   r   __doc__dataclassesfieldlistr   r   r   r   r   r   r   r   r   r   r   r     s   
 

r   c                   @  s,   e Zd ZU ejedZded< d	ddZdS )

LocalStater   zdict[str, FrameStateSizeEntry]automatic_dynamicr   r   c                 C  s   d dd | j D S )N
c                 s  s&    | ]\}}| d |   V  qdS ): N)renderr   r   r   r   	<genexpr>]  s    
z$LocalState.render.<locals>.<genexpr>)joinr   itemsr   r   r   r   r   \  s   
zLocalState.renderNr   r   )	r   r   r   r   r   dictr   r   r   r   r   r   r   r   V  s
   
 r   c                   @  s*   e Zd ZU ded< ded< dZded< dS )DistributedStater   
compile_pgr   local_stateNzOptional[list[LocalState]]
all_states)r   r   r   r   r   r   r   r   r   r   c  s   
 r   c                   @  sT   e Zd ZU e Zded< edddZedd
dZedddZ	edddZ
dS )TensorifyStatezset[str]force_specializationsr   r   r   r   c                 C     | j | d S r   )r   addclsr   r   r   r   
specializep  s   zTensorifyState.specializer   c                 C  s
   || j v S r   )r   r   r   r   r   should_specializet     
z TensorifyState.should_specializec                 C     | j   d S r   )r   r   r   r   r   r   r   x     zTensorifyState.clearc                 C  s   t | jdkS r   )r   r   r   r   r   r   empty|  r  zTensorifyState.emptyN)r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   setr   r   classmethodr   r   r   r  r   r   r   r   r   j  s   
 r   Callable[..., None]c                   C  s
   t tS r   )torchdynamo_loggingget_step_loggerlogr   r   r   r   _step_logger  r   r
  r   r   Generator[None, None, None]c                 c  sR    | j j}| j j}zg | j _d| j _d V  W || j _|| j _d S || j _|| j _w r   )speculation_logr   r   )r   r   r   r   r   r    save_and_restart_speculation_log  s   	
r  c                 c  s2    z| j j}d| j _d V  W || j _d S || j _w NF)outputshould_exit)r   tmpr   r   r   (temporarely_allow_writes_to_output_graph  s   r  c                   @  sP   e Zd ZU ded< ded< ded< dZded	< dddZdddZdddZdS )BlockStackEntryr,   r   zInstruction | Nonetargetr   stack_indexNzHOptional[Union[ContextWrappingVariable, GenericContextWrappingVariable]]with_contextr   r   c                 C  s
   | j d uS r   )r  r   r   r   r   can_restore  r   zBlockStackEntry.can_restorerJ   c                 C  sN   | j d usJ | jr t| jdr | jjr t| j d t| jjS t| j d S )Ntarget_valuesr   )r  r  hasattrr  rJ   tupler   r   r   r   	resume_fn  s   
zBlockStackEntry.resume_fnr   r   is_graph_breakVariableTracker | Nonec                 C  s0   | j d usJ |r| j  s|s| j |S d S r   )r  exit_on_graph_breakexit)r   r   r  r   r   r   r    s   zBlockStackEntry.exitr  )r   rJ   )r   r   r  r   r   r  )r   r   r   r   r  r  r  r  r   r   r   r   r    s   
 


r  c                   @     e Zd ZdS )r   Nr   r   r   r   r   r   r   r         r   c                   @  r   )ReturnValueOpNr!  r   r   r   r   r#    r"  r#  c                   @  s   e Zd ZdZdS )YieldValueOpzY
    Signal to the symbolic tracer to stop and return control flow to the
    caller
    N)r   r   r   r   r   r   r   r   r$    s    r$  fnCallable[..., object]Callable[..., Any]c                   s6   t t| jt|  t| d	 fdd}|S )
Nr   InstructionTranslatorr   r,   r   r   c                   s   |   | | i  d S r   )pushr   popnr   r   fn_varnargsr   r   impl  s   zstack_op.<locals>.impl)r   r(  r   r,   r   r   )r   inspect	signature
parametersre   	functoolswraps)r%  r/  r   r,  r   stack_op  s
   r5  modobjectr   c                 C  s&   t | tjsdS | jdd tjv S )NF.r   )
isinstancetypes
ModuleTyper   splitsysstdlib_module_names)r6  r   r   r   	is_stdlib  s   r?  with_msg	list[str]c                 C  sb   | rddd}nddd}dd	 t |D }td
d t|D }|d}||d |d  S )Nxr   r   r   c                 S  s   | sJ dd S )Nmsgr   rB  r   r   r   r%       z(get_assert_bytecode_sequence.<locals>.fnc                 S  s   | sJ d S r   r   rD  r   r   r   r%       c                 S     g | ]}|j qS r   r   r   r   r   r   r   
<listcomp>      z0get_assert_bytecode_sequence.<locals>.<listcomp>c                 s  s"    | ]\}}| d r|V  qdS )POP_JUMPN)
startswith)r   ir   r   r   r   r     s     z/get_assert_bytecode_sequence.<locals>.<genexpr>RAISE_VARARGSr   )rB  r   r   r   )disget_instructionsr   	enumerater   )r@  r%  insts	begin_idxend_idxr   r   r   get_assert_bytecode_sequence  s   

rV  c                  C  sb   t jdksJ ddd} dd t| D }t|d |d	d	d
 d }|d}||| S )zNGet the bytecode instructions that precede BUILD_LIST in a list comprehension.      r   	list[int]c                   S     dd t dD S )Nc                 S     g | ]}|qS r   r   r   rN  r   r   r   rJ        zB_get_comprehension_bytecode_prefix.<locals>.fn.<locals>.<listcomp>r   ranger   r   r   r   r%       z._get_comprehension_bytecode_prefix.<locals>.fnc                 S  rG  r   rH  rI  r   r   r   rJ    rK  z6_get_comprehension_bytecode_prefix.<locals>.<listcomp>r   NLOAD_FAST_AND_CLEAR
BUILD_LISTr   rZ  )r=  version_inforP  rQ  r   r   )r%  rS  	start_idxrU  r   r   r   "_get_comprehension_bytecode_prefix  s   
 
rh  dict[str, dict[str, Any]]c            	      C  s   t jdksJ ddd} ddd}dd	d
}ddd}ddd}|| }||}||}||}|d |d d|d |d d|d |d d|d g ddS )a  Discover bytecode patterns for comprehension result handling.

    Analyzes sample functions to extract the opcode sequences that appear
    after END_FOR for each result disposition (stored, discarded, returned, consumed).

    Returns patterns with:
        - pre_store_ops: opcodes between END_FOR and first STORE_FAST
        - post_store_op: first opcode after all STORE_FASTs (for disambiguation)
    rW  r   rZ  c                  S  s   dd t dD } | S )Nc                 S  r\  r   r   r]  r   r   r   rJ    r^  zI_get_comprehension_result_patterns.<locals>.fn_stored.<locals>.<listcomp>r   r_  )resultr   r   r   	fn_stored     z5_get_comprehension_result_patterns.<locals>.fn_storedr   c                   S  s   dd t dD  dS )Nc                 S  r\  r   r   r]  r   r   r   rJ  "  r^  zL_get_comprehension_result_patterns.<locals>.fn_discarded.<locals>.<listcomp>r   r_  r   r   r   r   fn_discarded!  rl  z8_get_comprehension_result_patterns.<locals>.fn_discardedc                   S  r[  )Nc                 S  r\  r   r   r]  r   r   r   rJ  &  r^  zK_get_comprehension_result_patterns.<locals>.fn_returned.<locals>.<listcomp>r   r_  r   r   r   r   fn_returned%  ra  z7_get_comprehension_result_patterns.<locals>.fn_returnedc                   S  s   t dd tdD S )Nc                 S  r\  r   r   r]  r   r   r   rJ  )  r^  zK_get_comprehension_result_patterns.<locals>.fn_consumed.<locals>.<listcomp>r   )sumr`  r   r   r   r   fn_consumed(     z7_get_comprehension_result_patterns.<locals>.fn_consumedr%  r'  tuple[list[str], Optional[str]]c           	      S  s&  t t| jd d }g }d}t| D ] }|r|jr n|j}|r5|j|kr5|p.t|j}|	|j
 q||dd d }d}g }|t|k rh|| dkrh|	||  |d7 }|t|k rh|| dksQ|t|k r|| dkr|d7 }|t|k r|| dkst||t|k r|| fS dfS )zCExtract (pre_store_ops, post_store_op) from comprehension bytecode.r   FEND_FORNr   
STORE_FAST)r   rP  findlinestarts__code__rQ  starts_line	positionsr   r   r   r   r   r   )	r%  target_linerS  startedinstrposopsidxpre_store_opsr   r   r   extract_pattern+  s,   
z;_get_comprehension_result_patterns.<locals>.extract_patternr   r   )r  post_store_op)stored	discardedreturnedconsumedNre  r   r   )r%  r'  r   rr  )r=  rf  )	rk  rm  rn  rp  r  r  r  r  r  r   r   r   "_get_comprehension_result_patterns  s   




r  c                   @  sB   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S )ComprehensionAnalysisa9  Metadata about a comprehension's bytecode structure.

    Attributes:
        end_ip: Instruction pointer after all comprehension bytecode
        result_var: Name of result variable, or None if result stays on stack
        result_on_stack: True if result stays on stack (discarded, returned, or in expression)
        iterator_vars: Variables from LOAD_FAST_AND_CLEAR (need restoration)
        walrus_vars: Variables assigned via walrus operator (:=) inside comprehension
        captured_vars: Variables read from outer scope via LOAD_FAST inside comprehension
    r   end_ipzOptional[str]
result_varr   result_on_stackrA  iterator_varswalrus_varscaptured_varsN)r   r   r   r   r   r   r   r   r   r  R  s   
 r  r   truth_fnCallable[[object], bool]r)  c           	      C  s   |t jus|r	dS t| jtsJ | j}dD ]9}t|}| j||t|  }dd |D }||krO|rB|d}| j||  j	}nd}| 
t|  dS qdS )NF)FTc                 S  rG  r   rH  rI  r   r   r   rJ    rK  z:_detect_and_normalize_assert_statement.<locals>.<listcomp>
LOAD_CONSTzassertion errorT)operatortruthr9  r   r   rV  instructionsr   r   argvalr)  rg   create)	r   r  r)  current_instruction_pointerr@  assert_insts	cur_instsload_const_idx	error_msgr   r   r   &_detect_and_normalize_assert_statementg  s2   
r  F8Callable[[InstructionTranslatorBase, Instruction], None]c                   s6   ddd	ddfdd d fdd}|S )Nvaluera   r   r   c                 S  s$   t dd|  dg tjdd d S )NzData-dependent branchingzattempted to jump with zyDetected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.z1Use `torch.cond` to express dynamic control flow.gb_typecontextexplanationhints)r9   r   FUNDAMENTALr  r   r   r   raise_jump_graph_break  s   
z,generic_jump.<locals>.raise_jump_graph_breakr   r   r   r   r,   	extra_msgr   r   c           
   
     sP  |   sJ d }z| W n ty" } z|}W Y d }~nd }~ww |d us)J |  r4| | j| | j| jt||d | | t	
d | jj| tdt| | |  gdd}|   | | j|} rq| | |jd usxJ | |j|}tjdkr| jtdg t|j|d d	}	|	| | j|	g| |  d S )
Nr   r   zgeneric_jump triggered compilezgeneric_jump r   r   
stack_popsrX     TO_BOOLr   )r  )should_compile_partial_graphr:   maybe_has_backedgeraise_loop_graph_breakf_codelog_graph_breakcode_optionsr   r)  r	  debugr  compile_subgraphr>   r_   frame_summarypopcreate_call_resume_atnext_instructionr  r=  rf  add_output_instructionsr'   r   copy_positions)
r   r   r  r  r   eall_stack_locals_metadataif_nextif_jump	jump_inst)r)  r  r   r   jump_graph_break  sT   




z&generic_jump.<locals>.jump_graph_breakc                   s  |   }tjrt| r|   }| r?t| r | |S |  r+ | || nt	dd| dg t
jdddd | r[| jjdtjgt||fi R   | | d S t|tr|j}t|tjsm|d	k}tjjj|}|st	d
t|dg t
jd | | d S | jjdtjgt|fi R  }t| |t|j| d}| jjdtjgt||fi R   | | d S | rt|t r|j!rt"|j!#t$j% | rr| &| | | d S d S | r|  r | || d S t|t'r| j(|j)}|rr| &| | | d S d S t|t*rz|+| d}	W n+ t,j-yU   t,.|  z|+| d}	W n t,j-yR   t,.|  d }	Y nw Y nw t|	t/r|	0| g i }t1t1|	dd dd }
| r| }|
dkrt|tst2j34dt5|j6 }t,j7t8| |gd t|tt9fr|rr| &| | | d S d S d S t|tr|: rЈr| &| | | d S d S t	dd|	 d| dg d d S drr| &| | | d S d S | s|;| rt<|=| rr| &| | | d S d S t|trxzt|jtjr4|:| j}nt>|jd	k}W n% t,j?ya } z|  r\ | ||d| dW  Y d }~S  d }~ww |rvro| &| | | d S d S t|t2j@rdrr| &| | | d S d S ddl!mA} |j!d ur||j!r|B rr| &| | | d S d S | d S )Nz>Data-dependent assertion failed (cannot compile partial graph)zvalue: zuDynamo has determined when encountering a data-dependent assert failure that it should not compile the partial graph.zUse `torch._assert()` to raise a hard AssertionError when the check fails. This error will propagate back the user code that called the compiled function (i.e. Dynamo will not trace any exception handling).zRemove the assert statement.zMove the assert statement outside of any context managers in order to graph break with partial graph compilation (if fullgraph=False).r  r   r   z#Assertion failed on symbolic shapesr   )example_value__bool____len__r%  r   z&__bool__ should return bool, returned r   z3Data-dependent branching with non-constant __bool__zmethod: z
, result: z}Attempted to perform data-dependent branching on a user-defined object with a __bool__ method that did not return a constant.Tr   )r  r   )is_constant_source)Cr  r    rewrite_assert_with_torch_assertr  is_python_constantr   as_python_constantjumpr  r9   r   r  	is_tensorr  create_proxytorch_assert_asyncr^   r9  r   sym_numSymBoolfxexperimentalsymbolic_shapesexpect_truer   
USER_ERRORscalar_tensorrd   rX   noderl   sourcer=   
make_guardr<   SEQUENCE_LENGTHr)  r   get_submodule
module_keyr   var_getattrr   ObservedAttributeErrorhandle_observed_exceptionrt   r   getattrr   rg   r  typer   raise_observed_exception	TypeErrorr   evaluate_exprhas_unpack_var_sequencer   unpack_var_sequencer   	UserErrorBackwardHookVariabler  get_real_value)r   r   r  r  sym_exprrj  scalar_to_tensor_proxyscalar_to_tensorr6  rB  method_nameresult_valuerC  eval_resultr  r  r  r)  r  r  r   r   inner  sJ  



















	


"




zgeneric_jump.<locals>.inner)r  ra   r   r   )r   )
r   r   r   r,   r  ra   r  r   r   r   r   r   r   r,   r   r   r   )r  r)  r  r   r  r   generic_jump  s   
9 :r  cgr1   cleanuplist[Instruction]r   c                 C  s   g }| }|dur| | |j}|dust|D ]<} | jD ]6}t|jtr2|| 	|j
| q|jdus9J t|jtsAJ |j| || |j
| qqdS )zsGenerates bytecode to restore the block stack for running the unsupported instruction
    in the compiled bytecode.N)r   parentr   block_stackr9  r  r   extend_outputr  try_except_torch_function_moder  rh   reconstruct_typetry_finally)r   r  r  all_txescur_txbr   r   r   _reconstruct_block_stack  s*   

r   
msg_prefixYCallable[[Callable[..., None]], Callable[[InstructionTranslatorBase, Instruction], None]]c                   s   d fdd}|S )Ninner_fnr  r   r  c                   s0   t d fdd}dfdd |S )Nr   r   r   r,   r   r   c              
     s@  | j }| _ |  }|| r|jd usJ  | ||jS zvz
| |W W || _ S  ty } zZ| jrO| js9| jr: |  t	dd| j ddgt
j|d |jrS |  sX |  rc| | j| | j| j dt| |d |  |d t|j|j|_W Y d }~nd }~ww W || _ n|| _ w || j d S )	Nz0Graph break under GenericContextWrappingVariablez!Active generic context managers: z]Attempted to graph break in an active context manager(s) that doesn't support graph breaking.zEMove the offending context manager(s) to outside the compiled region.r  r  r  r  from_excz:

r  graph_break)current_instruction_push	speculater   r   r:   active_generic_context_managers	one_graphr   remove_from_statsr9   r   CAUSED_BY_EARLIER_GRAPH_BREAK
skip_framer  r  r  r  r  r  r   add_to_statsr>   rC  
real_stackr   )r   r   	prev_pushspeculationexcp)handle_graph_breakr  r  r)  r   r   wrapper  sV   
(

%z>break_graph_if_unsupported.<locals>.decorator.<locals>.wrapperr   r>   c           
        s  t jdkr$t jdk r$|jdkr$ttjd |jttjd |j }nt|j|j}t	d|j | j
j| |t | d}t| j
j}g }t| || | j
|  ~t jdkr|jdkr| jd urk| j nd}t|dkrt jd	k szJ | j
td
|dg |jd usJ t|jd}|d | | j
| n|jd u sJ t|}	d |	_| j
|	g | j
| | t |   r| t  | j
| | j| d S )NrX     rW  CALLPRECALLz%s triggered compiler  r   r   r  KW_NAMESr  Frb  ) r=  rf  r   rP  stack_effectopmapargopcoder	  r  r  r  r   r1   root_txr   r  rQ  kw_namesr  r   r'   r#   r  r  copyexn_tab_entryr*  r)  r   r  r  )
r   r   r   r  r  r  r  r   
call_insts	inst_copyr)  r   r   r    s\   





zIbreak_graph_if_unsupported.<locals>.decorator.<locals>.handle_graph_breakr  )r   r   r   r,   r   r>   r   r   )r3  r4  )r  r  r  r)  )r  r  r   	decorator  s   4>z-break_graph_if_unsupported.<locals>.decorator)r  r  r   r  r   )r)  r  r'  r   r&  r   break_graph_if_unsupported  s   xr(  c                      s"   e Zd ZdZd fddZ  ZS )BytecodeDispatchTableMetazTInstalls a `cls.dispatch_table` on every subclass to speed up calls to self.OPCODE()r   r  r   r   basesr   dctr   r   c                   sP   t  ||| ddd  fd	d
tj D fddtdD _d S )Nr   r   r   r   r   r   c                 W  s6   t d|  d| d|  dd|  dgtjd d S )NzMissing bytecode handlerz with args z=Dynamo does not know how to handle the bytecode instruction ``.z%Do not trace code that produces the `z_` bytecode instruction (see https://docs.python.org/3/library/dis.html for bytecode semantics).r  )r9   r   SUPPORTABLE)r   r   r   r   r   _missing]  s   


z4BytecodeDispatchTableMeta.__init__.<locals>._missingc              
     s&   i | ]\}}|t |t |qS r   )r  r3  partial)r   r   op)r.  r   r   r   r   i  s    z6BytecodeDispatchTableMeta.__init__.<locals>.<dictcomp>c                   s   g | ]}  |qS r   )getr]  )dispatch_tabler   r   rJ  n      z6BytecodeDispatchTableMeta.__init__.<locals>.<listcomp>   )r   r   r   r   r   r   )super__init__rP  r  r   r`  r2  )r   r   r*  r+  	__class__)r.  r   r2  r   r6  Z  s   
z"BytecodeDispatchTableMeta.__init__)
r   r  r   r   r*  r   r+  r   r   r   )r   r   r   r   r6  __classcell__r   r   r7  r   r)  W  s    r)  c                   @  s   e Zd ZU dZejedZded< ejddZ	ded< d)ddZ
d*ddZd)ddZd+ddZd,ddZd*ddZd*ddZd+ddZd*dd Zd-d!d"Zd.d$d%Zd/d'd(ZeZdS )0ExceptionStackzU
    Exception stack that it is shared among all InstructionTranslator instances
    r   zlist[ExceptionVals]
_exc_stackN)defaultzOptional[ExceptionVals]_current_exceptionr   r   c                 C  s
   d | _ d S r   r=  r   r   r   r   clear_current_exception  r   z&ExceptionStack.clear_current_exceptionvalr   c                 C  s   |  | || _d S r   )._set_context_and_break_context_reference_cycler=  r   r@  r   r   r   set_current_exception  r   z$ExceptionStack.set_current_exceptionc                 C  s&   | j d usJ | | j  |   d S r   )r=  r   r?  r   r   r   r   move_current_exception_to_stack  s   z.ExceptionStack.move_current_exception_to_stackc                 C  s   | j d usJ | j S r   r>  r   r   r   r   get_current_exception  s   z$ExceptionStack.get_current_exceptionprev_idxr   c                 C  sT   |j  }rt|tur|S t| j| dkr(| j| }| ||d  || |S Nr   r   )__context__r  rg   r   r;  _set_context_recursiveset_context)r   r@  rF  ctxprevr   r   r   rI    s   

z%ExceptionStack._set_context_recursivec                 C  s\   | }}d}	 |j }t|tu rd S ||u r|t d S |}||u r%d S |r*|j }| }qr  )rH  r  rg   rJ  rf   )r   r@  oslow_oslow_update_toggler  r   r   r   _break_context_reference_cycle  s    
z-ExceptionStack._break_context_reference_cyclec                 C  s$   |  |t| jd  | | d S Nr   )rI  r   r;  rP  rB  r   r   r   rA    s   z=ExceptionStack._set_context_and_break_context_reference_cyclec                 C  
   | j  S r   )r;  r  r   r   r   r   r    r   zExceptionStack.popc                 C  r   r   )r;  r   rB  r   r   r   r     rE  zExceptionStack.appendc                 C  s
   t | jS r   )r   r;  r   r   r   r   r    r   zExceptionStack.__len__r   c                 C  s
   | j | S r   )r;  )r   r   r   r   r   __getitem__  r   zExceptionStack.__getitem__r   c                 C  s   d| j d| jS )Nzself._exc_stack=z - self._current_exception=)r;  r=  r   r   r   r   __str__     zExceptionStack.__str__r   )r@  r   r   r   )r   r   )r@  r   rF  r   r   r   r  )r   r   r   r   r   )r   r   r   r   r   r   r   r;  r   r=  r?  rC  rD  rE  rI  rP  rA  r  r   r  rS  rT  __repr__r   r   r   r   r:  q  s"   
 











r:  c                      s
  e Zd ZU ded< ded< ded< ded< ded	< d
ed< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded < d!ed"< d#ed$< d%ed&< d'ed(< ded)< ded*< d+ed,< ded-< d.ed/< d0ed1< d2ed3< dd6d7Zdd8d9Zdd;d<Zdd=d>Zdd?d@ZddAdBZ	ddGdHZ
ddKdLZddNdOZdddRdSZddTdUZddVdWZddXdYZejdZkrՐdd\d]Zndd^d]Zedd_d`ZddbdcZddddeZddfdgZddjdkZddmdnZddodpZddrdsZddtduZddvdwZddxdyZddzd{Z dd|d}Z!eZ"dd~dZ#dddZ$dddZ%e&j'dddZ(dddZ)dddZ*e+d ddZ,d!ddZ-dddZ.dddZ/e/Z0dddZ1e+d"ddZ2dddZ3d#ddZ4e4Z5e4Z6e7e8j9dZ:e7e8j;dZ<e7e8j9dZ=e7e8j;dZ>dddZ?dddZ@dddZAdddZBdddZCdddZDdddZEdddZFdddZGd$ddZHd%ddZId&ddZJdddZKdddZLdddZMd'ddńZNdddǄZOd(dd˄ZPddd̈́ZQdddτZRdddфZSdddӄZTdddՄZUdddׄZVdddلZWeXdddۍddd݄ZYeXdddۍdddZZeXdddۍdddZ[dddZ\dddZ]dddZ^dddZ_d)ddZ`dddZaeXdddۍdddZbdddZcedd*ddZed+ddZfd,dd	Zgedd-ddZhdddZieXdddۍdddZjdddZkdddZldddZmdddZnd.ddZodddZpdddZqerfd/d"d#Zsdd$d%ZtetZudd&d'Zvdd(d)ZwewZxdd*d+Zydd,d-Zzdd.d/Z{dd0d1Z|dd2d3Z}dd4d5Z~dd6d7Zdd8d9ZeXdd:dۍdd;d<Zdd=d>Zdd?d@ZddAdBZddCdDZddEdFZddGdHZddIdJZd0dMdNZd1dQdRZddSdTZddUdVZddWdXZddYdZZdd[d\Zdd]d^Zdd_d`ZddadbZeZddcddZddedfZddgdhZddidjZddkdlZddmdnZddodpZddqdrZee8jZee8jZee8j9Zee8jZee8jZee8jZee8jZee8jZee8jZee8jZee8jZee8jZee8jZeXddsdۍee8jZee8jZee8jZee8jZee8jZee8jZee8jZee8jÃZee8jŃZee8jǃZee8jɃZee8j˃Zee8j˃Zee8j΃Zee8jЃZee8j҃Zee8jԃZee8jփZee8j؃Zee8jڃZېddtduZejdZkrddvdwZݐddxdyZސddzd{Zߐdd|d}Zd2d3ddZeXdddۍdddZdddZdddZe4Ze4Ze7e8j;dZe7e8j;dZe7e8j9dZe7e8j9dZdddZdddZd4ddZedd5ddZdddZdddZdddZdddZdddZdddZdddZdddZdddZdddZdddZeXdddۍdddZdddZdddZdddZdddZdddZeZ eZeZdZdddZdddZdZdddZdddZ	Pdd6ddZ	d7dĐdńZ
ddƐdǄZd8dɐdʄZed9d̐d̈́Zejd:dАdфZd;dӐdԄZddՐdքZd<dאd؄Zd=dڐdۄZddܐd݄Zd>ddZd?ddZd@ddZdAddZdBddZeddCddZ	P	P	PdDdE fddZ  ZS (F  r   r?   r  dict[str, VariableTracker]symbolic_localssymbolic_globalsr   symbolic_torch_function_stater   symbolic_stream_statez$Optional[dict[str, VariableTracker]]post_prune_cell_and_freevarslist[VariableTracker]stackOptional[int]r   r,   current_instructionr   r  zlist[BlockStackEntry]r  r   r   zOptional[ConstantVariable]r   accept_prefix_instr  prefix_instsinline_depthinconsistent_side_effectszOptional[SpeculationEntry]current_speculationz	list[Any]r2  r:  exn_vt_stackzOptional[ExecutionRecorder]exec_recorderz+Optional[Callable[[VariableTracker], bool]]strict_checks_fnstart_pointhas_no_inlined_callsz#Optional[InstructionTranslatorBase]r  is_child_tracer_activez3list[tuple[VariableTracker, list[VariableTracker]]]debug_localsOptional[CompilePackage]packagez
deque[str]latest_bytecode_queuer   r   c                 C  s
   d| _ dS )z
        InstructionTranslator has encountered instructions which may cause
        dynamo to see a different version of history from eager
        See: https://github.com/pytorch/pytorch/issues/110765
        TN)rd  r   r   r   r   mark_inconsistent_side_effects  s   
z8InstructionTranslatorBase.mark_inconsistent_side_effectsc                 C  sv   | }|d ur9|j j}|jd usJ |j|jd  D ]}|jdv r" n|jtv r1|j}||k r1 dS q|j}|d usdS )N)RETURN_VALUERETURN_CONSTTF)r`  offsetr   r  r   r   r  r  )r   r  
cur_offsetr   jump_offsetr   r   r   r    s   

z,InstructionTranslatorBase.maybe_has_backedgerA  c                 C  
   | j d S )Nco_cellvarsr  r   r   r   r   cellvars$  r   z"InstructionTranslatorBase.cellvarsc                 C  rv  )Nco_freevarsrx  r   r   r   r   freevars'  r   z"InstructionTranslatorBase.freevarsc                 C  s"   t | ds|  |   | _| jS )N_cell_and_freevars)r  ry  r{  r|  r   r   r   r   cell_and_freevars*  s   
z+InstructionTranslatorBase.cell_and_freevarsc                   sF   fddj  D _tjj  fddj  D _ d S )Nc                   s"   i | ]\}}|   v r||qS r   r}  r   r   r   r   r   1  s
    z?InstructionTranslatorBase.prune_dead_locals.<locals>.<dictcomp>c                   s   i | ]\}}| v r||qS r   r   r   )readsr   r   r   8  s    )rX  r   r\  r   r  r`  r   r   r  r   r   prune_dead_locals/  s   

z+InstructionTranslatorBase.prune_dead_localsr%  ra   r   kwargsc                 C  s   t |tsJ t |tsJ t |tsJ tdd t|| D s&J d }t|dr0|j	}t|dr8|j
}|rIt|rIt|rItd| | || || d S )Nc                 s  s    | ]}t |tV  qd S r   )r9  ra   r   rB  r   r   r   r   E  s
    
z:InstructionTranslatorBase.call_function.<locals>.<genexpr>r  r%  z$Attempt to trace forbidden callable )r9  ra   r   r   all	itertoolschainvaluesr  r  r%  callablerU   AssertionErrorr)  r   )r   r%  r   r  r  r   r   r   r   <  s   

z'InstructionTranslatorBase.call_functionrn   Sequence[VariableTracker]c                 C  s    t |ts	t|}|| ||S )zD
        Redirect the call to the generator "call_function"
        )r9  ro   r   r   r%  r   r  r   r   r   inline_generator_functionR  s   
	z3InstructionTranslatorBase.inline_generator_functionr   c                 C  s0   t jrt| r| |||S t| |||S )zF
        A call to some user defined function by inlining it.
        )r   "enable_faithful_generator_behaviorr-   get_coder  InliningInstructionTranslatorinline_callr  r   r   r   inline_user_function_return_  s   	z5InstructionTranslatorBase.inline_user_function_returnNr   c                 C  st   |d u r| j }| jdkrd| j dnd}t| jj|}|d u r"dnd| d}| jj d| d| jj | | S )Nr   z (inline depth: )r   r   r   z in )r   rc  r;   r  co_filenameco_name)r   r   inline_depth_strfuncnamefuncname_strr   r   r   get_line_of_code_headerm  s   $z1InstructionTranslatorBase.get_line_of_code_headerc                 C  s8   d|    d}t| jj| j }|d| 7 }|S )NzTRACE starts_line r   z    )r  	linecachegetliner  r  r   rstrip)r   log_strliner   r   r   get_log_starts_line_log_strw  s   z5InstructionTranslatorBase.get_log_starts_line_log_strc                 C  sJ   | j |krd S || _ t| jj|| jj | jr#tdt	| j
 d S d S )N%s)r   r   set_current_locr  r  r  is_trace_source_log_enabledtrace_source_logr  r]   r  )r   r   r   r   r   rw  }  s   
z%InstructionTranslatorBase.starts_linec              
   C  sj  t  | _| j}|du rdS | j|  | _}|d | _|jr#| |j | js@|  r@|  r@| 	 | _
| j
| r@| | dS | jrPtd|j|jt| j tjryzt| j}W n tye   d}Y nw | jd|j dt|j d|  | | z| j|j | | | jj W S  ty     tjy } z|  | W Y d}~dS d}~w t!t"fy   Y dS  t#t$fy+ } ze| j%s| js| j&st'|t#r|j(rt'|t$rt)d	d
dddgt*j+d  | j
du rt,d t'|t$rt)dd
dddgt*j+dd t'|t#sJ d|_( dt-| }| j.| j/||d W Y d}~nd}~ww | j
0| j dS )z<Process exactly one instruction, return False we should exitNFr   zTRACE %s %s %sz0<self.stack repr truncated due to large integer>zTRACE  Tz3cannot resume from torch._dynamo.step_unsupported()r   ztraced torch._dynamo.step_unsupported(), but Dynamo is instructed to error on graph break. This graph break is used for debugging only.z1Remove the torch._dynamo.step_unsupported() call.z9Make sure fullgraph=False and error_on_graph_break=False.r  z1empty checkpoint - cannot resume from graph breakz6torch._dynamo.step_unsupported() with empty checkpointztraced torch._dynamo.step_unsupported(), but there is no checkpoint to step_graph_break from. This graph break is used for debugging only.zInclude at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some line of code that is not in a try/with block, and has an empty Python stack.)r  r  r  r  r  zEncountered graph break that we cannot resume from. Compiling up to the previous resumable state, then skipping the rest of the function. Graph break encountered:

r  )1rV   r   r   r  r`  rw  r^  r  is_non_empty_graphr  re  r   step_graph_breakis_trace_bytecode_log_enabledtrace_bytecode_logr  r   r  reprr   verbose
ValueErrorro  r   update_block_stackr2  r  r  r  r   r   r   exception_handlerr#  r$  r:   r8   r
  is_tracing_resume_prologuer9  r  r9   r   
DYNAMO_BUGr	  r   r  r  r   )r   ipr   
stack_reprr  r   r   r   r   step  s   




	

:zInstructionTranslatorBase.stepr  r   c                 C  s   |j }|r+t| jdkr%|j| jd jur'|j| jd ju r)| j  d S d S d S d S | jrC|jdvrEt| jdks<J | j  d S d S d S )N   rb  )NOPJUMP_BACKWARD	NOT_TAKENr   )r"  r   r  r  r  r   )r   r   r   r   r   r   r    s   	z,InstructionTranslatorBase.update_block_stackc                 C     d S r   r   r+  r   r   r   r  )     c                 C  s   | j d usJ | j| j  S r   )r   r  r   r   r   r   r  ,  s   z*InstructionTranslatorBase.next_instructioncontinue_instc              	   C  s0  | j jrJ | jd usJ | jrJ td | j j| td|  gd}| j	rFddl
m} tjs4J t| j j}|g td|d| tddd	td|d| tddd	 | d||d g |d
d\}}|| g }t| j	|| | |g|g| || |g td|dtdtd|dtd |d j}|g td|d| td| |g tdtddd	 | j	t  |d  jd7  _|dkr|g td|d| t t|d td|dtd |td|d d	td|d d	td|d d	g | j | | j	 | j	j!|dd    d S | j g tdtd t| j j}| j |d| g |d j"# D ]\}	}
| j t ||
| |$|	g qn| j tdt%|g| j& d S )Nzstep triggered compilestep_unsupported)r   r   	skip_coder  r   rd  r  TFDELETE_SUBSCRrX  LIST_APPENDSTORE_SUBSCRUNPACK_SEQUENCEPOP_TOPrb  )'r  output_instructionsre  r^  r	  r  r  r>   r  r  
eval_framer  r   nested_graph_breaksr1   r  r  r%   create_load_constcreate_binary_subscrr'   create_resumer   codegen_call_resume	num_stackr"   r*   r)  r   r&   r  rQ  r  r  locals_namesr   create_storer(   r  )r   r  r  r  r  leaf_resume_codeleaf_resume_namer  r  localr~  r   r   r   r  1  s  









z*InstructionTranslatorBase.step_graph_breakc                 C  s
   t d S r   )r   current_framer   r   r   r   run_ctx_mgr  s   
z%InstructionTranslatorBase.run_ctx_mgrc                 C  s  |    t| jj zz<| j|  | j| _z|  r!	 |  sW n$ t	yF } z| j
rAtdt|j dt| |jd  d }~ww W no tyP     tyW     ty } z@t|tr~t| tr~| js~| js~dt| }| j| j||d t|drd|jv rtj| jj | jj!j"dddd	}||_#  d }~w t	y } z
| j$r| j$% |_& d }~ww W | j'  t| tr| j(  | j)  n| j'  t| tr| j(  | j)  w w W d    d S 1 sw   Y  d S )
NzError while tracing through a Dynamo-generated resume function prologue. Errors are not allowed when tracing resume function prologues.
r   ztFailed to handle graph break gracefully. Skipping the function and falling back to eager. Graph break encountered:

r  rC  zData-dependentFT)print_outputinclude_strideinclude_device)*r  r   r  r  r  push_txr   ri  r  	Exceptionr  r7   r  r   r   with_traceback__traceback__r   r3   RuntimeErrorr9  r:   r(  r   r
  r  r  r  rC  r  r  GraphModule
nn_modulesgraphprint_readablepartial_fx_graphrg  
get_recordexec_recordpop_txr  mark_bytecode_tracing_stop)r   r  r   readable_graphr   r   r   run  s   








"zInstructionTranslatorBase.runr@  Optional[VariableTracker]c                 C  s4   |d u st |tsJ dt| | j| d S )Nz"push expects VariableTracker, got )r9  ra   r_   r^  r   rB  r   r   r   r)  E  s   zInstructionTranslatorBase.pushvalsc                 C  s   |D ]}|  | qd S r   r%  )r   r  r@  r   r   r   	push_manyK  s   z#InstructionTranslatorBase.push_manyc                 C  rR  r   )r^  r  r   r   r   r   r  O  r   zInstructionTranslatorBase.popnc                   s   g t  fddt|D S )Nc                   s   g | ]}   qS r   r  )r   r   r   r   r   rJ  S      z2InstructionTranslatorBase.popn.<locals>.<listcomp>)r   r`  )r   r  r   r   r   r*  R  s   zInstructionTranslatorBase.popnc                 C  s   |j }| jr|| jv r| j|| j|  z| | j|   W nM tyn   |drZz|	dd}| | j|  W n. tyY   t
dd| d| ddgtjd Y nw t
d	d| d
| dg tjd Y nw |dr|| j| d S d S )Nr8  implicitz5Attempted to read undefined local variable (implicit)z
LOAD_FAST z5Could not find an implicit local variable with name ``z(This happens in dict/list comprehensionsr  z*Attempted to read undefined local variablez+Could not find a local variable with name `__stack)r  rg  f_localsadd_local_varr)  rX  unwrapKeyErrorrM  replacer9   r   r  r  )r   r   r   new_namer   r   r   	LOAD_FASTU  s@   




z#InstructionTranslatorBase.LOAD_FASTc                 C  sl   |j |  v s	J | j|j  }| jj|}| | | jr2|j | jv r4| j	|j | j|j   d S d S d S r   )
r  r}  rX  r  side_effects	load_cellr)  rg  r  r  )r   r   cellcontents_varr   r   r   
LOAD_DEREFx  s   
z$InstructionTranslatorBase.LOAD_DEREFc                 C  sP   |j }|  }|| || j|< |tkr&| }t|tu s!J || _d S d S r   )	r  r  set_name_hintrX  rI   r  r  r   r  )r   r   r   	loaded_vtr@  r   r   r   rt    s   


z$InstructionTranslatorBase.STORE_FASTc                 C  s   | j |j= d S r   )rX  r  r+  r   r   r   DELETE_FAST     z%InstructionTranslatorBase.DELETE_FASTc                 C  sb   |j |  v s	J | j|j  }|  }| jj|| t|ts"J |j	d ur/|
|j	 d S d S r   )r  r}  rX  r  r  r  
store_cellr9  r}   
local_namer  )r   r   r  r@  r   r   r   STORE_DEREF  s   
z%InstructionTranslatorBase.STORE_DEREFc                 C  sX   |j }|d u rtj|jdS | j| }|s$tj|jd| j|< | j| }|d us*J |S )Nr  )r  rg   r  r  _constants_cache)r   r   rN  r@  r   r   r   _load_const  s   

z%InstructionTranslatorBase._load_constc                 C  s   |  | | d S r   )r)  r  r+  r   r   r   r    rU  z$InstructionTranslatorBase.LOAD_CONSTc                 C  s   |j }| jr&|| jv r| j|| j|  n|| jv sJ | j| | jj|< || jvr0| |S || jv rK| jj	| j|  }| 
| jj	|| d S | j| }| 
t| |t| d S r   )r  rg  	f_globalsadd_global_var
f_builtinsbuiltinsload_builtinrY  r  r  r)  load_globalra   buildrN   )r   r   r   variabler  r   r   r   _load_global  s   




z&InstructionTranslatorBase._load_globalc                 C  s$   d}|  |}t|}t| ||S )Nztorch.nn.modules.module)import_sourcer   ra   r	  )r   module_namemodule_sourcefglobals_valuer   r   r   nn_modules_globals_vt  s   
z/InstructionTranslatorBase.nn_modules_globals_vtc                 C  sj   |j d usJ tjdkrtjdk r|j d r| | | | tjdkr1|j d r3| | d S d S d S )Nr  r  r  )r  r=  rf  	PUSH_NULLr  r+  r   r   r   LOAD_GLOBAL  s   

z%InstructionTranslatorBase.LOAD_GLOBALc                 C  sr   |   }|j}t|}|| jvrt | j|< | jj|| j| }t|t	r.t
d|dg d | jj||| d S )Nz%Storing Tensor hook handle in globalsThis is not supported.r  )r  r  rN   rY  r7  r  r  track_global_existingr9  r   r9   store_global)r   r   r  r   r  r
  r   r   r   STORE_GLOBAL  s    


z&InstructionTranslatorBase.STORE_GLOBALr  rN   c                 C  s   d|v rt jjj| }|dddddd}nt|}d|dd }| jdur3| j|| || jj|< | jj	}||vsI|| |u sIJ |||< | j
| t|S )	z-Create an alias to a module for use in guardstorch_package>r   <r8  _dot_	__import_N)r  rn  package_importer_package_imported_modulesr  r   add_import_sourcer  import_sourcesglobal_scopeupdate_co_namesrN   )r   r  r  aliasr  r   r   r   r    s    
z'InstructionTranslatorBase.import_sourcer   levelc                 C  sB   | d|d }t||k rtd|d }|r| d| S |S )z
        Copied from the Cpython implementation of __import__
        Resolve a relative module name to an absolute one.
        https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L902
        r8  r   z2attempted relative import beyond top-level packager   )rsplitr   ImportError)r   r   rn  r#  bitsbaser   r   r   resolve_name  s
   z&InstructionTranslatorBase.resolve_namec                 C  s   | j d}| j d}|dur%|dur#||jkr#tjd||jdd |S |dur,|jS tjddd | j d }d	| j vrD|d
d }|S )z
        Copied from the Cpython implementation of __import__
        https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L1090
        __package____spec__Nz)__package__ != __spec__.parent (%r != %r)rX  )
stacklevelzYcan't resolve package from __spec__ or __package__, falling back on __name__ and __path__r   __path__r8  r   )r  r1  r  r	  warning
rpartition)r   rn  specr   r   r   calc_package  s*   

z&InstructionTranslatorBase.calc_packagec           
      C  sH  |  d\}}| }| }|j}tj d| d| d| }|| jv r/| j| }t|}nLzt|||| jd}W n tyW   t	dd| d| d| dg t
jd	 Y nw |d
krg|  }| |||}|sv|dd
 }	| |	}n| |}| jr| j|| t|tjtfr| t||d d S t	dt|dg d	 d S )Nr  r   )fromlistr#  globalszImport failurezmodule_name: z, fromlist: z, level=z"Failure when attempting to import.r  r   r8  r  zBad import resultz%Import result is not a Python module.)r*  r  r  rG   LOCAL_MOD_PREFIXr  rN   
__import__r%  r9   r   r  r0  r(  	partitionr  rg  add_local_modr\   r:  r;  rF   r)  r   r_   )
r   r   r#  r1  r  recorded_namer  r  pkgtop_level_module_namer   r   r   IMPORT_NAME   sR   






z%InstructionTranslatorBase.IMPORT_NAMEc                 C  s   |  | | |j d S r   )DUP_TOP
_load_attrr  r+  r   r   r   IMPORT_FROM`     
z%InstructionTranslatorBase.IMPORT_FROMr  c                 C  sv   || j vrtddd| dg tjd | j | }t|r/t| jj}t||}t	
| ||S t|s5J tj|dS )Nz%failed to find name in frame builtinsr   zFailed to find name `z` in frame's builtins.r  r  )r  r9   r   r  r  rN   r  %name_of_builtins_dict_key_in_fglobalsrM   ra   r	  rT   rg   r  )r   r  r@  builtins_source
var_sourcer   r   r   load_builtin_from_argvalf  s$   



z2InstructionTranslatorBase.load_builtin_from_argvalc                 C  s   |  | |j d S r   )r)  rC  r  r+  r   r   r   r  }  rq  z&InstructionTranslatorBase.load_builtinInstruction | BlockStackEntryc                 C  sZ   | j d usJ | jd usJ |jd usJ t d| j | j  | j|j | _ | j | _d S )Nir_count)r   ri  r  rZ   	incrementindexofr+  r   r   r   r    s   zInstructionTranslatorBase.jumpFTc                 C  .   |j d usJ | jt||j t| j d S r   r  r  r   r  r   r^  r+  r   r   r   
SETUP_LOOP      z$InstructionTranslatorBase.SETUP_LOOPc                 C  rH  r   rI  r+  r   r   r   SETUP_EXCEPT  rK  z&InstructionTranslatorBase.SETUP_EXCEPTc                 C  r   r   )r  r  r+  r   r   r   	POP_BLOCK  r  z#InstructionTranslatorBase.POP_BLOCKc                 C     |  | d S r   setup_or_before_withr+  r   r   r   
SETUP_WITH  r  z$InstructionTranslatorBase.SETUP_WITHc                 C  rH  r   rI  r+  r   r   r   SETUP_FINALLY  s    z'InstructionTranslatorBase.SETUP_FINALLYc                 C  s   |  d  d S r   r%  r+  r   r   r   BEGIN_FINALLY  r  z'InstructionTranslatorBase.BEGIN_FINALLYc                 C  sB   |  d\}}|d u sJ | | | || tgd i  d S )Nr  rX  )r*  r)  r   rf   )r   r   r  r   r   r   r   WITH_CLEANUP_START  s   
z,InstructionTranslatorBase.WITH_CLEANUP_STARTc                 C  s   |  d | d  d S Nr  )r*  r)  r+  r   r   r   WITH_CLEANUP_FINISH  s   
z-InstructionTranslatorBase.WITH_CLEANUP_FINISHc              
   C  s   |    }| | z|| }| | W d S  ttjfyM } z&t|tjr.t|  t	j
dkr9| t n|    | | W Y d }~d S d }~ww NrW  )r  realizer)  next_variableStopIterationr   ObservedUserStopIterationr9  r  r=  rf  rf   r  )r   r   itr@  r  r   r   r   FOR_ITER  s   



z"InstructionTranslatorBase.FOR_ITERc                 C  s"   t |tjtfr|| g i }|S r   )r9  r   re   r   r   rB  r   r   r   _create_exception_type  s
   
z0InstructionTranslatorBase._create_exception_typer   r   c                 C  sN   |   }|| d}t|ttfsJ t||}|| dtd|gi  d S )Nr  __setattr__)r  r  r9  rg   r   from_frame_summarycall_method)r   r   r  tbnew_tbr   r   r   _attach_traceback_to_exception  s   
z8InstructionTranslatorBase._attach_traceback_to_exceptionr   c                 C  s   |  |}t| jrt|tjr|jtu rtt	
| g i }| |r3t|dd d u r3tjj |_| |rS| j| t|j}t|dd }|d| |dtdttdg tjd d S )Npython_stackraised exception )r  zFailed to raise exceptionz.Attempted to raise a non-Exception type/value.r  )r^  r-   r  r9  r   r~   exc_typerZ  re   r  r   _isinstance_exceptionr  r  _guardsr   extract_stackre  rf  rC  r   get_dynamo_observed_exceptionr9   r   r   r  )r   r@  observed_exception_typere  r   r   r   _raise_exception_variable  s0   





z3InstructionTranslatorBase._raise_exception_variablec                 C  s:  |j dkr3t| jstd}tjt| |gd t| jsJ | jd }| |s,J || | d S |j dkr[| j	d }z| | W | j
 }| | d S | j
 }| | w |  }|  }z | | W | j
 }| | | |}|| td| d S | j
 }| | | |}|| td| w )Nr   zNo active exception to reraiser  rb  r   	__cause__)r  r   rf  rg   r   r  r  rh  rm  r^  rE  rd  r  r^  call_setattr)r   r   rC  r@  curr_excfrom_vtcauser   r   r   rO  	  s8   












z'InstructionTranslatorBase.RAISE_VARARGSc                 C  sD   | j d }t|tsJ |jtu rtdddg d d S | | d S )Nrb  z CLEANUP_THROW with StopIterationr   zRReceived StopIteration when handling generator.throw/close. This is not supported.r  )r^  r9  r~   rg  rZ  r9   RERAISEr   r   tosr   r   r   CLEANUP_THROW7	  s   


z'InstructionTranslatorBase.CLEANUP_THROWc                 C  sl   t jdkr#|  }|jr|  }| | d S | | | | d S |  }|  }|  }| | d S )Nr  )r=  rf  r  r  rm  r)  )r   r   r@  r   _exc_tbr   r   r   rs  E	  s   

z!InstructionTranslatorBase.RERAISETypeIs[ExceptionVals]c                 C  s
   t |tS r   )r9  r   rB  r   r   r   rh  \	  r   z/InstructionTranslatorBase._isinstance_exceptionc                 C  s  g }t jdkrLt jdk rdnd}t| j|ksJ | j|  }| jd }| |s+J t|j}|| d}t jdkrKt| jd t	sK|
| jd  n%t| jdksUJ | jd	 }| jd
 }| |sfJ t|j}|| d}||||g7 }| ||i  d S )Nr  rX           rb  r     ir  )r=  rf  r   r^  rh  re   rg  r  r9  r   r   r   )r   r   r   fn_locr%  r@  typrb  r   r   r   WITH_EXCEPT_START_	  s0   







z+InstructionTranslatorBase.WITH_EXCEPT_STARTraised_exceptionr   c           	        s  d d fdd}t jdkr`jj}|rFtj|jkr*  tj|jks|jr7	t
jj 	j  | d S j  j }| ttu r^|  tjr/j }|jjdkrd j  tjd	krj  ttu rtd
t d g tjd j }|jjdksqj }j  tj|jkrȈ  tj|jksttddd d	}j t!|d tj tjdkrjd }	t
"  	| 	t
#|j$ n	t
j% 	t
j% 	t
j% 	t
"  	| 	t
#|j$ | d S j  ttu r>|  )NzDynamo found no exception handler at the top-level compiled function when encountering an exception. Exception will propagate outside the compiled region.r   r   c                    s\   j  } t|  }t|sJ tdd|   d| j d g t	j
t	jd d S )NzObserved exceptionrf  r   r  r  )rf  rE  r   rk  python_typer9  r9   python_type_namer   r   r  r-  )rp  
dynamo_excobserved_exn_gb_explanationr  r   r   r   bubble_exception_to_interpreter	  s   

zTInstructionTranslatorBase.exception_handler.<locals>.bubble_exception_to_interpreterr  EXCEPT_HANDLERrX  r   z#Observed exception (EXCEPT_HANDLER)z  This graph break is unexpected.r  g    .Ar  r  r   )&r=  rf  r`  r"  r   r^  depthr  lastir)  r   rg   rs  rf  rE  r  r   rd  r  r(  r  r   r   r*  r9   r   r   r  rD  r  r,   r   r   r  r   re   rg  rf   )	r   r  r  r"  rp  block_stack_entryexception_varexcept_handler_instold_exceptionr   r  r   r  	  s   







	






z+InstructionTranslatorBase.exception_handlerc                 C  sH   |   }t| jdkrt}n| jd }| | | | | j  d S )Nr   rb  )r  r   rf  rf   r)  rD  )r   r   r@  prev_excr   r   r   PUSH_EXC_INFO
  s   


z'InstructionTranslatorBase.PUSH_EXC_INFOc                 C  s   t jdkr|  }t| jsJ | j  d S t| jdks J | jd jjdkr-td| j  | 	d t| js>J | j  d S )Nr  r   rb  r  zYBug in Dynamo tracing of exception handling.Top of the block stack is not EXCEPT_HANDLER.rX  )
r=  rf  r  r   rf  r  r   r   r  r*  )r   r   r   r   r   r   
POP_EXCEPT%
  s   


z$InstructionTranslatorBase.POP_EXCEPTc                 C  s:  t | jdks	J |  }tjdkr| jd }n| j }t|tttt	fs7t
dt|d| dg tjd tjdkrR| |sRt
dt|d	| dg tjd t|tr[|j}n|g}|D ]:}t|tt	tfs{t
d
t|d| dg tjd | |rt|j|jr dS t|tjrt|j|jr dS q`dS )Nr  r  rb  z Exception with bad expected typez"`except ...` has unsupported type r8  r  zCaught non-Exception valuezCExcept expects to receive an object of Exception type but received z#Exception with non-type expectationz!`except ...` expects a non-type: TF)r   r^  r  r=  rf  r9  re   r|   r   r   r9   r   r   r  rh  r   
issubclassrg  r%  r   )r   expected_exc_typesexc_instanceexpected_typesexpected_typer   r   r   check_if_exc_matches:
  sr   

	





z.InstructionTranslatorBase.check_if_exc_matchesc                 C  s   |  t|   d S r   )r)  r   rg   r  r+  r   r   r   CHECK_EXC_MATCH
  s   z)InstructionTranslatorBase.CHECK_EXC_MATCHc                 C  s   |   s| | d S d S r   )r  r  r+  r   r   r   JUMP_IF_NOT_EXC_MATCH
  s   z/InstructionTranslatorBase.JUMP_IF_NOT_EXC_MATCHc                 C  s:   |j dkr| | d S | t|j  | | di  d S )Nzexception matchr  )r  r  r)  r   r*  r+  r   r   r   
COMPARE_OP
  s   
"z$InstructionTranslatorBase.COMPARE_OPc                 C  s   |  tt|  gi  d S r   )r   re   iterr  r+  r   r   r   GET_ITER
     z"InstructionTranslatorBase.GET_ITERzjEncountered graph break when attempting to trace CALL_FUNCTION: a call to a regular function, e.g. f(x, y))r)  r  c                 C  s&   |  |j}|  }| ||i  d S r   r*  r  r  r   )r   r   r   r%  r   r   r   CALL_FUNCTION
  s   z'InstructionTranslatorBase.CALL_FUNCTIONzjEncountered graph break when attempting to trace CALL_FUNCTION_EX: a variadic function call, e.g. f(*args)c                 C  s`  |j dkrti }|  }n/|j dkstjdkr*|  }t|tr%ti }|  }ntdd|j  d|j  g tj	d tjdkrM|  }t|tsMJ |  }tjd	krftjdk rf|  }t|tsfJ t|t
sw|| rwt|| }t|trt| t|}t|t
rt|tstd
dt| dt| dg tjd | }| ||j| d S )Nr   r   rz  z%Variadic function call with bad flagszflags: zHAttempted to call a variadic function (CALL_FUNCTION_EX) with bad flags r  r  r  z0Variadic function call with bad args/kwargs typezargs type: z, kwargs type: z2Expected args to be a list and kwargs to be a dict)r  rl   r  r=  rf  r9  r   r9   r   r  rw   has_force_unpack_var_sequencer|   force_unpack_var_sequencer   re   call_custom_dictr   r_   r  keys_as_python_constantr   r   )r   r   
kwargsvarsargsvarsnullr%  r   r   r   CALL_FUNCTION_EX
  sT   








z*InstructionTranslatorBase.CALL_FUNCTION_EXzyEncountered graph break when attempting to trace CALL_FUNCTION_KW: a function call with keyword arguments, e.g. f(x=True)c                 C  s   |   }| |j}|   }t|tr| sJ | }|d t|  |t| d  }}tt	||}t|t|ksAJ | 
||| d S r   )r  r*  r  r9  r|   r  r  r   r   zipr   )r   r   argnamesr   r%  kwargs_listr  r   r   r   CALL_FUNCTION_KW
  s   &z*InstructionTranslatorBase.CALL_FUNCTION_KWc                 C  s\   |  tj|dd |jd }| jd | }tjdk r"| | d S | tj||d d S )Nr  r  r   co_namesr  )	r  r   r  r  r  r=  rf  r=  LOAD_METHODr   r   r  r  r   r   r   LOAD_METHOD_SUPER
  s   

z+InstructionTranslatorBase.LOAD_METHOD_SUPERc                 C  s:   |  tj|dd |jd }| jd | }| | d S )Nr  r  r   r  )r  r   r  r  r  r=  r  r   r   r   LOAD_ATTR_SUPER  s   
z)InstructionTranslatorBase.LOAD_ATTR_SUPERc                 C  sp   |  |j |  }tjdkr| | | | d S tjdkr,| | | | d S | | | d  d S )Nr  r  )r=  r  r  r=  rf  r)  r  r   r   objr   r   r   r  	  s   




z%InstructionTranslatorBase.LOAD_METHODc                 C  s:   |  |j}|  }|d u sJ |  }| ||i  d S r   r  )r   r   r   dummyr%  r   r   r   CALL_METHOD  s
   z%InstructionTranslatorBase.CALL_METHODattrc                 C  s2   |   }tt| |t|gi }| | d S r   )r  re   r  r   rg   r  r)  )r   r  r  rj  r   r   r   r=     s   z$InstructionTranslatorBase._load_attrc                 C  s2   t jdkr|jd r| | d S | |j d S )NrW  r  )r=  rf  r  r  r=  r  r+  r   r   r   	LOAD_ATTR)  s
   


z#InstructionTranslatorBase.LOAD_ATTRzkEncountered graph break when attempting to trace STORE_ATTR: storing an object's attribute, e.g. x.attr = yc                 C  s2   |  d\}}tt| |t|j|gi  d S rU  )r*  re   setattrr   rg   r  r  )r   r   r@  r  r   r   r   
STORE_ATTR1  s   z$InstructionTranslatorBase.STORE_ATTRc                 C  s*   |   }tt| |t|jgi  d S r   )r  re   delattrr   rg   r  r  r  r   r   r   DELETE_ATTR=  s   z%InstructionTranslatorBase.DELETE_ATTRr  c                 C  sb   g }|dksJ |dkr| td | jdkrtdntd| jd}| tdtd|g |S )a  
        Debug CPython expects the stack to be empty after the return.
        Calling compile_subgraph will push cells and frame values to TOS.
        This function will pop those 2 values from the stack before actually returning.

        Expects the stack to be:
            cells, frame values, current frame stack (0 or 1 values)

        Pops cells and frame values, leaving the current frame stack as TOS.
        A return instruction is included.
        r   rX  rq  rr  r  r  )extendr*   r   r'   r  )r   r  rS  return_instr   r   r   codegen_return_with_popsE  s   
z2InstructionTranslatorBase.codegen_return_with_popsr~  resume_instmetar@   resume_codeslist[types.CodeType]r  r1   is_leafhandle_inactive_ctxtuple[types.CodeType, str]c                   s  |rzt |j|jD ]4\\}}	}
ttj|
 }|t  || |	g t
d||| ||td q	|jD ]8\}}	ttj| }|t  || |	g t
d||| ||j|j|  td qAt|r|jsJ |j}td|j }|rtj|tfddjD }t|j t fdd|D }t fdd|D }|	t ||| t g |D ]}|	t ||j|j|  | gt
d q|	tdtd	t|d
gt
dt|jdd nt|j }t|j}tjdk r$t|dks$J dtjt|j  }j!jdus7J t"#j$j%j!j|jtdd j&D |||tdd j&D |t|jt|jt|j t|j' }t()j$*ddd  }|durt+,|t()|d< |j-rj./|| d}nj./|t01|j2| |}j3durj34|j2d | t5d |j6  d7  < ||fS )a.  
        Creates the resume function for the frame corresponding to `self`.

        Expects the TOS to be:
            [frame N cells, ..., frame 1 cells],
            [
                frame N stack + locals,
                ...,
                frame 1 stack + locals
            ]

        Some additional codegen may happen to prepare the frame stack + locals values for the generated resume function:
        - inactive context variables in the stack and locals will be replaced by their types
        - if the frame is a leaf frame, prune dead locals

        Regardless of codegen, the stack will be left in the same state as before.

        Args:
            - idx: depth of this frame: 0 corresponds to the leaf frame (frame N), N-1 to the root frame (frame 1).
            - resume_inst: the instruction that this frame should resume at
            - meta: metadata for this frame returned from OutputGraph.compile_subgraph
            - resume_codes: nested resume code objects generated from previous create_resume calls.
            - cg: codegen object to output to
            - is_leaf: True if `self` corresponds to the leaf frame.
            - handle_inactive_ctx: If True, handles inactive context variables as described above. This is necessary
                iff the resume function is traced
        r  r  __resume_at_c                 3  s(    | ]}| v r|  vr|V  qd S r   r~  r   r   r  r   r   r     s    z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>c                 3  s    | ]	}| vr|V  qd S r   r   r  argnames_null_setr   r   r         c                 3  s    | ]	}| v r|V  qd S r   r   r  r  r   r   r     r  r  rd  r  NTrW  r   z&variables should not be NULL in < 3.12c                 s  s    | ]}|j jV  qd S r   )r  rs  r   r  r   r   r   r         c                 s      | ]}|  V  qd S r   )r  r  r   r   r   r     r  orig_graphmodulec                   S  r  r   r   r   r   r   r   r         z9InstructionTranslatorBase.create_resume.<locals>.<lambda>r   resumesr   )7r  stack_ctx_argsstack_ctx_idxes_origr   rh   r^  append_outputr&   r  r  r*   r  r  r'   locals_ctx_argsrX  r  r  r.   r  r/   rs  r   r  r  r  locals_null_keysr   r"   keysr=  rf  stack_null_idxesr`  rH   lookupr  r   r  r  r0   get_contextr1  weakrefrefrz  r  install_global_unsafer:  FunctionTyper  rn  add_resume_functionrW   r  )r   r~  r  r  r  r  r  r  jr   j_origrK  r   resume_nameall_argnamesr  argnames_nullr  	stack_lennew_codeorig_graphmodule_maybepackage_namer   )r  r  r   r   r  e  s   *




	

z'InstructionTranslatorBase.create_resumer  list[StackLocalsMetadata]c              
   C  s  d| _ t| jj}g }g }g }| }d}|dur@|| u r|}	n|j}	|	jdkr5|| || ||	 |j}|d7 }|dust| j	t|d j
 }
|sx|
dksTJ |t|
d  t|
d D ]	}|td qc|td | S |d | u r|td|
d d}|
|d _n:|t|
 t|
d D ]	}|td q|tddd ||d  j}||d   jd7  _|d t  |g td||d | t||d	 g }|D ]}|t ||| gtd q|tdtdt|dg || |g tdt|td g }g }t|D ]$\}}|||| |||  |||| u d	\}}|| || q*| ||| |td | S )
aP  
        Codegen all resume function(s) from the frame stack starting at `self`, call them,
        and return the result.
        Assumes that the unsupported instruction has already been run.

        Expects the TOS to be:
            [
                frame N locals,
                frame N-1 stack + locals,
                ...,
                frame 1 stack + locals
            ], *(frame N stack (post-unsupported instruction))

        Leaves the result of calling the resume functions on the stack and returns it
        (empty stack after return).

        Args:
            - inst: the instruction of the current (deepest) frame to resume at
            - all_stack_locals_metadata: metadata returned from OutputGraph.compile_subgraph - contains
                metadata such as local names, NULL positions, stack length, etc.
        Nr   rq  r   r  r  rd  r  T)r   r1   r  r  r  r   r   r  r   r^  r  r  r*   r`  r  r'   rQ  r  r)  r   r%   r  r  r"   r  r&   r!  deepcopyrR  r  r  )r   r   r  r  txesidxesresume_instsr  r~  r  current_num_stackr   stack_insert_idxfilter_instsr  resume_namesrN  resume_coder  r   r   r   r  (  s   





	
	

	z/InstructionTranslatorBase.create_call_resume_atr  c                 C  s  | td tt|| D ]9\}\}}|t|d kr n*|jr6| t ||| g |	|| n
| |
|dd | td q| tdtdt| d dg | td | d	 jr| |d	| g |	|d	 | d	  | g td n| tdg|
|d	 dtd | t t |d	| gtd|d	td
 | g tdtdddtdtddd | tdd dS )a  
        Calls the provided resume functions.

        Expects the TOS to be in the state:
            [frame N cells, ..., frame 1 cells],
            [
                frame N stack + locals,
                frame N-1 stack + locals,
                ...,
                frame 1 stack + locals
            ]

        Pops the cells and frame values, leaving the result of calling the resume functions on TOS.

        Args:
            - resume_codes: list of resume function code objects to call
            - resume_names: list of the corresponding names of the resume functions
            - cg: PyCodegen object to output instructions to
        r  r   Fr   r  rd  r  rX  rb  r  LIST_EXTENDTN)r  r%   rR  r  r   rz  r&   r  r  make_function_with_closureload_function_namer*   r'   r)   r$   )r  r  r  rN  r   coder   r   r   r    s   	
	


z-InstructionTranslatorBase.codegen_call_resumec                 C  sz   t jdkr| jj}|r| jr|j| jd jurdS tdd | jD o<| j o<| jp-| j	 o<| j
 o<| j o<| jjjd u S )Nr  rb  Fc                 s  r  r   r  r  r   r   r   r   N  r  zIInstructionTranslatorBase.should_compile_partial_graph.<locals>.<genexpr>)r=  rf  r`  r"  r  r  r  r
  rk  r   r  r	  r  current_tracerr  )r   r   r   r   r   r  E  s$   
z6InstructionTranslatorBase.should_compile_partial_graphziEncountered graph break when attempting to trace STORE_SUBSCR: trying to store subscript, e.g. x[key] = yc                 C  s(   |  d\}}}|| d||gi  d S )NrX  __setitem__r*  ra  )r   r   r@  r  keyr   r   r   r  X  s   z&InstructionTranslatorBase.STORE_SUBSCRc                 C  s$   |  d\}}|| d|gi  d S )Nr  __delitem__r  )r   r   r  r  r   r   r   r  `  s   z'InstructionTranslatorBase.DELETE_SUBSCRc                 C  s   |  |j}| t| d S r   )r*  r  r)  r|   r   r   r   r   r   r   BUILD_TUPLEd  s   z%InstructionTranslatorBase.BUILD_TUPLEc                 C  s"   |  |j}| t|| d d S )N)r   )r*  r  r)  r{   r  r   r   r   BUILD_SLICEh  s   z%InstructionTranslatorBase.BUILD_SLICEc                 C     dS )zCheck if comprehension speculation is allowed in nested context.

        For the base class (non-inlined), this always returns False.
        Fr   r   r   r   r   #_can_speculate_comprehension_nestedl  s   z=InstructionTranslatorBase._can_speculate_comprehension_nestedc                 C  s   t jdkr
|jdksdS |  sdS tdd | jD o2| j o2| j o2| j o2| j	 o2| j
jjdu }|r>| jdur>|  }|rX| jdkrX|  }|| rU| | dS || _|  }|dksbJ | j| |  jd7  _dS )	z
        Handle comprehension start for Python 3.12+ BUILD_LIST/BUILD_MAP with argval 0.
        Returns True if a graph break was triggered and the caller should return early.
        rW  r   Fc                 s  r  r   r  r  r   r   r   r     r  zSInstructionTranslatorBase._maybe_setup_comprehension_speculation.<locals>.<genexpr>NTr   )r=  rf  r  _is_comprehension_startr  r  r
  r   r  r	  r  r  r  r  _comprehension_depthr  r   !_handle_comprehension_graph_breakre  _find_comprehension_end_for_ip_comprehension_end_for_ipsr   )r   r   can_speculater  
end_for_ipr   r   r   &_maybe_setup_comprehension_speculations  s8   	

z@InstructionTranslatorBase._maybe_setup_comprehension_speculationc                 C  s2   |  |rd S | |j}| t|t d d S Nmutation_type)r	  r*  r  r)  rz   r`   r  r   r   r   rd    s   
z$InstructionTranslatorBase.BUILD_LISTc                 C  s>   t jrtdddg d | |j}t|t d}| | d S )Nzmissing BUILD_SET handlerr   z:Missing BUILD_SET bytecode handler (for testing purposes).r  r  )r   +inject_BUILD_SET_unimplemented_TESTING_ONLYr9   r*  r  rm   r`   r)  )r   r   r   new_setr   r   r   	BUILD_SET  s   z#InstructionTranslatorBase.BUILD_SETr   r  c              
   C  sx   |  |j}g }|D ]%}z
|||  W q
 ty/   tdt|| dg tjd Y q
w | 	||t
 d d S )Nz-Failed to unpack object for BUILD_LIST_UNPACKzU cannot be unpacked into a list for the BUILD_LIST_UNPACK bytecode (`[*x, *y, ...]`).r  r  )r*  r  r  r  NotImplementedErrorr9   r   r   r  r)  r`   )r   r   r   seqsr   seqr   r   r   BUILD_LIST_UNPACK  s   
z+InstructionTranslatorBase.BUILD_LIST_UNPACKc                 C  s   | j |td d S )Nr   )r  r|   r+  r   r   r   BUILD_TUPLE_UNPACK  ra  z,InstructionTranslatorBase.BUILD_TUPLE_UNPACKc                 C  sX   |  |rd S | |jd }tt|d d d |dd d }| t|t d d S )Nr  r   r  )r	  r*  r  r   r  r)  rl   r`   )r   r   r   dr   r   r   	BUILD_MAP  s
   
"z#InstructionTranslatorBase.BUILD_MAPc                   s^     |j} fdd|D }i }|D ]}t|tsJ ||j q t|t d d S )Nc                   s    g | ]}t t |gi qS r   )re   r   r   r  r   r   r   rJ    s     z>InstructionTranslatorBase.BUILD_MAP_UNPACK.<locals>.<listcomp>r  )r*  r  r9  rl   updater   r)  r`   )r   r   r   rj  rB  r   r   r   BUILD_MAP_UNPACK  s   z*InstructionTranslatorBase.BUILD_MAP_UNPACKc                 C  sn   |   }| |j}t|tsJ | sJ || }t|t|ks&J | t	t
t||t d d S r
  )r  r*  r  r9  r|   r  r  r   r)  rl   r   r  r`   )r   r   r  r  r   r   r   BUILD_CONST_KEY_MAP  s   
z-InstructionTranslatorBase.BUILD_CONST_KEY_MAPc                 C  sb   |  d\}}|jdksJ |jd usJ | j|j   }t|ts%J || d||fi  d S )Nr  r   r  )r*  r  r  r^  rX  r9  rl   ra  )r   r   r   r   r  r   r   r   MAP_ADD  s   z!InstructionTranslatorBase.MAP_ADDc                 C  b   |   }|jdksJ |jd usJ | j|j  }t|ts J | s&J || d|gi  d S )Nr   r   r  r  r  r^  r9  rm   
is_mutablera  r   r   r   r  r   r   r   SET_ADD     z!InstructionTranslatorBase.SET_ADDc                 C  r  Nr   r  r  r  r   r   r   
SET_UPDATE  r   z$InstructionTranslatorBase.SET_UPDATEc                 C  sn   |   }|jdksJ |jd usJ | j|j   }t|ts"J | s(J | jj	
| |j| d S r   )r  r  r  r^  rX  r9  rz   r  r  r  mutationr   r   r  r   r   r   r    s   z%InstructionTranslatorBase.LIST_APPENDc           	   
   C  s   |j }tjdk r|  }|  }tjdkr%t|jdsJ tj|jjd}d }d }d }d }tjdk rV|d urV|d@ r>|  }|d@ rF|  }|d@ rN|  }|d@ rV|  }| 	t
||| j|||| d S )	Nr  co_qualnamer  r     r|  r  r   )r  r=  rf  r  r  r  rg   r  r$  r)  rq   r  )	r   r   flagsfn_namer  defaultsclosurer   
kwdefaultsr   r   r   MAKE_FUNCTION  s@   


z'InstructionTranslatorBase.MAKE_FUNCTIONc                   s     }| r|jt|jd}n<t|tr4|j r4t|j	 |j
  fddt|jD }n|r?|}ntdt|| dg tjd t||jkrmtdd|j d	t| | d
g tjd t|D ]}| qqd S )N)r  c                   s   g | ]	}t  | qS r   )rd   r]  proxyr   r   r   rJ  9  s    z=InstructionTranslatorBase.UNPACK_SEQUENCE.<locals>.<listcomp>z+Failed to unpack object for UNPACK_SEQUENCEzV cannot be unpacked into a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`).r  z9Length mismatch when unpacking object for UNPACK_SEQUENCEzexpected length: z
, actual: za unpacked to a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`) with unexpected length.)r  r  r  r`  r  r9  r   r  r  as_proxyr   r  r  r9   r   r   r  r   r  r   r)  )r   r   r  r@  rN  r   r,  r   r  2  s0   
	z)InstructionTranslatorBase.UNPACK_SEQUENCEc           
      C  s   d|j   krdksJ  J |j d@ }|j d? }|  }|| rnt|| }t||| ks3J |d | }||t||  }|t|| d  }t|D ]}	| |	 qQ| t| t|D ]}	| |	 qdd S t	dt
|| dg tjd d S )Nr   i     r%  z%Failed to unpack object for UNPACK_EXz; cannot be unpacked into a list for the UNPACK_EX bytecode.r  )r  r  r  r   r  r   r   r)  r|   r9   r   r   r  )
r   r   prefixsuffixr  r  vals_prefix	vals_listvals_suffixitemr   r   r   	UNPACK_EXR  s,   



z#InstructionTranslatorBase.UNPACK_EXz-Encountered intentional debugging graph breakc                 C  s    | j rtddddgd d S d S )Nz#Forced graph break on leaf functionr   zSForced graph break on non-inlining function for nested graph break testing purposeszGSet torch._dynamo.config.debug_force_graph_break_on_leaf_return = Falser  )rj  r9   r+  r   r   r   graph_break_on_leaf_functionj  s   
z6InstructionTranslatorBase.graph_break_on_leaf_functionc                 C  s   |j dkr| | d S d S )NGRAPH_BREAK_IF_LEAF)r  r7  r+  r   r   r   r  y  s   
zInstructionTranslatorBase.NOPc                 C     |    d S r   r  r+  r   r   r   r  ~  rF  z!InstructionTranslatorBase.POP_TOPc                 C  s(   |   }|   }| | | | d S r   r  r)  r   r   ar  r   r   r   ROT_TWO  s   
z!InstructionTranslatorBase.ROT_TWOc                 C  s:   |   }|   }|   }| | | | | | d S r   r:  )r   r   r<  r  cr   r   r   	ROT_THREE  s   

z#InstructionTranslatorBase.ROT_THREEc                 C  sL   |   }|   }|   }|   }| | | | | | | | d S r   r:  )r   r   r<  r  r>  r  r   r   r   ROT_FOUR  s   


z"InstructionTranslatorBase.ROT_FOURc                 C  s    |   }| | | | d S r   r:  )r   r   r<  r   r   r   r<    s   
z!InstructionTranslatorBase.DUP_TOPc                 C  s<   |   }|   }| | | | | | | | d S r   r:  r;  r   r   r   DUP_TOP_TWO  s   


z%InstructionTranslatorBase.DUP_TOP_TWOr  flagc                 C  sX   |dkrt t| |gi S |dkrt t| |gi S |dkr*t t| |gi S |S )Nr   r  rX  )re   r   r   r  ascii)r   r  rB  r   r   r   _convert_value  s   z(InstructionTranslatorBase._convert_valuefmt_specr&  c                 C  s   |   }t|tr#ddlm}m} |j||||jd}| | d S | 	||d@ }t
d|  d }| ttj||gi  d S )Nr   )LazySymNodeFormatStringrv   r3  rX  z{:})r  r9  r   torch._dynamo.variables.lazyrF  rv   r  r  r)  rD  rg   r  r   re   r   format)r   rE  r&  r  rF  rv   fmt_varr   r   r   _format_value  s   

z'InstructionTranslatorBase._format_valuec                 C  s>   |j }|d us	J |d@ dkr|  }ntd}| ||S )Nr|  r   )r  r  rg   r  rK  )r   r   r&  rE  r   r   r   FORMAT_VALUE  s   

z&InstructionTranslatorBase.FORMAT_VALUEc              	   C  s   g }g }i }|j d usJ | |j D ]Y}| r$|d || qt|tjr_||j ||j	 t
| t
|j @ rXtdd| d| d|j dg tjd ||j qtdt|d	g tjd q| tjd
||| d S )Nz{}zBUILD_STRING key conflictzformat_string_parts: z
, kwargs: z, part.sym_kwargs: z1Failed to build format string due to key conflictr  zBUILD_STRING type errorzLFormat string part type is not correct - expected constant or format string.r   )r  r*  r  r   r9  r   StringFormatVariableformat_stringr  sym_argsr  r  
sym_kwargsr9   r   r  r  r   r)  r  r   )r   r   format_string_partsr   r  partr   r   r   BUILD_STRING  s<   
z&InstructionTranslatorBase.BUILD_STRINGc                 C  sF   |j dks|j dksJ |j dkrd}nd}td|d}| | d S )Nr   r   iszis notr  r  )r  r'   r  )r   r   
new_argvalnew_instr   r   r   IS_OP  s   
zInstructionTranslatorBase.IS_OPc                 C  s   |j dks|j dksJ | d\}}|j }z| || d|gi  W n2 tjtfyV } z#t|tr<|jr8 |	  | | 
t| t||gi  W Y d }~nd }~ww |dkrb| | d S d S )Nr   r   r  __contains__)r  r*  r)  ra  r   ObservedTypeErrorr:   r9  r  r  r  ra   r	  rA   	UNARY_NOT)r   r   leftrightr0  r  r   r   r   CONTAINS_OP  s2   

z%InstructionTranslatorBase.CONTAINS_OPc                 C  r  )Nr   r  )r  r  r  r^  r9  rz   r  ra  r  r   r   r   r    r   z%InstructionTranslatorBase.LIST_EXTENDc                 C  s"   |  tt| |  gi  d S r   )r)  re   r  r   r  r+  r   r   r   LIST_TO_TUPLE  s   "z'InstructionTranslatorBase.LIST_TO_TUPLEc                 C  sr   | j d }| |sJ |jtu r7tt| tdgi }|	| td| |	| td| || j d< d S d S )Nrb  zgenerator raised StopIterationrH  rn  )
r^  rh  rg  rZ  r   re   r  r   rg   ro  )r   r   r@  new_valr   r   r   STOPITERATION_ERROR   s   


z-InstructionTranslatorBase.STOPITERATION_ERRORc                 C  sf   |   }|jdksJ |jd usJ | j|j   }t|ts"J | s(J || d|gi  d S r!  )	r  r  r  r^  rX  r9  rl   r  ra  r  r   r   r   
DICT_MERGE2  s   z$InstructionTranslatorBase.DICT_MERGEc                 C  r9  r   r  r+  r   r   r   	GEN_START=  rF  z#InstructionTranslatorBase.GEN_STARTc                 C  sH   | j d }| r| tt|  d S | || dg i  d S )Nrb  r  )r^  r  r)  rg   r  r   r  ra  rt  r   r   r   GET_LEN@  s   
z!InstructionTranslatorBase.GET_LENc                 C  s,   | j d }| | t| t|gi  dS )zr
        If STACK[-1] is an instance of collections.abc.Mapping, push True.
        Otherwise, push False
        rb  N)r^  r)  r  ra   r	  rB   rt  r   r   r   MATCH_MAPPINGG  s   

z'InstructionTranslatorBase.MATCH_MAPPINGc                 C  s,   | j d }| | t| t|gi  d S Nrb  )r^  r)  r  ra   r	  rE   rt  r   r   r   MATCH_SEQUENCEU  s   

z(InstructionTranslatorBase.MATCH_SEQUENCEc              	   C  st   |  d\}}}t|j}| | t| t||||gi  t	j
dk r8| jd }| tt|t  d S d S )NrX  r  rb  )r*  rg   r  r  r)  r  ra   r	  rC   r=  rf  r^  r\   )r   r   subjectr   namesr  ru  r   r   r   MATCH_CLASS_  s   



z%InstructionTranslatorBase.MATCH_CLASSc                 C  sv   | j d }| j d }t|tsJ | | t| t||gi  tj	dk r9| j d }| t
t|t
  d S d S )Nrb  r  r  )r^  r9  r|   r)  r  ra   r	  rD   r=  rf  rg   r  r\   )r   r   r  r  ru  r   r   r   
MATCH_KEYSo  s   



z$InstructionTranslatorBase.MATCH_KEYSc                 C     |  | d d S )Nr  r)  rC  r+  r   r   r   LOAD_ASSERTION_ERROR  rU  z.InstructionTranslatorBase.LOAD_ASSERTION_ERRORc                 C  rk  )N__build_class__rl  r+  r   r   r   LOAD_BUILD_CLASS  rU  z*InstructionTranslatorBase.LOAD_BUILD_CLASSz`Encountered graph break when attempting to trace BINARY_SUBSCR: a binary subscript, e.g. x[attr]c                 C  s,   |j dkr| | d| _d S | jrJ d S )Nr   F)r  append_prefix_instra  r+  r   r   r   RESUME  s   


z InstructionTranslatorBase.RESUMEc                 C  s   |j d usJ t|j  | |S r   )r  _binary_op_lookupr+  r   r   r   	BINARY_OP  s   z#InstructionTranslatorBase.BINARY_OPc                 C  r  r   r   r+  r   r   r   r    r  z!InstructionTranslatorBase.PRECALLc                 C  sV   | j d |j }t|tsJ |D ]	}t|tsJ q| jd u s"J tj|d| _d S )N	co_constsr  )r  r  r9  r  r   r   rg   r  )r   r   r   r   r   r   r   r    s   z"InstructionTranslatorBase.KW_NAMESc                 C  s   |  t  d S r   )r)  r   r+  r   r   r   r    rE  z#InstructionTranslatorBase.PUSH_NULLcall_kwc           	      C  sP  |rt jdks	J |  }t|tr| sJ | }n	| jr$| jjnd}|j	d us-J | 
|j	d }t jdkrM|d }t|d trGg n|d g}nt|d tr[|d }g }n	|d }|d g}|r||dt|   }|t| d  }tt||}t|t|ksJ n
||dd   }i }z| ||| W d | _d S d | _w )Nr  r   r  r   r   )r=  rf  r  r9  r|   r  r  r   r  r  r*  r   r   r   r  r   )	r   r   ru  r   contentsr%  r   r  r  r   r   r   _call  s4   


zInstructionTranslatorBase._callzTEncountered graph break when attempting to trace CALL: a function call, e.g. f(x, y)c                 C  rN  r   rw  r+  r   r   r   r    s   zInstructionTranslatorBase.CALLc                 C  s&   |j d usJ | | j|j    d S r   )r  r)  r^  r+  r   r   r   COPY  s   zInstructionTranslatorBase.COPYc                 C  s<   |j d usJ | j|j   | jd | jd< | j|j  < d S re  )r  r^  r+  r   r   r   SWAP  s   .zInstructionTranslatorBase.SWAPc                 C  r  r   r   r+  r   r   r   CACHE  r  zInstructionTranslatorBase.CACHEc                 C  rN  r   rO  r+  r   r   r   BEFORE_WITH  r  z%InstructionTranslatorBase.BEFORE_WITHrK  >Union[ContextWrappingVariable, GenericContextWrappingVariable]c                 C  s   t |tr| s| j| tjdkr5|jr'| jr$|jj	| jd j	ur'd }n| j
jd us/J | j
jj	}n|j	}|r^t | tsBtjrQ| jt||t| j| n| jt||t| j || S )Nr  rb  )r9  ri   supports_graph_breaksr	  r   r=  rf  r"  r  r  r  r(  r   r  r  r   r^  enter)r   rK  r   r  r   r   r   	enter_ctx  s*   

z#InstructionTranslatorBase.enter_ctxc                 C  s*   t dd|  d|   dg dd d S )NzUnsupported context managerz1Attempted SETUP_WITH/BEFORE_WITH/LOAD_SPECIAL on z%Dynamo does not know how to enter a `z` context manager.)z,Avoid using the unsupported context manager.aE  If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then it may be the case that it was created outside the compiled region, which Dynamo does not support. Supported context managers can cross graph break boundaries only if they are local non-closure variables, or are intermediate values.zFile an issue to PyTorch. Simple context managers can potentially be supported, but note that context managers can't be supported in generalr  )r9   r  )rK  r   r   r   unsupported_ctx_graph_break:  s   
z5InstructionTranslatorBase.unsupported_ctx_graph_breakc                 C  sZ   |   }t|ttfs| | t|ttfsJ | t||j | | || d S r   )	r  r9  rh   ri   r  r)  rk   r  r  )r   r   rK  r   r   r   rP  K  s   
z.InstructionTranslatorBase.setup_or_before_withc                 C  s   | j sJ | j| d S r   )ra  rb  r   r+  r   r   r   rp  Z  r?  z,InstructionTranslatorBase.append_prefix_instc                 C  sL   t jdkr| jst| j|j tsJ | jj	 | j|j< d S | 
| d S rW  )r=  rf  ra  r9  rX  r  r   r  r  track_cell_newrp  r+  r   r   r   	MAKE_CELL^  s
   
z#InstructionTranslatorBase.MAKE_CELLc                 C  rN  r   rp  r+  r   r   r   COPY_FREE_VARSi  r  z(InstructionTranslatorBase.COPY_FREE_VARSc                 C  rN  r   r  r+  r   r   r   RETURN_GENERATORl  r  z*InstructionTranslatorBase.RETURN_GENERATORc                 C  sb   t jdkr
|   n| d t jdkr-| j| }|| jv r/| j| |  jd8  _d S d S d S )Nr  r  rW  r   )r=  rf  r  r*  rG  r  discardr  )r   r   
current_ipr   r   r   rs  s  s   





z!InstructionTranslatorBase.END_FORc                 C  sD   t | j|jd trtd|jd|j g tjd | | d S )Nz)LOAD_FAST_CHECK on uninitialized variablez/Attempted to load uninitialized local variable r  )	r\   rX  r1  r  r   r9   r   r  r  r+  r   r   r   LOAD_FAST_CHECK  s   
z)InstructionTranslatorBase.LOAD_FAST_CHECKc                 C  s6   |j | jvr| t  n| | t | j|j < d S r   )r  rX  r)  r   r  r+  r   r   r   rc    s   
z-InstructionTranslatorBase.LOAD_FAST_AND_CLEARc                 C  sJ   |  tj|dd |jd usJ |jd@ r| | d S | |j d S )Nr  r  r   )r  r   r  r  r  r=  r  r+  r   r   r   LOAD_SUPER_ATTR  s
   
z)InstructionTranslatorBase.LOAD_SUPER_ATTRc                 C  s   |j dkr| | d S |j dkr| | d S |j dkr+| t|  |  d S tdd|j  d|j  dg tj	d d S )	NrX  r}     z Missing CALL_INTRINSIC_1 handlerzCALL_INTRINSIC_1 operand: z,No handler implemented for CALL_INTRINSIC_1 z instruction.r  )
r  r`  UNARY_POSITIVEr)  r|   r  r  r9   r   r-  r+  r   r   r   CALL_INTRINSIC_1  s   




z*InstructionTranslatorBase.CALL_INTRINSIC_1c                 C  s   |   }|    | | d S r   r:  rt  r   r   r   END_SEND  s   z"InstructionTranslatorBase.END_SENDzpEncountered graph break when attempting to trace CALL_KW: a function call with keyword arguments, e.g. f(x=True)c                 C  s   | j |dd d S )NT)ru  rx  r+  r   r   r   CALL_KW  s   z!InstructionTranslatorBase.CALL_KWc                 C  s   | j jdv sJ d S )N)POP_JUMP_IF_TRUEPOP_JUMP_IF_FALSErZ  )r  r   r+  r   r   r   r    s   z!InstructionTranslatorBase.TO_BOOLc                 C  s   |j }|d us	J |  }t|tsJ |  }|d@ r2tjdks#J || tdgi }||_	nA|d@ r:||_
n9|d@ rdt|tsEJ |j}ttt|d d d |dd d ddt d	}||_	n|d@ rl||_n|d@ rs||_| | d S )
N   rz  r   r%  r|  r  T)strictr  )r  r  r9  rq   r=  rf  r   rg   r  r   r)  r|   r   rl   r   r  r`   r*  r(  r)  )r   r   r&  r%  r  r   annr   r   r   SET_FUNCTION_ATTRIBUTE  s0   $z0InstructionTranslatorBase.SET_FUNCTION_ATTRIBUTEc                 C  s   |  | |  |j d S r   )r)  rD  r  r  r+  r   r   r   CONVERT_VALUE  r  z'InstructionTranslatorBase.CONVERT_VALUEc                 C  s   |  tdd d S )Nr   r   )rK  rg   r  r+  r   r   r   FORMAT_SIMPLE  rq  z'InstructionTranslatorBase.FORMAT_SIMPLEc                 C  s   |  |  d d S r   )rK  r  r+  r   r   r   FORMAT_WITH_SPEC  rU  z*InstructionTranslatorBase.FORMAT_WITH_SPEC)	__enter____exit__
__aenter__	__aexit__c                 C  s   t |jts
J d| j|j }|dv rN|  }t |ttfs$| | t |ttfs-J |dkr?| t	| | 
| d S | t|d  | 
| d S | | |  }| | | 
| d S )Nz*expected LOAD_SPECIAL arg to be set to int)r  r  r  )r9  r  r   _load_special_namesr  rh   ri   r  r)  rj   r  rk   r=  )r   r   r  rK  r  r   r   r   LOAD_SPECIAL  s(   


z&InstructionTranslatorBase.LOAD_SPECIALc                 C  s   |  t|j d S r   )r)  rg   r  r  r+  r   r   r   LOAD_SMALL_INT  rq  z(InstructionTranslatorBase.LOAD_SMALL_INT)r  r  r  r  anyc                 C  s0   t |jts
J d| | | j|j  d S )Nz2expected LOAD_COMMON_CONSTANT arg to be set to int)r9  r  r   r)  rC  _common_constantsr+  r   r   r   LOAD_COMMON_CONSTANT)  s   z.InstructionTranslatorBase.LOAD_COMMON_CONSTANTc                 C  s    | j  dkrdd | _dS dS )Nr   c                   S  r   NTr   r   r   r   r   r   2  r  z>InstructionTranslatorBase.is_non_empty_graph.<locals>.<lambda>TF)r  count_callsr  r   r   r   r   r  /  s   
z,InstructionTranslatorBase.is_non_empty_graphadditional_stack_framesOptional[list[Any]]c                 C  s.   |d u rg }d t|  gtt| S )Nr   )r   	tracebackformat_listr  r   r   )r   r  r   r   r   format_frame_summary6  s   z.InstructionTranslatorBase.format_frame_summarytraceback.FrameSummaryc                 C  s(   t jt| jdd| jt| jddddS )Nr  	<unknown>r  F)lookup_line)r  FrameSummaryr  r  r   r   r   r   r   r  A  s   z'InstructionTranslatorBase.frame_summaryc                 C  s&   t | jdd}td}||d uS )Nr  r  z.*torch/nn/modules.*)r  r  recompilematch)r   r   nn_modules_patternr   r   r   is_co_filename_from_nn_modulesI  s   
z8InstructionTranslatorBase.is_co_filename_from_nn_modulesr0  c                 C  s,   | j |t|}tt|tj |S r   )	r  install_global_by_idr  r  r=   rO   r  r<   WEAKREF_ALIVE)r   r0  r  global_namer   r   r   store_global_weakref_by_idN  s
   z4InstructionTranslatorBase.store_global_weakref_by_idOptional[FakeTensorMode]c                 C  s
   | j jjS r   )r  tracing_context	fake_moder   r   r   r   r  U  r   z#InstructionTranslatorBase.fake_modecheck_fn!Callable[[VariableTracker], bool]c                 c  s*    | j }|| _ z	dV  W || _ dS || _ w )zx
        Strict mode is enabled on a per-VariableTracker level depending on the return value of check_fn(node).
        N)rh  )r   r  priorr   r   r   strict_translation_modeY  s   z1InstructionTranslatorBase.strict_translation_moder   c                 C  sF   | j d usJ | j dksJ | j| jj| j| j d | j| j d  S rG  )r   r  r   r  r  r   r  r   r   r   r   r  g  s   z#InstructionTranslatorBase.speculatec                 C  sT   t jdksJ | jdusJ | jd }t }dd | j|t| | D }||kS )zDetect if we're at the start of a list/dict comprehension in 3.12+.

        In Python 3.12+, comprehensions are inlined with a bytecode pattern that
        precedes BUILD_LIST/BUILD_MAP.
        rW  Nr   c                 S  rG  r   rH  rI  r   r   r   rJ  }  rK  zEInstructionTranslatorBase._is_comprehension_start.<locals>.<listcomp>)r=  rf  r   rh  r  r   )r   r  patternr0  r   r   r   r  q  s   
 z1InstructionTranslatorBase._is_comprehension_startc                 C  s|   t jdksJ | jdusJ d}t| jt| jD ]"}| j| }|jdkr*|d7 }q|jdkr;|d8 }|dkr;|  S qdS )zPFind the instruction pointer of the outermost END_FOR for current comprehension.rW  Nr   r]  r   rs  rb  )r=  rf  r   r`  r   r  r   )r   nesting_depth	search_ipr   r   r   r   r    s   



z8InstructionTranslatorBase._find_comprehension_end_for_ipr  c                   sN  t jdksJ jdusJ t  jd }g }g }g }t }|d }|dkrLj| }|jdkr=|d|j |d8 }n|jdv rG|d8 }nn|dks'|	| 
 }|dkratdd	d
g d tfddt||D }	t|	d |D ]i}
j|
 }|jdkr|jdkr|
d |k rj|
d  }|jdkr|j}||vr||vr|| || |jdkr||j qv|jdrt|jtr|jn|jf}|D ]}||vr||vr|| qqvg |d }|tjk rj| jdkrj| j |d7 }|tjk rj| jdks|}|tjk r<j| jdkr<|d7 }|tjk r<j| jdks'|tjk rJj| jndd$ fdd}d}|drej| j}d}n8|dr|d}d} d d ry|d n|}n!|ds d d krd}d}ntdd  d! d"g d t||||||d#S )%zDAnalyze comprehension bytecode to determine result handling pattern.rW  Nr   r   rc  )rz  r  rb  z)Comprehension analysis failed: No END_FORr   z=Could not find END_FOR instruction in comprehension bytecode.r  c                 3  s$    | ]} j | jd kr|V  qdS )r]  N)r  r   r]  r   r   r   r     s    zCInstructionTranslatorBase._analyze_comprehension.<locals>.<genexpr>ry  rt  r  r   r   r   r   c                   s*    |  }|d ko|d kp|d  S )Nr  r  r   )r   pat)patternsr  r  r   r   matches  s   zAInstructionTranslatorBase._analyze_comprehension.<locals>.matchesr  Fr  r  r  r  r  Tz)Comprehension analysis failed: No matcheszpre_store_ops=z, post_store_op=z8Comprehension does not match any known bytecode pattern.)r  r  r  r  r  r  )r   r   r   r   )r=  rf  r   r  r  r  r   insertr  r  r  r9   r   r`  r  r   r   rM  r9  r  r   r  )r   start_ipr  r  r  defined_insideiter_scan_ipr   r  for_iter_ipbody_ip	next_instvar_name	var_namesscan_ipstore_fast_ipr  r  r  r   )r  r  r  r   r   _analyze_comprehension  s   






	
 






z0InstructionTranslatorBase._analyze_comprehensionc                   s  t jdksJ   } jjtr |jr tdt	|jdg d  j
dus'J  j
d }dt|j td  g}td  jj |d	} fd
dtD }  |d }t jj}tdd |D }	t jt|j }
|g t|
 d |d|  ttD ]}|td || r||   q|t!dddg q|t!dg  "||||	|\}}|g t|
d |d| t!dddt|
d |d| t!ddd  #|g|g| |	dkr8|
d d }|g t||d| t$ ||	 |dt!dddt!dt!d |j%|j&rB|j&gng  }i }|D ] }t'  j(|< ||j)v r`|j)| ||< qIt|j)|j)|< qI|
d }|j%r|g t||d|  t*|j%D ]>\}}|g td||d |  ||v r|g td||| t!d q|t!dddg q|t!d|d| g |j+r ,t'  nH|j&r"|g t||d|  |j&|v r||||j& t!dg n|g tdt!dddt!d n|t!dg  j-|.   j/|j0 } j- 1|| d _
dS )zHandle list/dict comprehension graph break.

        Builds a synthetic function wrapping the comprehension bytecode,
        calls it via codegen_call_resume, then chains into the resume
        function for the post-comprehension code.
        rW  zDComprehension graph break in resume function with captured variableszCannot use comprehension optimization inside a resume function when there are captured variables. This can cause issues with deeply nested source chains.r  Nr   comprehension_graph_breakzcomprehension triggered compiler  c                   s*   g | ]}t  jt j |  tqS r   )r9  r^  r   r   r]  r   r  r   r   rJ  :  s    zOInstructionTranslatorBase._handle_comprehension_graph_break.<locals>.<listcomp>r   c                 s  s    | ]}|sd V  qdS )r   Nr   )r   mr   r   r   r   G  r  zNInstructionTranslatorBase._handle_comprehension_graph_break.<locals>.<genexpr>r  r  r  r  rd  r  r  r  )2r=  rf  r  r  r  rM  rK   r  r9   r   r   r   r  r>   r  r	  r  r  r  r`  r*  r1   r  ro  r^  r  r  r%   r  r  r   r*   pop_nullr'   _build_comprehension_fnr  r&   r  r  r   rX  r  rR  r  r)  r  rQ  r  r  r  )r   r   analysisr  r   r  stack_pops_null_maskr  r  nonnull_countlive_stack_depthrN  r  r'  frame_values_posvars_to_passexisting_varsr  fv_depthr  
walrus_varr  r   r  r   r    s^  	










	




z;InstructionTranslatorBase._handle_comprehension_graph_breakr  r  r  r  
list[bool]r  c                   sZ  ddl m} ddlm} ddlm m t	fdd|jD }	ddgt	|	 d	d
 t
D  ttt		jjp9g t		jjp@g  	jdurM	jn	jjtd	jj d jj jrijgng  j d 	
fdd}
|	j|
\}}|| |jr	j| |fS 	jt|	j |fS )a  Build a synthetic function wrapping comprehension bytecode.

        Uses the same calling convention as resume functions created by
        create_resume / ContinueExecutionCache.generate: the first two args
        are __nested_resume_fns and __nested_frame_values (ignored here),
        followed by stack items and live locals.

        Returns (code, name) where name is the global name for the function.
        r   )transform_code_objectr  )
CO_VARARGSCO_VARKEYWORDSc                 3  s     | ]}|   vr|V  qd S r   r~  r  r   r   r   r     s    zDInstructionTranslatorBase._build_comprehension_fn.<locals>.<genexpr>__nested_resume_fns__nested_frame_valuesc                 S  s   g | ]}d | qS )___stackr   r]  r   r   r   rJ    r3  zEInstructionTranslatorBase._build_comprehension_fn.<locals>.<listcomp>N__comprehension__at_r  r  r  r   r   r   c                   s  |d< t jdkr|d< |d< d|d< |d< t|d< d	|d
< d	|d< tfddD  |d< |d  B  @ |d< g }rP|tdtd |tdd	d d }t
D ]}| ro|td qa|tdd| d |d8 }qa	j}g }j	sj
r|tdj
d n	|tdd d jrÈjD ]}|td|d q|tddtj d |td || | | d d < d S )Nr  r  r$  co_firstlinenor   rw  rz  co_argcountr   co_posonlyargcountco_kwonlyargcountc                   s   g | ]}| vr|qS r   r   )r   r   r  r   r   rJ  :      zUInstructionTranslatorBase._build_comprehension_fn.<locals>.update.<locals>.<listcomp>co_varnamesco_flagsr  r  rq  r   r  r  r  r  r  r  rq  )r=  rf  r   r  r   r'   r`  _copy_comprehension_bytecoder  r  r  r  )r  r  r0  	nonnull_irN  
comp_instsepiloguer  r  r  r  r   comprehension_body_varsr'  r{  r   r  r   r  r  r  r   r   r  -  s\   



zAInstructionTranslatorBase._build_comprehension_fn.<locals>.update)r  r  r  r   r   r   )bytecode_transformationr  r  r  resume_executionr  r  r  r  r   r`  sortedr  rw  rz  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    sP   &?z1InstructionTranslatorBase._build_comprehension_fnr  c                 C  sr   i }g }t ||D ]}| j| }t|}d|_|||< || q	|D ]}|jdur6|j|v r6||j |_q$|S )z@Copy comprehension bytecode instructions, updating jump targets.N)r`  r  r!  r"  r   r  )r   r  r  inst_mapcopied_instsr  original_instcopied_instr   r   r   r  z  s   

z6InstructionTranslatorBase._copy_comprehension_bytecoder   fallback_linenotuple[str, int]c                 C  s    |d u s|dk r||fS ||fS r   r   )r   r   r   r  r   r   r   _make_frame_loc  s   z)InstructionTranslatorBase._make_frame_loc	frame_loctuple[tuple[str, int], ...]c                 C  sb   g }t jr$| j}|d ur$| |jj|j|jj}|| |j}|d us|	  || t
|S r   )r   r  r  r  r  r  r   r  r   reverser  )r   r  frame_loc_chain_list
current_txparent_frame_locr   r   r   _get_frame_loc_chain  s   
	
z.InstructionTranslatorBase._get_frame_loc_chainr  r   r   Unsupported | StepUnsupportedc                   s  |j rd S t|dd }|d u rtjj }z$tjr+| jd ur+| 	| j
j| j| j
j}n| 	|d j|d jd}W n tyJ   |d |d f}Y nw | |}d}tjrat }dt|}n	t | }t|}dt|}	|d ur{t||}d|d  d|d	  d
| d tjr | d|	 d7  n t|	7  tjjddd  fddd t|tr|jnt|}
t t!j"rt#st$%|
|frtjrڈ d7   d| j&d 7  t'  nt'd|d |d	 | d|_ d S )Nr  rb  r   r  r  r   zGraph break in user code at r   r   z
Graph Break Reason: z

User code traceback:
zQ
========== most recent `torch.compile` tracing attempt started here ==========

a}  
NOTE: the most recent `torch.compile` tracing attempt might not be where you applied `torch.compile`! This is due to how graph breaks are implemented - the optimized code object returned by Dynamo will call another Dynamo-generated resume function and tracing is re-enabled by calling the resume function as a normal Python function, which Dynamo intercepts as a top-level frame.
artifactc                   S  s
   dddS )Ndynamo_graph_break_reasonstring)r   encodingr   r   r   r   r   r     s   z;InstructionTranslatorBase.log_graph_break.<locals>.<lambda>c                     s     dt   S )Nr   )r  
format_excr   user_stack_tracer   r   r     rK  )metadata_fn
payload_fnz4
Most recent bytecode instructions traced (max 20):
r   zmGraph break (user stack suppressed due to duplicate graph break) in user code at %s:%s
Graph Break Reason: %sT)(loggedr  r  ri  r   rj  r   r  r  r  r  r  r   r  r   
IndexErrorr  r  r6   r   r  r  r4   r2   r   _loggingtrace_structuredr9  r:   r  r  graph_break_logisEnabledForr   DEBUGexplainr[   r   ro  r  )r   r  r   r   
user_stackr  frame_loc_chainstack_above_dynamo_formattedstack_above_dynamouser_stack_formattedr  r   r  r   r    s   






z)InstructionTranslatorBase.log_graph_breakr  types.CodeTyper:   c                 C  s(   t ddt|  dg tj|dd d S )Nzgraph break in loopzframe skipped: ztorch.compile detected a graph break in a for/while loop. Skipping the frame and falling back to eager, as graph breaks in loops are not supported.T)r  r  r  r  r  r  )r9   r5   r   r  )r  r   r   r   r   r    s   
z0InstructionTranslatorBase.raise_loop_graph_breakr  r  r  r  r  exportr  r   distributed_stateOptional[DistributedState]r)  Optional[tuple[types.CellType]]rG   Optional[dict[Instruction, int]]c                   s  t    || _|| _|| _|| _|| _|	| _|
| _d | _	g | _
d| _d | _td| _d| _g | _g | _d| _d | _d| _g | _|| _tdd| _d| _t | _|| _|d urY|nt| j| _|| _|| _ || _!|| _"|| _#|| _$|d urt%j&rt'|||d| _(nd | _(i | _)i | _*|| _+d| _,d| _-d| _.d | _/d | _0d| _1d | _2d| _3g | _4|| _5d	d
l6m7}m8}m9}m:} |j;||B |B |B @ r| <t=d  || _>d| _?d gt@|jA | _BtCDtEjF| _GtHDtEjF| _ItJK|jL| d S )Nr   r  Trb     )maxlen)r  r)  r  Fr   )CO_ASYNC_GENERATORCO_COROUTINECO_GENERATORCO_ITERABLE_COROUTINE)Mr5  r6  r  r  r  rX  rY  rZ  r[  r\  r^  r   ri  r'   r`  r  r  r	  r   r   ra  rb  rf  r   ro  r  r  r  r  r   rG  r  r  r  r  r  r)  r   replay_record_enabledrG   rg  nn_module_stack	num_callsr  r
  r   r  re  rh  rj  r  rk  rl  rn  r  r$  r%  r&  r'  r  r)  re   rc  rd  r   rt  r  r  r  r   r  r  r  r  r  	lazycacher  )r   r  r  r  r  r  r  rX  rY  rZ  r[  r  r  rc  r  rf  r  r)  rn  rG  r$  r%  r&  r'  r7  r   r   r6  #  s   




z"InstructionTranslatorBase.__init__r   r  r   rA  )r%  ra   r   r]  r  rW  r   r   )r%  rn   r   r  r  rW  r   ra   )r%  rn   r   r  r  rW  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   r   r   ra   )r  r   r   r]  )r   r,   r   ra   )r  r   r   rN   )r   r   rn  r   r#  r   r   r   )r  r   r   ra   )r   rD  r   r   )r@  ra   r   ra   )r   r   r   r   )r@  ra   r   r   )r@  ra   r   ry  )r  r   r   r   )r  r   r   r   )r   r,   r  r   r   r  )r~  r   r  r,   r  r@   r  r  r  r1   r  r   r  r   r   r  r   r,   r  r  r   r  )r  r  r  rA  r  r1   r   r   )r   r,   r   r   )r   r,   r   r  r   r   )r  ra   rB  r   r   ra   )rE  ra   r&  r   r   r   )F)r   r,   ru  r   r   r   )rK  r}  r   r,   r   ra   )rK  ra   r   r   )r  r  r   r   )r   r  )r0  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  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   )NNN)(r  r?   r  r  r  r   r  r   r  r   r  r   rX  rW  rY  rW  rZ  r   r[  r   r  r  r  r   rc  r   r  r   rf  r:  r  r  r)  r   rn  rm  rG  r!  r   r   (  r   r   r   r   rp  r  ry  r{  r}  r  r   r  r  r  r  rw  r  r=  rf  r  propertyr  r  r  r  r)  r  r  r*  r  r  rt  r  r   LOAD_CLOSUREr  r  r  r3  cached_propertyr  r  r  r   r  r(  r0  r;  EAGER_IMPORT_NAMEr>  rC  r  r  JUMP_FORWARDJUMP_ABSOLUTEr  r  not_r  r  r  JUMP_IF_FALSE_OR_POPJUMP_IF_TRUE_OR_POPrJ  rL  rM  rQ  rR  rS  rT  rV  r]  r^  rd  rm  rO  rv  rs  rh  r  r  r  r  r  r  r  r  r  r(  r  r  r  r  r  r  r  r=  r  r  r  staticmethodr  r  r  r  r  r  r  r  r  r  r	  rd  r  rz   r  r  BUILD_TUPLE_UNPACK_WITH_CALLr  r  BUILD_MAP_UNPACK_WITH_CALLr  r  r  r"  r  r+  r  r6  r7  r  r  r=  r?  r@  r<  rA  rD  rK  rL  rS  rW  r]  r  r^  r`  ra  DICT_UPDATErb  rc  rd  rf  ri  rj  rm  ro  r5  r|  r  negUNARY_NEGATIVErZ  invertUNARY_INVERTpowBINARY_POWERmulBINARY_MULTIPLYmatmulBINARY_MATRIX_MULTIPLYfloordivBINARY_FLOOR_DIVIDEtruedivBINARY_TRUE_DIVIDEr6  BINARY_MODULOBINARY_REMAINDERr   
BINARY_ADDsubBINARY_SUBTRACTgetitemBINARY_SUBSCRlshiftBINARY_LSHIFTrshiftBINARY_RSHIFTand_
BINARY_ANDor_	BINARY_ORxor
BINARY_XORipowINPLACE_POWERimulINPLACE_MULTIPLYimatmulINPLACE_MATRIX_MULTIPLY	ifloordivINPLACE_FLOOR_DIVIDEitruedivINPLACE_TRUE_DIVIDEimodINPLACE_MODULOINPLACE_REMAINDERiaddINPLACE_ADDisubINPLACE_SUBTRACTilshiftINPLACE_LSHIFTirshiftINPLACE_RSHIFTiandINPLACE_ANDixorINPLACE_XORior
INPLACE_ORrq  rs  r  r  r  rw  r  ry  rz  r  JUMP_BACKWARD_NO_INTERRUPTPOP_JUMP_FORWARD_IF_TRUEPOP_JUMP_BACKWARD_IF_TRUEPOP_JUMP_FORWARD_IF_FALSEPOP_JUMP_BACKWARD_IF_FALSEr{  r|  r  r  rP  rp  r  r  r  rs  r  rc  r  r  r  r  r  r  r  r  r  LOAD_FAST_BORROWr  POP_ITERr  r  r  r  r  r  r  r  r  r  r  
contextlibcontextmanagerr  r  r  r  r  r  r  r  r  r  r  r  r6  r9  r   r   r7  r   r     s  
 #

q. EJ#	

>
	/"& S@		 D *s#		
' 
	
!			
































/%

!
  g n$)	metaclassc                      s   e Zd Zed6ddZejd7ddZd8 fd"d#Zd9d$d%Z	d:d(d)Z
d;d*d+Zd9d,d-Zd<d0d1Zd<d2d3Zd<d4d5Z  ZS )=r(  r   c                   C  s   t jS r   )tlsr  r   r   r   r   r    s   z InstructionTranslator.current_txr   c                 c  s0    t tdd }| t_z	d V  W |t_d S |t_w )Nr  )r  r  r  )r   r  r   r   r   set_current_tx  s   z$InstructionTranslator.set_current_txr  r  r  r  r  r   r  r  r)  Optional[tuple[Any, ...]]torch_function_mode_stackr  compiler_fnr
  r   r  export_constraintsframe_stater  r   rf  r:  r  r  rn  rm  r   c                   s  t  tjd|j d|d  d|d   t jd i dt||	| ||||||||
|dd|d	|d
|d|d|d|di di dd dd d|d|ddd|d|d|d| |   t| j	j
 |   |
| _|| _| jr| jsJ di | _t|  }t|dd }| D ]&\}}||vrd }|rt||i  }t|t|d|d}|| j|< q| j	j}|  D ].}||v r|| }t|ddd}t||}| }||| n| }||_|| j|< q|d usJ t|  |D ]6\}}t |}t|dd}z	t|j!|}W n t"y'   t#$ }Y nw |%|||}||_|| j|< qt&|| _'t( | _)|rMt#j*| j| _W d    n1 sXw   Y  W d    d S W d    d S 1 sqw   Y  d S )!Nztorchdynamo start tracing r  r  r   r  r  )local_scoper   r  r  r
  rn  r  r  r  r  r)  r  rX  rY  rZ  r[  r  r  rc  r   r  rf  r  rn  z4Export without one graph - something has gone wrong.dynamismT)is_inputr  )r  is_derefed_cell_contents)r  r   )+r
  r   INFOr  r5  r6  r?   _throw_if_in_functorchr   r  r  r  r
  r  rX  r  r}  r0   r  r1  r   	frozensetrv   r  rQ   r  ry  r  r  r  r  r{  rP   cell_contentsr  r   DeletedVariabletrack_cell_existingr   rZ  r   r[  realize_all)r   r  r  r  r  r  r)  r  r  r  r
  r  r  r  r  rf  r  rn  r}  r  r   r  local_dynamismvarr  contents_sourcer  cell_varr  cell_sourcer7  r   r   r6    s    #
TzInstructionTranslator.__init__c                 C  s   t jd}t| jjd| jj}t jj	 }t jjj
jt jjj
jt jjj
jf}|d urS| |v rU||urW| j }d| d| d| d}tdd|g d	 d S d S d S d S )
Neagerr  zhIf you are reaching here, it means dynamo failed for one of the following reasons:
- Calling torch.func.zP(compiled_fn) function from eager mode is not supported. Ensure that torch.func.zp is also wrapped within a torch.compile function. For more information, see PyTorch issue #128711.
- torch.func.z2(fn) requires the function to be inlined by dynamoz%Unsupported functorch tracing attemptr   r  )r  _dynamolookup_backendr0  getattr_staticr  r  _C
_functorchpeek_interpreter_stackTransformTypeVmapGradJvpr  r   lowerr9   )r   r  r  ciforbidden_keysr   rC  r   r   r   r  Y  s4   


	
z,InstructionTranslator._throw_if_in_functorchr  rS   c                 C  s0   t |tr| j|j S t |tr| j|j S tr   )r9  rQ   r  r  rN   r  r  r  )r   r  r   r   r   get_example_valuex  s
   

z'InstructionTranslator.get_example_valuec                 C  s6   | j  D ]}t|trt| tjjr dS qdS r   )	rX  r  r9  r   r  r  r  nnModule)r   r   r   r   r   $symbolic_locals_contain_module_class  s   z:InstructionTranslator.symbolic_locals_contain_module_classc                 C  sL   t | jr | jd  }r"t|tr$t|| t d| jd< d S d S d S d S )Nrb  r  )r   r^  r9  rp   ry   r  r`   )r   ru  r   r   r   "replace_tos_if_return_is_generator  s   z8InstructionTranslator.replace_tos_if_return_is_generatorr   r,   c                 C  s(  |    | jd usJ | jd usJ t d| j| j  tjsE| j dkrE| j	sE| 
 sE| jsE| jsE| jsE| jsEtdt| j d | _t tjd| jj d|j d td | jj| td|  gd	d
|jdkrrdndd}t|dks~J |d jrJ | j|  ||d j! t")NrE  r   zhNo ops traced for the FX graph. `torch.compile` will skip the frame and fall back to eager.
Frame info: ztorchdynamo done tracing r   r  zreturn triggered compilereturn_valueF)r  rq  r   r  )#r  r   ri  rZ   rF  r   allow_empty_graphsr  r  rd  r  r  r
  r   r  r   	SkipFramer5   r  r
  r   r  r  r   r	  r  r  r>   r  r   r  r  r  r  r#  r   r   r  r   r   r   _return  sZ   	

zInstructionTranslator._returnc                 C  rN  r   r  r+  r   r   r   rq    r  z"InstructionTranslator.RETURN_VALUEc                 C  rN  r   r  r+  r   r   r   rr    r  z"InstructionTranslator.RETURN_CONST)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   rf  r:  r  r  rn  rm  r   r   r   )r  rS   r   r   r  r-  )r   r   r   r;  r  r  r  r  r6  r  r  r  r  r  rq  rr  r9  r   r   r7  r   r(    s     
&




/r(  r  c                 C  s<   g | ]\}}t td |v r|dd nd|dd  qS )INPLACErX  NBINARY_)r  r(  )r   r   r   r   r   r   rJ    s    $rJ  r  r?   r  r  get_inline_depthCallable[[], int]c                 c  s   t js	dV  dS | jdu rt | _| j }| j }| j|j|j|j	t
  d}z]dV  d}W | j }t
 }|r|dur| }||j }	|	|j }
t|j|j|j|	|
t|j||rc|d nd|rj|d nd|rq|d nd|j|d}| j| | j|	 dS dS dS | j }t
 }|r|dur| }||j }	|	|j }
t|j|j|j|	|
t|j||r|d nd|r|d nd|r|d nd|j|d}| j| | j|	 w w w )a[  
    Context manager for profiling inline calls.

    Args:
        output: The OutputGraph containing profiler_state
        code: The code object being inlined (for timing metadata)
        get_inline_depth: Callable that returns inline_depth (called after work completes)

    Yields:
        None (profiling happens around the with block)
    NFTr   r   r  )	func_namer   firstlineno
cumtime_ns
tottime_nsbytecode_countrc  caller_func_namecaller_filenamecaller_firstlinenois_primitive_call
call_stack)r   dynamo_profilerprofiler_stater   get_current_callerget_call_stackr)  r  r  r  timetime_nsr  start_time_nschild_time_nsr   r  r   r  r   co_coder  record_timingadd_child_time)r  r  r  caller_infor  trace_successstack_entrytrace_end_nsrc  r  r  timingr   r   r   profile_inline_call  sz   








r  c                      s   e Zd ZU dZded< ded< edCddZedDddZedEddZ	dFddZ
dG fd#d$ZedHd&d'ZdId(d)ZdJd+d,ZdJ fd-d.ZdK fd4d5ZdLd6d7ZdLd8d9ZdMd=d>ZdL fd?d@ZdL fdAdBZ  ZS )Nr  z Trace and inline a called methodr  symbolic_resultr   r  r   funcrn   r   r  r  rW  r   ra   c                   sZ   d }t  j|  fdd |  |||}| W  d    S 1 s&w   Y  d S )Nc                     s
    j d S rQ  rc  r   r  r   r   r   !  s   
 z;InliningInstructionTranslator.inline_call.<locals>.<lambda>)r  r  r  build_inline_tracerinline_call_)r   r  r  r   r  tracerr   r  r   r    s   $z)InliningInstructionTranslator.inline_calltrace_rules.SkipResultc              
   C  sF  |   rtdt| dg d t| tr;t|  ddr;t|  dd }tdt|  d|   d	| d
dgd tj	| dd}|j
rddlm} t| drbt| jdrb| jj|u rbtddS t| drk| jjnd}d| dg}d|  vr|d| ddg7 }tdd| d|   d|   d|j d| d |d |S )!NzInline attempt with __self__zAttempted to inline a function with the `__self__` attribute. Dynamo is expected to decompose method calls into function calls with a `self` argument.r  _torchdynamo_disableF_torchdynamo_disable_msgz2Skip inlining `torch.compiler.disable()`d functionzSkip inlining function z= since it was wrapped with `torch.compiler.disable` (reason: r  z(Remove the `torch.compiler.disable` callT)is_inlined_callr   )!produce_trampoline_autograd_applyr%  _originz"allowlist in dynamo known functionr   zAvoid calling the function `r,  r  z:Apply `@torch._dynamo.dont_skip_tracing` to the function `zw` to force tracing into the function. More graph breaks may occur as a result of attempting to trace into the function.z Please file an issue to PyTorch.z.Attempted to inline function marked as skippedz
qualname: z, name: z, filename: `z`, skip reason: z?Dynamo developers have intentionally marked that the function `z` should not be traced.)has_selfr9   r   r9  rs   r0  r  get_functionr   check_verboseskippedtorch._dynamo.variables.miscr  r  r%  r  
SkipResultr   get_filenameget_namer   )r  rC  rj  r  fn_qualnamer  r   r   r   check_inlineable&  sh   







	z.InliningInstructionTranslator.check_inlineablec                   s  t |tttfs
J |  d }jj}tjs$|r$|j	
 d  }r$|}|d u r>t|}|jdu s4J tjs>|r>||j	 < d }z	|||}W n? ty } z3tdd|  d|  d| j ddd |D  d	| 
d
|  dg tj|d W Y d }~nd }~ww |d usJ t| D ]}	t |	tstdd| d|	 dg tjd q jdv r|rt |d tjstdd j d| d j dg d d}
tjj j!"drdt#$ #  }
t%j&dkrj'j(d$ fdd }t)*d!t+| t,*d" |
|j- |r5t |d t.r5j/|d j0}t |tj1j2r5t34|t56|j7j8d#< |rYt |d t9rY|d j:}t |tj1j2rYt34|t56|j7j8d#< t |t;raJ t< rut= |j>j?j@|}|S t |j>j?j@|}|S )%NFz2failed to bind arguments when attempting to inlinezfunc='z' r   z	; args = c                 S  s   g | ]}|  qS r   )r  )r   r  r   r   r   rJ    r  zEInliningInstructionTranslator.build_inline_tracer.<locals>.<listcomp>z; kwargs = z4Argument mismatch when attempting to trace function r8  r  z:Encountered unconverted argument when attempting to inlinezfunc: z, arg: zWAn argument to an inlined function was not successfully converted to a VariableTracker.r  )r  r_  r   z2Unsupported __setitem__/__setattr__ inline attemptzcode name: z, args: zAttempted to inline z: where first argument (self) is not a user-defined object.r   bytecoder   r  r   r   c                    s6   j jjd} t }d j d|  d| S )N)r   zTRACE inlined call z from r   )r  rx  r   rY   r  r  )headerr  r  cur_instr  parent_coder   r   get_trace_call_log_str  s
   zQInliningInstructionTranslator.build_inline_tracer.<locals>.get_trace_call_log_strr  zINLINING %s%s, %sr  r   )Ar9  rs   rq   ro   r  r  r  r   dont_skip_tracingpreviously_inlined_functionsr1  r  r  r  	bind_argsr  r9   r  r  r  r   r  r  r  r  ra   r  r  r   r   r  r  	_internal	log_stateis_artifact_enabledrP  Bytecoder=  rf  r`  r  trace_call_logr  r]   r	  r   r   r  r  r  r  r  r  r0   r  forwardrv  r   r  rr   r-   &InliningGeneratorInstructionTranslatorrY  rZ  r[  )r  r  r   r  rj  tracing_ctxprevious_result
sub_localsr  r   r1  r  moduler  r   r  r   r  h  s   



"



	z1InliningInstructionTranslator.build_inline_tracerc              
   C  s  | j }d|_d|_| j}t }|jr| |j}zYz| |   W d    n1 s,w   Y  W n7 t	j
yM } zd| d| }t|  d }~w ty\ } zd|_ d }~w tyi   td|  w W | j|_d|_n| j|_d|_w | jjrtS | jd usJ | j|ju r|j| j | j| jO  _td| | jjj| tjst| tr| j rt!|rt| tr| j"rt| tsJ g }| j# s| jg}t	j$t%| |d d S | jS t!|rt| tsJ | j# sJ t&| j't( dS | jS )	NFTz!Observed exception DURING INLING z : zFAILED INLINING %szDONE INLINING %sr  r  ))r  rj  rk  r  r  nullcontextrh  r  r  r   r   r	  r  r:   r  r  r   r  r  rf   r  r  rY  r  rd  r  traced_coder   r   r  r9  r  is_generator_from_ctx_managerr-   generator_exhaustedis_constant_noner  rZ  ry   generated_itemsr`   )r   r  r  
strict_ctxr  rC  r   r   r   r   r    s~   


z*InliningInstructionTranslator.inline_call_r  r  rX  rY  rZ  r   r[  r   funcvar7BaseUserFunctionVariable | LocalGeneratorObjectVariabler   c                   sZ  |  }|d }	t|	ts|	j}	|jj}
|
r|
j nd }|d ur,|j}|j	}|j
}n"t }t| t|} fddt D }|
rNt|||d|
j < t jdi d|jdi d|d|	d	|d
|d|d|d|d|d d|jd|jd d|jd|jd|jd|jd| || _|| _|j| _d | _|j | _|j| _d S )N__builtins__c                   s   i | ]}|t  |qS r   )r  r  r  r   r   r   W  r  z:InliningInstructionTranslator.__init__.<locals>.<dictcomp>)r  rG  r  r  r  r  r  rX  rY  rZ  r[  r  r  r  r  rc  r   r  rf  r  rn  rG  r   )get_globalsr9  r   __dict__r  r  inlined_code_cacher1  r  rG  r  r!   r    r   r+   r   r5  r6  r  rc  r  rf  r  rn  r  r  r*  r  r)  r!  r
  )r   r  r  rX  rY  rZ  r[  r  r  r  r  cachedr  rG  r  r7  r  r   r6  ;  s~   

	

z&InliningInstructionTranslator.__init__r  c                 C  s   | j jS r   )r  r  r   r   r   r   r  z  s   z'InliningInstructionTranslator.fake_modec                 C  s   t | j S r   )r   r  r  r  r   r   r   r   r  ~  rE  z)InliningInstructionTranslator.run_ctx_mgrr   c                 C  s*   t jsdS | j sdS | j sdS dS )zCheck if comprehension speculation is allowed in this inlined context.

        Unlike should_compile_partial_graph(), this skips the exception table entry check.
        FT)r   r  r   should_allow_nested_graph_breaksr  r  r   r   r   r   r    s   

zAInliningInstructionTranslator._can_speculate_comprehension_nestedc                   s0   t jr| j s
dS | j sdS t  S dS r  )r   r  r  r  r  r  r5  r   r7  r   r   r    s   


z:InliningInstructionTranslator.should_compile_partial_graphr   r,   r  r  r  c                   s(   t jr
t ||S tdddg d d S )NzGraph break in inlined functionr   z2Graph breaks in an inlined call are not supported.r  )r   r  r5  r  r9   r  r7  r   r   r    s   
z3InliningInstructionTranslator.create_call_resume_atc                 C  s   |   | _d | _tr   )r  r  r   r#  r+  r   r   r   rq    s   
z*InliningInstructionTranslator.RETURN_VALUEc                 C  s   |  || _d | _tr   )r  r  r   r#  r+  r   r   r   rr    s   z*InliningInstructionTranslator.RETURN_CONSTr   r   #tuple[Any, VariableTracker, Source]c           	      C  s   d| j v r4| j d ds4| j d }| |}d|v r#tjjj| }nt|}t| ||}t	||}n| j
d| j }t|}| j }t| ||}t||}t|rWt|}|||fS )Nr   namedtuple_r  ___unnamed_scope)r  rM  r  r  rn  r  r  r   rc   rL   r  r  rN   rM   r?  rR   )	r   r   r  r  r  fglobals_vtglobal_sourceglobals_nameglobals_sourcer   r   r   get_globals_source_and_value  s.   



z:InliningInstructionTranslator.get_globals_source_and_valuec                   s   |j }|| jvr| |S | jj| ju rt | d S | |\}}}| jj	||r9| 
| jj|| d S | j| }| 
t| || d S r   )r  r  r  r  r   r5  r  r  r  has_pending_mutation_of_attrr)  	load_attrra   r	  )r   r   r   r   r  r  r  r7  r   r   r    s   


z*InliningInstructionTranslator._load_globalc                   sn   | j j| ju rt | d S |  }t|tr!td|j	dg d |j	}| 
|\}}}| j j||| d S )Nz3Storing Tensor hook handle in globals (inline call)r  r  )r  r   r  r5  r  r  r9  r   r9   r  r  r  
store_attr)r   r   r  r   _fglobals_valuer  r   r7  r   r   r    s   
z*InliningInstructionTranslator.STORE_GLOBAL)
r  r   r  rn   r   r  r  rW  r   ra   )r  rn   r   r  )
r  r   r  rn   r   r  r  rW  r   r  r/  )r  r   r  r  rX  rW  rY  rW  rZ  r   r[  r   r  r  r   r   r1  r.  r  r0  r-  )r   r   r   r  )r   r   r   r   r   r  r  r;  r  r  r  r6  r2  r  r  r  r  r  rq  rr  r  r  r  r9  r   r   r7  r   r    s0   
 A 
M?

	


*r  c                      s   e Zd ZU ded< d fdd	Zd fddZd ddZd!ddZd!ddZd! fddZ	d! fddZ
d!ddZd!ddZ  ZS )"r  r]  r  r   r   r  r   r   c                   s(   t  j|i | g | _d| _d| _d S r  )r5  r6  r  r   r  )r   r   r  r7  r   r   r6    s   
z/InliningGeneratorInstructionTranslator.__init__ra   c                   sF   t  j j fdd t  W  d    S 1 sw   Y  d S )Nc                     s    j S r   r  r   r   r   r   r     s    zEInliningGeneratorInstructionTranslator.inline_call_.<locals>.<lambda>)r  r  r  r5  r  r   r7  r   r   r    s   $z3InliningGeneratorInstructionTranslator.inline_call_r   c                 C  r   r  r   r   r   r   r   r    s   zCInliningGeneratorInstructionTranslator.should_compile_partial_graphr   r,   c                 C  sL   |   }| j| t| jtkrtj| t t	j
s| jr$|| _td S r   )r  r  r   r   ru   r   InfiniteGeneratorErrorr)  rf   r   r  r  r  r$  )r   r   topr   r   r   YIELD_VALUE  s   
z2InliningGeneratorInstructionTranslator.YIELD_VALUEc                 C  sB   | j d }t|ts|   tt| |gi }| | d S d S re  )r^  r9  ry   r  re   r  r   r)  )r   r   ru  resr   r   r   GET_YIELD_FROM_ITER  s   

z:InliningGeneratorInstructionTranslator.GET_YIELD_FROM_ITERc                      d| _ t |S r  )r   r5  rq  r+  r7  r   r   rq  $     z3InliningGeneratorInstructionTranslator.RETURN_VALUEc                   r  r  )r   r5  rr  r+  r7  r   r   rr  (  r  z3InliningGeneratorInstructionTranslator.RETURN_CONSTc              
   C  s   t | jdks	J |  }| jd }| stdddg d z|| }W n. ttjfyS } zt	|tjr;t
|  |   | t|j W Y d }~d S d }~ww t	| jtr_| jdksaJ |  jd8  _| | | | d S )	Nr  rb  Unreachable sub-generator coder   @Should only be encountered while implementing generator support.r  r   r   )r   r^  r  r  r9   rY  rZ  r   r[  r9  r  r)  rg   r  r  r   r   r  r   r   r@  ru  exr   r   r   
YIELD_FROM,  s2   

 


z1InliningGeneratorInstructionTranslator.YIELD_FROMc              
   C  s
  t | jdks	J |  }| jd }t|ttfs&t|trpt|jtj	j
rp| rfz|| }W n- ttjfy^ } ztjdk rE|   | t|j | | W Y d }~d S d }~ww | | d S tdddg d d S tdd	t| d
t| dg d d S )Nr  rb  rW  r   r   r!  r  zSEND with bad typez
TOS type: z(Attempted to SEND with unsupported type r8  )r   r^  r  r9  rx   rp   r   r  collectionsabcIteratorr  rY  rZ  r   r[  r=  rf  r)  rg   r  r  r9   r_   r"  r   r   r   SENDR  s>   



z+InliningGeneratorInstructionTranslator.SEND)r   r   r  r   r   r   r/  r  r-  )r   r   r   r   r6  r  r  r  r  rq  rr  r$  r(  r9  r   r   r7  r   r    s   
 



&r  )r   r   r   r   )r   r  )r   r   r   r  )r%  r&  r   r'  )r6  r7  r   r   )r@  r   r   rA  r,  )r   ri  )r   r   r  r  r)  r   r   r   )r  r  r)  r   r   r  )r   r   r  r1   r  r  r   r   )r)  r   r  r   r   r  )r  r?   r  r  r  r  r   r  (  r   
__future__r   r%  collections.abcr  r!  r   rP  r3  r   r0  r  r  r   r  r  r=  	threadingr  r  r:  r  r   typingr   r   r   r   r   r	   r
   typing_extensionsr   r  torch._loggingtorch._dynamo.dynamo_profilerr   r   torch._dynamo.excr   r   torch._guardsr   r   r   torch._logging.structuredr   %torch.fx.experimental.symbolic_shapesr   torch.utils._functoolsr   r   r   r   r   r  r   r   bytecode_analysisr   r   r   r    r  r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   codegenr1   r2   r3   r4   r5   r6   r7   r8   r9   r:   funcname_cacher;   guardsr<   r=   output_graphr>   r?   r@   	polyfillsrA   rB   rC   rD   rE   replay_recordrF   rG   r  rH   rI   rJ   rK   r  rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   utilsrV   rW   rX   rY   rZ   r[   r\   r]   r^   variables.baser_   r`   ra   variables.builderrb   rc   rd   variables.builtinre   variables.constantrf   rg   variables.ctx_managerrh   ri   rj   rk   variables.dictsrl   rm   variables.functionsrn   ro   rp   rq   rr   rs   rt   variables.iterru   variables.lazyrv   variables.listsrw   rx   ry   rz   r{   r|   variables.miscr}   r~   r   r   r   r   r   variables.nn_moduler   r   variables.streamsr   variables.tensorr   r   variables.torch_functionr   r   variables.user_definedr   r   r   r   r   r   r   r   torch._subclasses.fake_tensorr   rn  r   	getLoggerr   r	  r  getArtifactLoggerr  r  r  r  r  r  r   r   r   containsr   r   r8  r   r   cacher   	dataclassr   r   r   r   r   r
  r  r  r  r  r  r   r  r#  r$  r5  r?  rV  rh  r  r  r  r  r  r   r(  r  r)  r:  r   r(  rf  _nb_opsrr  r  r  r  r   r   r   r   <module>   sd   $ D,(
,$	 $		
	F$

A
*
!  
! 
b                               q  $	=   p