o
    j9:j                    @  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 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l/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6mZ7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN ddlOmOZO ddlPmQZQ ddlRmSZS ddl5mTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z] ddl^m_Z_ ddl`maZambZb ddlcmdZdmeZemfZf ddlgmhZhmiZimjZjmkZkmlZl ddlmmnZnmoZo ddlpmqZqmrZrmsZs ddltmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z| ddl8m}Z}m~Z~ ddlmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZmZ dd lmZmZ dd!lmZ dd"lmZmZmZmZ dd#lmZ dd$lmZmZmZmZmZmZmZ dd%lmZ dd&lmZ dd'lmZmZmZmZmZmZ dd(lmZmZmZmZmZmZmZ dd)lmZmZ dd*lmZ dd+lmZ dd,lmZmZmZ dd-lmZmZ dd.lmZmZmZmZmZ er<dd/lmZmZmZ dd0lmZ dd1lmZ eeԡZe!j֠ed2Ze!j֠ed3Ze!j֠ed4Ze!j֠ed5Zeܡ Zd6d7 eޡ D Zd8ed9< eejjZeejjZd:d; ed<< d=d; ed>< e9jeB eB Zd?ed@< e	jddEdFZejG dGdH dHZejG dIdJ dJZejG dKdL dLZejG dMdN dNZG dOdP dPZe	jddRdSZejddWdXZejddYdZZejG d[d\ d\ZG d]d^ d^eZG d_d` d`eZG dadb dbeZddfdgZddkdlZe	jddodpZddudvZdwZddzd{ZddddZdddZ dddZdddZG dd deZejG dd dZG ddU dUedZG dd deZejdkrsdd 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TYPE_CHECKING	TypeAliasTypeVar)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)%maybe_setup_comprehension_speculation)
!augment_exc_message_with_hop_nameBackendCompilerFailedcollapse_resume_framesformat_frame_infoget_stack_above_dynamoResumePrologueTracingErrorStepUnsupportedunimplementedUnsupported	UserError)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)
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DictBuiltinVariable)ConstantVariable)ContextWrappingVariableGenericContextWrappingVariableWithEnterFunctionVariableWithExitFunctionVariableConstDictVariable)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)SetVariable)SymbolicStreamState)supported_comparison_opsSymNodeVariableTensorVariable)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   e/home/nk/hobo-godmode/plappi-mvp/.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bool | Noneerror_on_graph_breakzGraphCompileReason | None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
< eje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_grad	list[str]autograd_grad_leaked_tensorsgraph_break_on_requires_grad_r   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   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>e  s    
z$LocalState.render.<locals>.<genexpr>)joinr   itemsr   r   r   r   r   d  s   
zLocalState.renderNr   r   )	r   r   r   r   r   dictr   r   r   r   r   r   r   r   ^  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list[LocalState] | None
all_states)r   r   r   r   r   r   r   r   r   r   k  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   
specializex  s   zTensorifyState.specializer   c                 C  s
   || j v S r   )r   r   r   r   r   should_specialize|     
z TensorifyState.should_specializec                 C     | j   d S r   )r   r   r   r   r   r   r        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   r  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_indexNz?ContextWrappingVariable | GenericContextWrappingVariable | Nonewith_contextr   r   c                 C  s
   | j d uS r   )r  r   r   r   r   can_restore  r   zBlockStackEntry.can_restorerK   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  rK   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   rK   )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*  r4  r   r1  r   stack_op  s
   r:  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)r;  r   r   r   	is_stdlib  s   rD  with_msgr   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   rF  r   r   r   r*       z(get_assert_bytecode_sequence.<locals>.fnc                 S  s   | sJ d S r   r   rH  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   )rF  r   r   r   )disget_instructionsr   	enumerater   )rE  r*  insts	begin_idxend_idxr   r   r   get_assert_bytecode_sequence  s   

rZ  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 ]:}t|}| j||t|  }dd |D }||krP|rB|d}| j||  j	}nd}| 
t| |  dS qdS )NF)FTc                 S  rK  r   rL  rM  r   r   r   rN     rO  z:_detect_and_normalize_assert_statement.<locals>.<listcomp>
LOAD_CONSTzassertion errorT)operatortruthr>  r   r   rZ  instructionsr   r   argvalr.  ra   build)	r   r[  r.  current_instruction_pointerrE  assert_insts	cur_instsload_const_idx	error_msgr   r   r   &_detect_and_normalize_assert_statement  s2   
rh  Fntorch.fx.Nodec                 C  s   | j ddpt| dd}|sdS | d}d}t|D ]\}}| dr+|}q|dk r2dS ||  }d}|d t|k rJ||d   }| |rTd|  S d S )	zIExtract the innermost user source location from an FX node's stack trace.stack_tracer   r   zFile r   r   z, code: )metagetgetattrstriprA  rV  rQ  r   )ri  sttrace_lineslast_file_idxrR  line	file_linecoder   r   r   get_node_source_infoP  s    rw     valuera   	max_linesr   c                   s   t | tsdS zK| jj}g g t ddd d fdd| s/s/W dS g }tt D ]}|| |d q9dd	dd |D  W S  t
yc   tjddd Y dS w )zWalk the FX graph backwards from a TensorVariable to show how it was
    computed, with user source locations. Graph inputs (placeholders) are always
    shown first, followed by operations in dataflow order ending at the branch
    condition.r   ar<  r   r   c                 S  s   t | tjjr
| jS t| S r   )r>  torchfxNoder   repr)r{  r   r   r   fmt_args  s   z0format_tensor_computation_trace.<locals>.fmt_argri  rj  r   c                   s  | j v rd S | j  t| }| jdkr6g }|r"|d|  || j  d| j d | d S | jdkrtk rt| jdt| j}d	 fdd	| j
D }g }|rd|d|  || j  d
| d| d | | j
D ]}t|tjjr| q{d S d S d S )Nplaceholderz# z: graph input ()r   r   z, c                 3  s    | ]} |V  qd S r   r   )r   r{  )r  r   r   r         z@format_tensor_computation_trace.<locals>.walk.<locals>.<genexpr>z = r   )r   r   rw  opr   r  r   ro  r   r   r   r>  r|  r}  r~  )ri  sourceblocktarget_nameargs_strr{  r  rz  	op_blocksplaceholder_blocksvisitedwalkr   r   r  v  s2   




	z-format_tensor_computation_trace.<locals>.walkz@

  The branch condition involves a tensor computed as follows:
r   c                 s  s    | ]}d | V  qdS )    Nr   )r   rt  r   r   r   r     s    z2format_tensor_computation_trace.<locals>.<genexpr>z&format_tensor_computation_trace failedT)exc_infoN)r{  r<  r   r   )ri  rj  r   r   )r>  r   proxynoder	  r   r   extendr   r   	Exceptionr  debug)ry  rz  r  	all_linesr  r   r  r   format_tensor_computation_tracec  s0   


r  8Callable[[InstructionTranslatorBase, Instruction], None]c                   s6   ddd	ddfdd d fdd}|S )Nry  ra   r   r   c                 S  s   t | }g }t| tr9z$| jjjd}|d ur.| dkr.|jt	j
t	jt	jfv r.|d W n	 ty8   Y nw |tj |d tdd|  d| |d d S )	Nexample_valuer   zThe branch condition uses a scalar integer tensor. Consider rewriting the computation to use plain Python ints (e.g. use int attributes instead of tensor buffers) so the condition becomes a shape guard instead of data-dependent branching.z1Use `torch.cond` to express dynamic control flow.z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.gb_typecontextexplanationhints)r  r>  r   r  r  rm  rn  dimdtyper|  r   int32int64r   r  r  r   FUNDAMENTALr9   )ry  
trace_infor  exampler   r   r   raise_jump_graph_break  s<   


z,generic_jump.<locals>.raise_jump_graph_breakr   r   r   r   r+   	extra_msgr   r   c           
   
     sT  |   sJ d }z| W n ttfy$ } z|}W Y d }~nd }~ww |d us+J |  r6| | j| | j| jt||d | 	| t
d | jj| tdt| | |  gdd}|   | | j|} rs| 	| |jd uszJ | |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      TO_BOOLr   )r  )should_compile_partial_graphr:   r;   maybe_has_backedgeraise_loop_graph_breakf_codelog_graph_breakcode_optionsr   r.  r  r  r  compile_subgraphr?   r_   frame_summarypopcreate_call_resume_atnext_instructionr  rB  version_infoadd_output_instructionsr&   r   copy_positions)
r   r   ry  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jjdkrt| r|   }| rFt|	 r&| 
|S |  r2 | || d S tdd| dg tjdddd | rb| jjd	tjgt||fi R   | 
| d S t|tr|j}t|tjst|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/j0y^   t/1|  z|.| d}	W n t/j0y[   t/1|  d }	Y nw Y nw t|	t2t3fr|	4| g i }t5t5|	dd dd }
| r|	 }|
dkrt|tst/j6t7| dt8|j9 gd t|tt:f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r}zt|jtjr9|;| j}nt?|jdk}W n% t/j@yf } z|  ra | ||d| dW  Y d }~S  d }~ww |r{rt| )| | 
| d S d S t|tAjBrdrr| )| | 
| d S d S ddl$mC} |j$d ur||j$rĈ|D rr| )| | 
| d S d S | d S )Nr   z>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   z#Assertion failed on symbolic shapesr   )r  __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)Er  r    rewrite_assert_with_torch_assertrB  flagsoptimizerh  is_python_constantr   as_python_constantjumpr  r9   r   r  	is_tensorr  create_proxyr|  _assert_asyncr^   r>  r   sym_numSymBoolr}  experimentalsymbolic_shapesexpect_truer   
USER_ERRORscalar_tensorrd   rX   r  rm   r  r>   
make_guardr=   SEQUENCE_LENGTHr.  r   get_submodule
module_keyr   var_getattrr   ObservedAttributeErrorhandle_observed_exceptionr   rt   r   ro  raise_observed_exception	TypeErrortyper   r   evaluate_exprhas_unpack_var_sequencer   unpack_var_sequencer   r;   r   BackwardHookVariabler  get_real_value)r   r   ry  rg  sym_exprresultscalar_to_tensor_proxyscalar_to_tensorr;  rF  method_nameresult_valueeval_resultr  r  r  r.  r  r[  r   r   inner  sR  



















	


"




zgeneric_jump.<locals>.inner)ry  ra   r   r   )r   )
r   r   r   r+   ry  ra   r  r   r   r   r   r   r   r+   r   r   r   )r[  r.  r  r   r  r   generic_jump  s   
'9 ?r  cgr0   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_stackr>  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              
     st  | j }| _ |  }|| r|jd usJ  | ||jS zz
| |W W || _ S  ttfy } zr| jrV| js;| jr< t	|trE|
  tdd| j ddgtj|d t|ddr] |  sb |  rm| | j| | j| j dt| |d	 t	|tr|
  |d
 tt|dt|t|d|  g|_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_exc
skip_frameFz:

r  graph_breakrG  
real_stack)current_instruction_push	speculater   r   r:   r;   active_generic_context_managers	one_graphr   r>  remove_from_statsr9   r   CAUSED_BY_EARLIER_GRAPH_BREAKro  r  r  r  r  r  r  r   add_to_statsr?   r  r   )r   r   	prev_pushspeculationexcp)handle_graph_breakr  r  r.  r   r   wrapper  s`   
-



'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r     r     CALLPRECALLz%s triggered compiler  r   r   r  KW_NAMESra  Frl  ) rB  r  r   rT  stack_effectopmapargopcoder  r  r  r  r   r0   root_txr  r  rU  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   )r8  r9  )r  r  r  r.  )r  r  r   	decorator  s   9>z-break_graph_if_unsupported.<locals>.decorator)r  r  r   r  r   )r.  r  r%  r   r$  r   break_graph_if_unsupported  s   }r&  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   _missingr  s   


z4BytecodeDispatchTableMeta.__init__.<locals>._missingc              
     s&   i | ]\}}|t |t |qS r   )ro  r8  partial)r   r   r  )r,  r   r   r   r   ~  s    z6BytecodeDispatchTableMeta.__init__.<locals>.<dictcomp>c                   s   g | ]}  |qS r   )rn  r   rR  )dispatch_tabler   r   rN    s    z6BytecodeDispatchTableMeta.__init__.<locals>.<listcomp>   )r   r   r   r   r   r   )super__init__rT  r  r   ranger/  )r   r   r(  r)  	__class__)r,  r   r/  r   r2  o  s   
z"BytecodeDispatchTableMeta.__init__)
r   r  r   r   r(  r   r)  r   r   r   )r   r   r   r   r2  __classcell__r   r   r4  r   r'  l  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ExceptionVals | None_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  s\   |j  }rt|tur|S t| j| dkr,| j| }| ||d  ||ur,|| |S Nr   r   )__context__r  rg   r   r8  _set_context_recursiveset_context)r   r=  rC  ctxprevr   r   r   rF    s   

z%ExceptionStack._set_context_recursivec                 C  sb   | }}d}	 |j }t|tu rd S ||u r |td  d S |}||u r(d S |r-|j }| }qr  )rE  r  rg   rG  create)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   )rF  r   r8  rN  r?  r   r   r   r>    s   z=ExceptionStack._set_context_and_break_context_reference_cyclec                 C  
   | j  S r   )r8  r  r   r   r   r   r    r   zExceptionStack.popc                 C  r   r   )r8  r   r?  r   r   r   r     rI  zExceptionStack.appendc                 C  s
   t | jS r   )r   r8  r   r   r   r   r    r   zExceptionStack.__len__r   c                 C  s
   | j | S r   )r8  )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=)r8  r:  r   r   r   r   __str__     zExceptionStack.__str__r   )r=  r   r   r   )r   r   )r=  r   rC  r   r   r   )r   r   )r   r   r   r   r   )r   r   r   r   r   r   r   r8  r   r:  r<  r@  rA  rB  rF  rN  r>  r  r   r  rQ  rR  __repr__r   r   r   r   r7    s"   
 











r7  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< dd6d7Zdd8d9Zdd;d<Zdd=d>Zdd?d@ZddAdBZ	ddGdHZ
d dKdLZddNdOZdddRdSZddTdUZddVdWZddXdY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ddfdgZd
didjZddldmZddndoZddqdrZddsdtZddudvZddwdxZddydzZ dd}d~Z!dddZ"eZ#ddd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Z0e0Z1dddZ2e,dddZ3dddZ4dddZ5e5Z6e5Z7e8e9j:dZ;e8e9j<dZ=e8e9j:dZ>e8e9j<d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ddd΄ZQdddЄZRddd҄ZSdddԄZTdddքZUeVddd؍dddڄZWeVddd؍ddd݄ZXeVddd؍dddZYdddZZdddZ[dddZ\dddZ]dddZ^dddZ_eVddd؍dddZ`dddZadddZbecdddZddddZeddd	ZfecdddZgdddZheVddd؍dddZi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 Zpeqfd d#d$Zrdd%d&ZsesZtdd'd(Zudd)d*ZvevZwdd+d,Zxdd-d.Zydd/d0Zzdd1d2Z{dd3d4Z|dd5d6Z}dd7d8Z~dd9d:ZeVdd;d؍dd<d=Zdd>d?Zdd@dAZddBdCZddDdEZddFdGZddHdIZddJdKZd!dNdOZd"dRdSZddTdUZddVdWZddXdYZddZd[Zdd\d]Zdd^d_Zdd`daZddbdcZeZddddeZddfdgZddhdiZddjdkZddldmZddndoZddpdqZddrdsZee9jZee9jZee9j:Zee9jZee9jZee9jZee9jZee9jZee9jZee9jZee9jZee9jZee9jZeVddtd؍ee9jZee9jZee9jZee9jZee9jZee9jZee9jZee9jZee9jăZee9jƃZee9jȃZee9jʃZee9jʃZee9j̓Zee9jσZee9jуZee9jӃZee9jՃZee9j׃Zee9jكZڐddudvZejdZkrddwdxZܐddydzZݐdd{d|Zސdd}d~Zߐd#d$ddZeVddd؍dddZdddZdddZe5Ze5Ze8e9j<dZe8e9j<dZe8e9j:dZe8e9j:dZdddZdddZd%ddZec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dddZeVd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d'dĐdńZ	d(dǐdȄZ
ddɐdʄZd)d̐d̈́Zed*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ecd0ddZ	P	P	Pd1d2 fddZ  ZS (3  r   r@   r  dict[str, VariableTracker]symbolic_localssymbolic_globalsr   symbolic_torch_function_stater   symbolic_stream_statez!dict[str, VariableTracker] | Nonepost_prune_cell_and_freevarslist[VariableTracker]stack
int | Noner   r+   current_instructionr   r  zlist[BlockStackEntry]r  r   r   zConstantVariable | Noner  accept_prefix_instr  prefix_instsinline_depthinconsistent_side_effectszSpeculationEntry | Nonecurrent_speculationz	list[Any]r/  r7  exn_vt_stackzExecutionRecorder | Noneexec_recorderz(Callable[[VariableTracker], bool] | Nonestrict_checks_fnstart_pointhas_no_inlined_callsz InstructionTranslatorBase | Noner  is_child_tracer_activez3list[tuple[VariableTracker, list[VariableTracker]]]debug_localsCompilePackage | None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)rb  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   ra  r  )r   r  
cur_offsetr   jump_offsetr   r   r   r    s   

z,InstructionTranslatorBase.maybe_has_backedger   c                 C  
   | j d S )Nco_cellvarsr  r   r   r   r   cellvars9  r   z"InstructionTranslatorBase.cellvarsc                 C  rt  )Nco_freevarsrv  r   r   r   r   freevars<  r   z"InstructionTranslatorBase.freevarsc                 C  s"   t | ds|  |   | _| jS )N_cell_and_freevars)r  rw  ry  rz  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   F  s
    z?InstructionTranslatorBase.prune_dead_locals.<locals>.<dictcomp>c                   s   i | ]\}}| v r||qS r   r   r   )readsr   r   r   M  s    )rV  r   rZ  r   r`  r^  r   r   r}  r   r   prune_dead_localsD  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   )r>  ra   r   rF  r   r   r   r   Z  s
    
z:InstructionTranslatorBase.call_function.<locals>.<genexpr>ry  r*  z$Attempt to trace forbidden callable )r>  ra   r   r   all	itertoolschainvaluesr  ry  r*  callablerU   AssertionErrorr.  r   )r   r*  r   r  r  r   r   r   r   Q  s   

z'InstructionTranslatorBase.call_functionrn   Sequence[VariableTracker]c                 C  s    t |ts	t|}|| ||S )zD
        Redirect the call to the generator "call_function"
        )r>  ro   r   r   r*  r   r  r   r   r   inline_generator_functiong  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_returnt  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   r   z in )r   ra  r<   r  co_filenameco_name)r   r   inline_depth_strfuncnamefuncname_strr   r   r   get_line_of_code_header  s   $z1InstructionTranslatorBase.get_line_of_code_headerc                 C  s8   d|    d}t| jj| j }|d| 7 }|S )NzTRACE starts_line r   r  )r  	linecachegetliner  r  r   rstrip)r   log_strrt  r   r   r   get_log_starts_line_log_str  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   starts_line  s   
z%InstructionTranslatorBase.starts_linec              
   C  sX  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$t%fy" } z[| j&s| js| j'st(|d	d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 d|_. dt/| }| j0| j1||d W Y d}~nd}~ww | j
2| 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  Tr  z3cannot 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  )3rV   r   r   r`  r^  r  r\  r  is_non_empty_graphr  rc  r   step_graph_breakis_trace_bytecode_log_enabledtrace_bytecode_logr  r   ra  r  r   verbose
ValueErrorrm  r   update_block_stackr/  r  r  r  r   r   r   exception_handlerr(  r)  r:   r;   r8   r  is_tracing_resume_prologuero  r>  r9   r   
DYNAMO_BUGr  r  r   r  r  r   )r   ipr   
stack_reprr  r   r   r   r   step  s   




	


9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   rl  )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   r0  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  s*  | j jrJ | jd usJ | jrJ td | j j| td|  gd}| j	rCd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|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 qk| j tdt%|g| j& d S )Nzstep triggered compilestep_unsupported)r   r   )	skip_coder  r   
BUILD_LISTr  TFDELETE_SUBSCRr  LIST_APPENDSTORE_SUBSCRUNPACK_SEQUENCEPOP_TOPrl  )'r  output_instructionsrc  r\  r  r  r  r?   r  r  
eval_framer  r   nested_graph_breaksr0   r  r  r$   create_load_constcreate_binary_subscrr&   create_resumer  codegen_call_resume	num_stackr!   r)   r.  r   r  rU  r  r  locals_namesr   r%   create_storer'   r`  )r   r  r  r  r  leaf_resume_codeleaf_resume_namer  r  localidxr   r   r   r  E  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	yG } z| j
rBtdt|j dt| |jd  d }~ww W n tyQ     tyX     ty } zNt|ttfrt| tr| js| jsdt| }| j| j||d t|tjs| jj  t |drd|j!v rt"j#$| jj%| jj&j'dddd	}||_(  d }~w t	y } z| j)r| j)* |_+t|tjs| j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 sw   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  rG  zData-dependentFT)print_outputinclude_strideinclude_device)/r  r   r  r  r  push_txr   rg  r  r  r  r7   r  r   r   with_traceback__traceback__r   r3   RuntimeErrorr>  r:   r;   r-  r   r  r  r  r   RestartAnalysisside_effectslog_side_effects_summaryr  rG  r|  r}  GraphModule
nn_modulesgraphprint_readablepartial_fx_graphre  
get_recordexec_recordpop_txr  mark_bytecode_tracing_stop)r   r  r   readable_graphr   r   r   run  s   







$zInstructionTranslatorBase.runr=  c                 C  s,   t |tsJ dt| | j| d S )Nz"push expects VariableTracker, got )r>  ra   r_   r\  r   r?  r   r   r   r.  ]  s   zInstructionTranslatorBase.pushvalsc                 C  s   |D ]}|  | qd S r   r#  )r   r  r=  r   r   r   	push_manyc  s   z#InstructionTranslatorBase.push_manyc                 C  rP  r   )r\  r  r   r   r   r   r  g  r   zInstructionTranslatorBase.popri  c                   s   g t  fddt|D S )Nc                   s   g | ]}   qS r   r  )r   r   r   r   r   rN  k      z2InstructionTranslatorBase.popn.<locals>.<listcomp>)r   r3  )r   ri  r   r   r   r/  j  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 )Nr=  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)ra  re  f_localsadd_local_varr.  rV  unwrapKeyErrorrQ  replacer9   r   r  r  )r   r   r   new_namer   r   r   	LOAD_FASTm  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   )
ra  r{  rV  r  r  	load_cellr.  re  r  r  )r   r   cellcontents_varr   r   r   
LOAD_DEREF  s   
z$InstructionTranslatorBase.LOAD_DEREFc                 C  sP   |j }|  }|| || j|< |tkr&| }t|tu s!J || _d S d S r   )	ra  r  set_name_hintrV  rJ   r  r  r   r  )r   r   r   	loaded_vtr=  r   r   r   
STORE_FAST  s   


z$InstructionTranslatorBase.STORE_FASTc                 C  s0   | j |j}t|tr| | | j |j= d S r   )rV  rn  ra  r>  r   _maybe_emit_sync_dealloc)r   r   varr   r   r   DELETE_FAST  s   

z%InstructionTranslatorBase.DELETE_FASTr  r   c                 C  s   ddl m}m} |j}|d u s|jdvrd S |jj}|jdi dd }t	|j
 }|s0d S d }| jjjD ]}	|	|v r?|	}q7|d u sI|jdkrKd S |jdi dd }
||
kr\d S |d u rd||}|
d u rl||}
| }| jdtjjj||
fi  | jdtjjj||| fi  d S )Nr   )get_current_stream	new_event)cudaxpucustomstreamr  r   )variables.streamsr  r  devicer  r  r  rm  rn  r	  userskeysr  r  nodesr  r  r|  opsstreamsrecord_eventsync_deallocas_proxy)r   r  r  r  r  r  alloc_streamr  	last_userri  last_use_stream	event_idxr   r   r   r    sH   z2InstructionTranslatorBase._maybe_emit_sync_deallocc                 C  sb   |j |  v s	J | j|j  }|  }| jj|| t|ts"J |j	d ur/|
|j	 d S d S r   )ra  r{  rV  r  r  r  
store_cellr>  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 )Nry  )r  rg   rJ  ra  _constants_cache)r   r   rR  r=  r   r   r   _load_const  s   

z%InstructionTranslatorBase._load_constc                 C  s   |  | | d S r   )r.  r  r0  r   r   r   r]    rS  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   )ra  re  	f_globalsadd_global_var
f_builtinsbuiltinsload_builtinrW  r  r  r.  load_globalra   rb  rN   )r   r   r   variablery  r   r   r   _load_global  s   




z&InstructionTranslatorBase._load_globalc                 C  s$   d}|  |}t|}t| ||S )Nztorch.nn.modules.module)import_sourcer   ra   rb  )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  rB  r  	PUSH_NULLr  r0  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  ra  rN   rW  r<  r  r  track_global_existingr>  r   r9   store_global)r   r   ry  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   <r=  _dot_	__import_N)r|  rl  package_importer_package_imported_modulesr  r   add_import_sourcer  import_sourcesglobal_scopeupdate_co_namesrN   )r   r  ry  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
        r=  r   z2attempted relative import beyond top-level packager   )rsplitr   ImportError)r   r   rl  r5  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)r  )
stacklevelzYcan't resolve package from __spec__ or __package__, falling back on __name__ and __path__r   __path__r=  r   )r  rn  r  r  warning
rpartition)r   rl  specr   r   r   calc_packageI  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   )fromlistr5  globalszImport failurezmodule_name: z, fromlist: z, level=z"Failure when attempting to import.r  r   r=  r  zBad import resultz%Import result is not a Python module.)r/  r  ra  rH   LOCAL_MOD_PREFIXr  rN   
__import__r7  r9   r   r  rB  r:  	partitionr  re  add_local_modr>  r?  r@  rG   r.  r   r_   )
r   r   r5  rC  r  recorded_namery  r  pkgtop_level_module_namer   r   r   IMPORT_NAMEf  sR   






z%InstructionTranslatorBase.IMPORT_NAMEc                 C  s   |  | | |j d S r   )DUP_TOP
_load_attrra  r0  r   r   r   IMPORT_FROM     
z%InstructionTranslatorBase.IMPORT_FROMra  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	
| |S )Nz%failed to find name in frame builtinsr   zFailed to find name `z` in frame's builtins.r  )r  r9   r   r  r  rN   r  %name_of_builtins_dict_key_in_fglobalsrM   ra   rb  rT   )r   ra  r=  builtins_source
var_sourcer   r   r   load_builtin_from_argval  s$   



z2InstructionTranslatorBase.load_builtin_from_argvalc                 C  s   |  | |j d S r   )r.  rU  ra  r0  r   r   r   r    s   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   rg  r  rZ   	incrementindexofr0  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\  r0  r   r   r   
SETUP_LOOP      z$InstructionTranslatorBase.SETUP_LOOPc                 C  rZ  r   r[  r0  r   r   r   SETUP_EXCEPT  r]  z&InstructionTranslatorBase.SETUP_EXCEPTc                 C  r  r   )r  r  r0  r   r   r   	POP_BLOCK     z#InstructionTranslatorBase.POP_BLOCKc                 C     |  | d S r   setup_or_before_withr0  r   r   r   
SETUP_WITH  r`  z$InstructionTranslatorBase.SETUP_WITHc                 C  rZ  r   r[  r0  r   r   r   SETUP_FINALLY  s    z'InstructionTranslatorBase.SETUP_FINALLYc              
   C  s   |    }| | z|| }| | W d S  ttjfyP } z)t|tjr.t|  t	j
dkr<| td  n|    | | W Y d }~d S d }~ww Nr  )r  realizer.  next_variableStopIterationr   ObservedUserStopIterationr>  r  rB  r  rg   rJ  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   )r>  r   re   r   r   r?  r   r   r   _create_exception_type	  s
   
z0InstructionTranslatorBase._create_exception_typer   r   c                 C  sR   |   }|| d}t|ttfsJ t||}|| dt| d|gi  d S )Nr  __setattr__)	r  r  r>  rg   r   from_frame_summarycall_methodra   rb  )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 }| |r4t|dd d u r4tjj |_| |rV| j| t|j}t|dd }|d|  |dtjt| d|  gd d S )Npython_stackraised exception )r  z/exceptions must derive from BaseException, not r  )rm  r,   r  r>  r   r~   exc_typeri  ra   rb  r  r   _isinstance_exceptionro  r|  _guardsr   extract_stackrt  rd  r@  r   get_dynamo_observed_exception
debug_reprr  r  python_type_name)r   r=  observed_exception_typert  r   r   r   _raise_exception_variable	  s0   




z3InstructionTranslatorBase._raise_exception_variablec                 C  sF  |j dkr/t| jstjt| dgd t| jsJ | jd }| |s(J || | d S |j dkrW| jd }z| | W | j	 }| 
| d S | j	 }| 
| w |  }|  }z%| | W | j	 }| 
| | |}|| dt| d|gi  d S | j	 }| 
| | |}|| dt| d|gi  w )Nr   zNo active exception to reraiser  rl  r   rn  	__cause__)r  r   rd  r   r  r  rw  r~  r\  rB  rs  r  rm  rp  ra   rb  )r   r   r=  curr_excfrom_vtcauser   r   r   rS  N	  sN   












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 )Nrl  z CLEANUP_THROW with StopIterationr   zRReceived StopIteration when handling generator.throw/close. This is not supported.r  )r\  r>  r~   rv  ri  r9   RERAISEr   r   tosr   r   r   CLEANUP_THROWv	  s   


z'InstructionTranslatorBase.CLEANUP_THROWc                 C  sl   t jdkr#|  }|jr|  }| | d S | | | | d S |  }|  }|  }| | d S )Nr  )rB  r  r  ra  r~  r.  )r   r   r=  r   _exc_tbr   r   r   r  	  s   

z!InstructionTranslatorBase.RERAISETypeIs[ExceptionVals]c                 C  s
   t |tS r   )r>  r   r?  r   r   r   rw  	  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  r           rl  r     ir  )rB  r  r   r\  rw  re   rv  r  r>  r   r   r   )r   r   r   fn_locr*  r=  typrq  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rajj}|rGtj|jkr*  tj|jks|jr8	t
jj 	j  | d S j  j }| ttu r_|  tjr6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sr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&'d  	t&'d  	t&'d  	t"#  	| 	t"$|j% | d S j  ttu rE|  )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                    sR   j  } t|  }t|sJ tdd|    g tj	tj
d d S )NzObserved exceptionru  r   )rd  rB  r   rz  python_typer>  r9   r{  r   r  r+  )r  
dynamo_excobserved_exn_gb_explanationr  r   r   r   bubble_exception_to_interpreter	  s   

zTInstructionTranslatorBase.exception_handler.<locals>.bubble_exception_to_interpreterr  EXCEPT_HANDLERr  r   z#Observed exception (EXCEPT_HANDLER)z  This graph break is unexpected.r   g    .Ar  r  r   )(rB  r  r^  r   r   r\  depthr  lastir.  ra   rb  rq  rd  rB  r  r   rs  r  r-  r  r   r   r/  r9   r   r   r  rA  r  r+   r   r   r  r   r   re   rv  rg   rJ  )	r   r  r  r   r  block_stack_entryexception_varexcept_handler_instold_exceptionr   r  r   r  	  s   







	






z+InstructionTranslatorBase.exception_handlerc                 C  sN   |   }t| jdkrtd }n| jd }| | | | | j  d S )Nr   rl  )r  r   rd  rg   rJ  r.  rA  )r   r   r=  prev_excr   r   r   PUSH_EXC_INFOG
  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   rl  r  zYBug in Dynamo tracing of exception handling.Top of the block stack is not EXCEPT_HANDLER.r  )
rB  r  r  r   rd  r  r   r   r  r/  )r   r   r   r   r   r   
POP_EXCEPTd
  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  rl  z Exception with bad expected typez"`except ...` has unsupported type r=  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  rB  r  r>  re   r|   r   r   r9   r   r   r  rw  r   
issubclassrv  r*  r   )r   expected_exc_typesexc_instanceexpected_typesexpected_typer   r   r   check_if_exc_matchesy
  sr   

	





z.InstructionTranslatorBase.check_if_exc_matchesc                 C  s   |  t| |   d S r   )r.  ra   rb  r  r0  r   r   r   CHECK_EXC_MATCH
  s   z)InstructionTranslatorBase.CHECK_EXC_MATCHc                 C  s   |   s| | d S d S r   )r  r  r0  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  )ra  r  r.  r   r/  r0  r   r   r   
COMPARE_OP
  s   
"z$InstructionTranslatorBase.COMPARE_OPc                 C  s    |  t| t|  gi  d S r   )r   ra   rb  iterr  r0  r   r   r   GET_ITER
  s    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/  ra  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   r  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)ra  rm   r  rB  r  r>  r   r9   r   r  rw   has_force_unpack_var_sequencer|   force_unpack_var_sequencer   rf   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/  ra  r>  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  ra  r  rB  r  rO  LOAD_METHODr   r   r  ra  r   r   r   LOAD_METHOD_SUPER5  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  ra  r  rO  r  r   r   r   LOAD_ATTR_SUPER>  s   
z)InstructionTranslatorBase.LOAD_ATTR_SUPERc                 C  s`   |  |j |  }tjdkr| | | | d S tjdkr,| | | | d S td)Nr  r  zPLOAD_METHOD should have been rewritten to LOAD_ATTR. We should never reach here.)rO  ra  r  rB  r  r.  r#  r  r   r   objr   r   r   r  D  s   



z%InstructionTranslatorBase.LOAD_METHODc                 C  s   t d)Nz^CALL_METHOD should have been rewritten to CALL_FUNCTION. This function should never be called.)r  r0  r   r   r   CALL_METHODU  s   z%InstructionTranslatorBase.CALL_METHODattrc                 C  s8   |   }t| t| |t| |gi }| | d S r   )r  ra   rb  ro  r   r.  )r   r  r  r  r   r   r   rO  Z  s   z$InstructionTranslatorBase._load_attrc                 C  s2   t jdkr|jd r| | d S | |j d S )Nr  r  )rB  r  r  r  rO  ra  r0  r   r   r   	LOAD_ATTRc  s
   


z#InstructionTranslatorBase.LOAD_ATTRzkEncountered graph break when attempting to trace STORE_ATTR: storing an object's attribute, e.g. x.attr = yc                 C  s8   |  d\}}t| t| |t| |j|gi  d S )Nr  )r/  ra   rb  setattrr   ra  )r   r   r=  r  r   r   r   
STORE_ATTRk  s   z$InstructionTranslatorBase.STORE_ATTRc                 C  s>   |   }| ||j t| t| |t| |jgi  d S r   )r  _maybe_sync_dealloc_attrra  ra   rb  delattrr   r  r   r   r   DELETE_ATTRw  s   z%InstructionTranslatorBase.DELETE_ATTRr  c                 C  s@   | j j||r| j j||}t|tr| | d S d S d S r   )r  r  has_pending_mutation_of_attr	load_attrr>  r   r  )r   r  r   attr_varr   r   r   r    s   
z2InstructionTranslatorBase._maybe_sync_dealloc_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   r  ro  rp  r  r  )r  r)   r   r&   ra  )r   r  rW  return_instr   r   r   codegen_return_with_pops  s   
z2InstructionTranslatorBase.codegen_return_with_popsr  resume_instrm  rA   resume_codeslist[types.CodeType]r  r0   is_leafhandle_inactive_ctxtuple[types.CodeType, str]c                   sb  |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-.||j/ j0durj01|j/d | t2d |j3  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  r  r  NTr  r   z&variables should not be NULL in < 3.12c                 s  s    | ]}|j jV  qd S r   )r  rq  r   r  r   r   r   r   ?  r  c                 s      | ]}|  V  qd S r   )r   r  r   r   r   r   C  r  orig_graphmodulec                   S  r  r   r   r   r   r   r   r   O      z9InstructionTranslatorBase.create_resume.<locals>.<lambda>r   resumesr   )4r  stack_ctx_argsstack_ctx_idxes_origr   rh   r\  append_outputr%   r  r  r)   r  r  r&   locals_ctx_argsrV  r  r  r-   r  r.   rq  r   r`  r  r	  locals_null_keysr   r!   r  rB  r  stack_null_idxesr^  rI   lookupr  r   r  r  r/   get_contextrn  weakrefrefr  install_resume_function_globalr  rl  add_resume_functionrW   r  )r   r  r  rm  r  r  r  r  jr   j_origrH  r   resume_nameall_argnamesr  argnames_nullr  	stack_lennew_codeorig_graphmodule_mayber   )r  r}  r   r   r    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   ro  r   r  r  r  r  T)r   r0   r  r  r  r   r   r  r   r\  r  r  r)   r3  r  r&   rU  r  r.  r   r$   r  r  r!   r  r%   r  deepcopyrV  r  r  )r   r   r  r  txesidxesresume_instsr  r  r  current_num_stackr   stack_insert_idxfilter_instsr  resume_namesrR  resume_coder  r   r   r   r  c  s   





	
	

	z/InstructionTranslatorBase.create_call_resume_atr  c                 C  s  | td tt|| D ]H\}\}}|t|d kr n9|jrE| t ||| g | |j	|ddgt
dtddd n
| ||dd | t
d q| tdtd	t| d d
g | t
d | d jr| |d| g | |j	|d ddgt
dtd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   T)r   )	push_nullFr   r  r  r  r  rl  r  LIST_EXTENDN)r  r$   rV  r  r   rx  r%   r  r  create_load_globalr)   r"   load_function_namer&   r(   r#   )r  r  r  rR  r   rv  r   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  rl  Fc                 s  r  r   )r  r  r   r   r   r     r  zIInstructionTranslatorBase.should_compile_partial_graph.<locals>.<genexpr>)rB  r  r^  r   r  r  r  r  ri  r   r  r  r  current_tracerr  )r   r   r   r   r   r    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 )Nr  __setitem__)r/  rp  )r   r   r=  r  keyr   r   r   r    s   z&InstructionTranslatorBase.STORE_SUBSCRc                 C  s0   |  d\}}| || || d|gi  d S )Nr  __delitem__)r/  _maybe_sync_dealloc_subscrrp  )r   r   r  r  r   r   r   r    s   z'InstructionTranslatorBase.DELETE_SUBSCRr  c                 C  s|   ddl m} ddlm} d }zt||r|| |}n
t||r%||}W n	 ty/   Y nw t|tr<| 	| d S d S )Nr   rl   )rw   )
variables.dictsrm   variables.listsrw   r>  getitem_constmaybe_getitem_constr  r   r  )r   r  r  rm   rw   item_varr   r   r   r    s$   



z4InstructionTranslatorBase._maybe_sync_dealloc_subscrc                 C  s   |  |j}| t| d S r   )r/  ra  r.  r|   r   r   r   r   r   r   BUILD_TUPLE  s   z%InstructionTranslatorBase.BUILD_TUPLEc                 C  s"   |  |j}| t|| d d S )N)r   )r/  ra  r.  r{   r  r   r   r   BUILD_SLICE  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_nested  s   z=InstructionTranslatorBase._can_speculate_comprehension_nestedc                 C  s0   t | |rd S | |j}| t| | d S r   )r1   r/  ra  r.  ra   rb  r  r   r   r   r    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  mutation_type)r   +inject_BUILD_SET_unimplemented_TESTING_ONLYr9   r/  ra  r   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/  ra  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|   r0  r   r   r   BUILD_TUPLE_UNPACK  s   z,InstructionTranslatorBase.BUILD_TUPLE_UNPACKc                 C  sV   t | |rd S | |jd }tt|d d d |dd d }| t| | d S )Nr  r   )r1   r/  ra  r   r  r.  ra   rb  )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 | d S )Nc                   s$   g | ]}t  t |gi qS r   )ra   rb  r   r   r  r   r   r   rN  	  s    z>InstructionTranslatorBase.BUILD_MAP_UNPACK.<locals>.<listcomp>)	r/  ra  r>  rm   updater   r.  ra   rb  )r   r   r   r  rF  r   r   r   BUILD_MAP_UNPACK  s   
z*InstructionTranslatorBase.BUILD_MAP_UNPACKc              	   C  sl   |   }| |j}t|tsJ | sJ || }t|t|ks&J | t	
| tt|| d S r   )r  r/  ra  r>  r|   r  r  r   r.  ra   rb  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/  ra  r  r\  rg  r>  rm   rp  )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  ra  r  r\  r>  r   
is_mutablerp  r   r   r   r  r   r   r   SET_ADD2     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  ra  r  r\  rg  r>  rz   r"  r  r  mutationr   r   r#  r   r   r   r  D  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}d }d }d }d }tjdk rV|d urV|d@ r>|  }|d@ rF|  }|d@ rN|  }|d@ rV|  }t	||| j
|||}	|rt|tsiJ |j}
ttt|
d d d |
dd d dd	t d
}|	| d| | |	 d S )Nr  co_qualnamer     r  r  r   Tstrictr  r   )r  rB  r  r  r  ry  ra   rb  r)  rq   r  r>  r|   r   rm   r   r  r`   get_dict_vtsetitemr.  )r   r   r  fn_namerv  defaultsclosurer   
kwdefaultsr*  r   annr   r   r   MAKE_FUNCTIONN  sP   


$
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.  r  r   r   r   rN    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  r3  ra  r>  r   r  ro  r  r   r  r  r9   r   r   r  r   r  r   r.  )r   r   r  r=  rR  r   r5  r   r    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  )ra  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_EX  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  )rh  r9   r0  r   r   r   graph_break_on_leaf_function  s   
z6InstructionTranslatorBase.graph_break_on_leaf_functionc                 C  s   |j dkr| | d S d S )NGRAPH_BREAK_IF_LEAF)ra  r>  r0  r   r   r   r    s   
zInstructionTranslatorBase.NOPc                 C     |    d S r   r  r0  r   r   r   r    rJ  z!InstructionTranslatorBase.POP_TOPc                 C  s(   |   }|   }| | | | d S r   r  r.  r   r   r{  r  r   r   r   ROT_TWO  s   
z!InstructionTranslatorBase.ROT_TWOc                 C  s:   |   }|   }|   }| | | | | | d S r   rA  )r   r   r{  r  cr   r   r   	ROT_THREE  s   

z#InstructionTranslatorBase.ROT_THREEc                 C  sL   |   }|   }|   }|   }| | | | | | | | d S r   rA  )r   r   r{  r  rD  r  r   r   r   ROT_FOUR  s   


z"InstructionTranslatorBase.ROT_FOURc                 C  s    |   }| | | | d S r   rA  )r   r   r{  r   r   r   rN    s   
z!InstructionTranslatorBase.DUP_TOPc                 C  s<   |   }|   }| | | | | | | | d S r   rA  rB  r   r   r   DUP_TOP_TWO  s   


z%InstructionTranslatorBase.DUP_TOP_TWOry  flagc                 C  sd   |dkrt | t| |gi S |dkr t | t| |gi S |dkr0t | t| |gi S |S )Nr   r  r  )ra   rb  r   r   r  ascii)r   ry  rH  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   rE  r  z{:})r  r>  r   torch._dynamo.variables.lazyrL  rv   rJ  r  r.  rJ  ra   rb  r  r   re   r   format)r   rK  r  ry  rL  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  ra   rb  rQ  )r   r   r  rK  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   r>  r   StringFormatVariableformat_stringr  sym_argsr	  r  
sym_kwargsr9   r   r  r  r   r.  rJ  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  )ra  r&   r  )r   r   
new_argvalnew_instr   r   r   IS_OP9  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__)ra  r/  r.  rp  r   ObservedTypeErrorr:   r>  r  r	  r  ra   rb  rB   	UNARY_NOT)r   r   leftrightr  r  r   r   r   CONTAINS_OPB  s2   

z%InstructionTranslatorBase.CONTAINS_OPc                 C  r   )Nr   r  )r  ra  r  r\  r>  rz   r"  rp  r#  r   r   r   r  _  r%  z%InstructionTranslatorBase.LIST_EXTENDc                 C  s&   |  t| t| |  gi  d S r   )r.  ra   rb  r  r   r  r0  r   r   r   LIST_TO_TUPLEh  s   z'InstructionTranslatorBase.LIST_TO_TUPLEc                 C  s   | j d }| |sJ |jtu r>t| t| t| dgi }|| t| d| || t| d| || j d< d S d S )Nrl  zgenerator raised StopIterationrE  r  )	r\  rw  rv  ri  ra   rb  r  r   call_setattr)r   r   r=  new_valr   r   r   STOPITERATION_ERRORm  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  ra  r  r\  rg  r>  rm   r"  rp  r#  r   r   r   
DICT_MERGE  s   z$InstructionTranslatorBase.DICT_MERGEc                 C  r@  r   r  r0  r   r   r   	GEN_START  rJ  z#InstructionTranslatorBase.GEN_STARTc                 C  sJ   | j d }| r| t| t|  d S | || dg i  d S )Nrl  r  )r\  r  r.  ra   rb  r   r  rp  r  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
        rl  N)r\  r.  r  ra   rb  rC   r  r   r   r   MATCH_MAPPING  s   

z'InstructionTranslatorBase.MATCH_MAPPINGc                 C  s,   | j d }| | t| t|gi  d S Nrl  )r\  r.  r  ra   rb  rF   r  r   r   r   MATCH_SEQUENCE  s   

z(InstructionTranslatorBase.MATCH_SEQUENCEc              	   C  sx   |  d\}}}t| |j}| | t| t||||gi  tjdk r:| j	d }| t| t
|t  d S d S )Nr  r  rl  )r/  ra   rb  r  r.  r  rD   rB  r  r\  r\   rg   )r   r   subjectr   namesr  r  r   r   r   MATCH_CLASS  s   



z%InstructionTranslatorBase.MATCH_CLASSc                 C  sx   | j d }| j d }t|tsJ | | t| t||gi  tj	dk r:| j d }| t| t
|t  d S d S )Nrl  r  r  )r\  r>  r|   r.  r  ra   rb  rE   rB  r  r\   rg   )r   r   r  r  r  r   r   r   
MATCH_KEYS  s   



z$InstructionTranslatorBase.MATCH_KEYSc                 C     |  | d d S )Nr  r.  rU  r0  r   r   r   LOAD_ASSERTION_ERROR  rS  z.InstructionTranslatorBase.LOAD_ASSERTION_ERRORc                 C  rr  )N__build_class__rs  r0  r   r   r   LOAD_BUILD_CLASS  rS  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_instr_  r0  r   r   r   RESUME  s   


z InstructionTranslatorBase.RESUMEc                 C  s   |j d usJ t|j  | |S r   )r  _binary_op_lookupr0  r   r   r   	BINARY_OP  s   z#InstructionTranslatorBase.BINARY_OPc                 C  r  r   r   r0  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  r>  r  r   r  rg   rJ  )r   r   r  r   r   r   r   r    s   z"InstructionTranslatorBase.KW_NAMESc                 C  s   |  t  d S r   )r.  r   r0  r   r   r   r#    rI  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   )rB  r  r  r>  r|   r  r  r  ry  r  r/  r   r   r   r  r   )	r   r   r|  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  ra  r   r~  r0  r   r   r   r  F  s   zInstructionTranslatorBase.CALLc                 C  s&   |j d usJ | | j|j    d S r   )r  r.  r\  r0  r   r   r   COPYM  s   zInstructionTranslatorBase.COPYc                 C  s<   |j d usJ | j|j   | jd | jd< | j|j  < d S rl  )r  r\  r0  r   r   r   SWAPQ  s   .zInstructionTranslatorBase.SWAPc                 C  r  r   r   r0  r   r   r   CACHE]  r  zInstructionTranslatorBase.CACHEc                 C  ra  r   rb  r0  r   r   r   BEFORE_WITH`  r`  z%InstructionTranslatorBase.BEFORE_WITHrH  8ContextWrappingVariable | GenericContextWrappingVariablec                 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  rl  )r>  ri   supports_graph_breaksr  r   rB  r  r   r  r  r  r-  r   r  r  r   r\  enter)r   rH  r   r  r   r   r   	enter_ctxc  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|  )rH  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  r>  rh   ri   r  r.  rk   r  r  )r   r   rH  r   r   r   rc    s   
z.InstructionTranslatorBase.setup_or_before_withc                 C  s   | j sJ | j| d S r   )r_  r`  r   r0  r   r   r   rw    rQ  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 rf  )rB  r  r_  r>  rV  ra  r   r  r  track_cell_newrw  r0  r   r   r   	MAKE_CELL  s
   
z#InstructionTranslatorBase.MAKE_CELLc                 C  ra  r   rw  r0  r   r   r   COPY_FREE_VARS  r`  z(InstructionTranslatorBase.COPY_FREE_VARSc                 C  ra  r   r  r0  r   r   r   RETURN_GENERATOR  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  r  r   )rB  r  r  r/  rY  _comprehension_end_for_ipsdiscard_comprehension_depth)r   r   
current_ipr   r   r   END_FOR  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\   rV  rn  ra  r   r9   r   r  r  r0  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   )ra  rV  r.  r   r  r0  r   r   r   LOAD_FAST_AND_CLEAR  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  rO  ra  r0  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 |j dkrD|   }t	t
|}| | d S tdd|j  d|j  dg tjd	 d S )
Nr  r     r  z Missing CALL_INTRINSIC_1 handlerzCALL_INTRINSIC_1 operand: z,No handler implemented for CALL_INTRINSIC_1  instruction.r  )ra  rg  UNARY_POSITIVEr.  r|   r  r  r  r   TypingVariabler	   r9   r   r+  )r   r   r   tvr   r   r   CALL_INTRINSIC_1  s    





z*InstructionTranslatorBase.CALL_INTRINSIC_1c                 C  s|   |   }|   }|jdkr(t|tsJ || dtd|gi  | | d S tdd|j d|j dg t	j
d d S )	Nr  rn  __type_params__z Missing CALL_INTRINSIC_2 handlerzCALL_INTRINSIC_2 operand: z,No handler implemented for CALL_INTRINSIC_2 r  r  )r  ra  r>  rn   rp  rg   rJ  r.  r9   r   r+  )r   r   arg2arg1r   r   r   CALL_INTRINSIC_2  s"   


z*InstructionTranslatorBase.CALL_INTRINSIC_2c                 C  s   |   }|    | | d S r   rA  r  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)r|  r  r0  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_FALSEr`  )r  r   r0  r   r   r   r  $  s   z!InstructionTranslatorBase.TO_BOOLc                 C  s  |j }|d us	J |  }t|tsJ |  }|d@ r=tjdks#J || t| dgi }|	| dt
d|gi  nG|d@ rE||_n?|d@ rut|tsPJ |j}ttt|d d d |dd d d	d
t d}|| d| n|d@ r}||_n|d@ r||_| | d S )N   r  r   rn  r   r*  r  r  Tr+  r  )r  r  r>  rq   rB  r  r   ra   rb  rp  rg   rJ  r1  r|   r   rm   r   r  r`   r-  r.  r2  r0  r.  )r   r   r  r*  r  r   r3  r   r   r   SET_FUNCTION_ATTRIBUTE.  s>   $
z0InstructionTranslatorBase.SET_FUNCTION_ATTRIBUTEc                 C  s*   |j d usJ | | |  |j  d S r   )r  r.  rJ  r  r0  r   r   r   CONVERT_VALUEV  s   z'InstructionTranslatorBase.CONVERT_VALUEc                 C  s   |  t| dd d S )Nr   r   )rQ  ra   rb  r0  r   r   r   FORMAT_SIMPLEZ     z'InstructionTranslatorBase.FORMAT_SIMPLEc                 C  s   |  |  d d S r   )rQ  r  r0  r   r   r   FORMAT_WITH_SPEC]  rS  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  )r>  r  r   _load_special_namesr  rh   ri   r  r.  rj   r#  rk   rO  )r   r   r  rH  r  r   r   r   LOAD_SPECIALo  s(   


z&InstructionTranslatorBase.LOAD_SPECIALc                 C  s   |  t| |j d S r   )r.  ra   rb  ra  r0  r   r   r   LOAD_SMALL_INT  r  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)r>  r  r   r.  rU  _common_constantsr0  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     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list[Any] | Nonec                 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_summary  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  FrameSummaryro  r  r   r   r   r   r   r    s   z'InstructionTranslatorBase.frame_summaryc                 C  s&   t | jdd}td}||d uS )Nr  r  z.*torch/nn/modules.*)ro  r  recompilematch)r   r   nn_modules_patternr   r   r   is_co_filename_from_nn_modules  s   
z8InstructionTranslatorBase.is_co_filename_from_nn_modulesr7  c                 C  s,   | j |t|}tt|tj |S r   )	r  install_global_by_idr  r  r>   rO   r  r=   WEAKREF_ALIVE)r   r7  ry  global_namer   r   r   store_global_weakref_by_id  s
   z4InstructionTranslatorBase.store_global_weakref_by_idFakeTensorMode | Nonec                 C  s
   | j jjS r   )r  tracing_context	fake_moder   r   r   r   r    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)rf  )r   r  priorr   r   r   strict_translation_mode  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 rD  )r   r  r   r  r  r   r`  r   r   r   r   r    s   z#InstructionTranslatorBase.speculater   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   co_firstlinenor   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 | UserError | 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  rl  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   C  s   z;InstructionTranslatorBase.log_graph_break.<locals>.<lambda>c                     s     dt   S )Nr   )r  
format_excr   user_stack_tracer   r   r   G  rO  )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)(loggedro  r|  rx  r   ry  r   r  r  r  r  r  r   r  r   
IndexErrorr  r  r6   r   r  r  r4   r2   r   _loggingtrace_structuredr>  r:   r  r  graph_break_logisEnabledForr   DEBUGexplainr[   r   rm  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_breakrv  types.CodeTypeUnsupported | UserErrorc                 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
  )rv  r   r   r   r   r  k  s   
z0InstructionTranslatorBase.raise_loop_graph_breakr`  r  r  r  r  exportr  r   distributed_stateDistributedState | Noner1  tuple[types.CellType] | NonerY  dict[Instruction, int] | Nonec                   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  Trl  rx  )maxlen)rv  r1  r  Fr   )CO_ASYNC_GENERATORCO_COROUTINECO_GENERATORCO_ITERABLE_COROUTINE)Mr1  r2  r  r  r  rV  rW  rX  rY  rZ  r\  r   rg  r&   r^  r  r  r  r   r  r_  r`  rd  r   rm  r  r	  r  r`  r   rY  r  r  r  r  r  r1  r   replay_record_enabledrH   re  nn_module_stack	num_callsr  r  r   r  rc  rf  rh  r  ri  rj  rl  resume_executionr  r  r  r  co_flagsr.  re   ra  rb  r   r{  r  r  r  r   r  r  r  r  r  	lazycacher  )r   r  r`  r  r  r  r  rV  rW  rX  rY  r  r  ra  r  rd  r  r1  rl  rY  r  r  r  r  r4  r   r   r2  y  s   



z"InstructionTranslatorBase.__init__r   r  )r   r   )r*  ra   r   r[  r  rU  r   r   )r*  rn   r   r  r  rU  r   ra   )r*  rn   r   r  r  rU  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   )ri  r   r   r[  )r  r   r   r   )r   r+   r   ra   )r  r   r   rN   )r   r   rl  r   r5  r   r   r   )ra  r   r   ra   )r   rV  r   r   )r=  ra   r   ra   )r   r   r   r   )r=  ra   r   r   )r=  ra   r   r  )r  r   r   r   )r  r   r   r   )r  ra   r   r   r   r   )r   r+   r  r   r   r  )r  r   r  r+   rm  rA   r  r  r  r0   r  r   r  r   r   r  r   r+   r  r  r   r  )r  r  r  r   r  r0   r   r   )r  ra   r  ra   r   r   )r   r+   r   r  r   r   )ry  ra   rH  r   r   ra   )rK  ra   r  r   r   r   )F)r   r+   r|  r   r   r   )rH  r  r   r+   r   ra   )rH  ra   r   r   )r  r  r   r   )r   r  )r7  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  )r  r   r   r   r   r  r   r   )rv  r  r   r  r   r   )NNN)(r  r@   r`  r  r  r   r  r   r  r   r  r   rV  rU  rW  rU  rX  r   rY  r   r  r  r  r   ra  r   r  r   rd  r7  r  r  r1  r  rl  rk  rY  r  r   r   (  r   r   r   r   rn  r  rw  ry  r{  r  r   r  r  r  r  r  r  rB  r  r  propertyr  r  r  r  r.  r  r  r/  r  r  r  r  r  r  LOAD_CLOSUREr  r]  r  r8  cached_propertyr"  r$  r(  r   r  r:  rB  rM  EAGER_IMPORT_NAMErP  rU  r  r  JUMP_FORWARDJUMP_ABSOLUTEr  r^  not_r  r_  r  JUMP_IF_FALSE_OR_POPJUMP_IF_TRUE_OR_POPr\  r^  r_  rd  re  rl  rm  rs  r~  rS  r  r  rw  r  r  r  r  r  r  r  r  r  r&  r  r  r  r  r  r  r  rO  r  r  r  r  staticmethodr  r  r  r  r  r  r  r  r  r  r  r  r  rz   r  r  BUILD_TUPLE_UNPACK_WITH_CALLr  r  BUILD_MAP_UNPACK_WITH_CALLr  r  r$  r'  r  r4  r  r=  r>  r  r  rC  rE  rF  rN  rG  rJ  rQ  rR  rY  r]  rc  r  rd  rg  rh  DICT_UPDATEri  rj  rk  rm  rp  rq  rt  rv  r:  posr  negUNARY_NEGATIVEr`  invertUNARY_INVERTpowBINARY_POWERmulBINARY_MULTIPLYmatmulBINARY_MATRIX_MULTIPLYfloordivBINARY_FLOOR_DIVIDEtruedivBINARY_TRUE_DIVIDEr;  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_ORrx  rz  r  r  r#  r~  r  r  r  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  rc  rw  r  r  r  r  r  r  r  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  r2  r6  r   r   r4  r   r     sz  
 #

p. DO#	
+
>
	0(& S<				 ; * 		
1
		!			
































/%

(
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  )ro  rZ  r  )r   r  r   r   r   set_current_tx  s   z$InstructionTranslator.set_current_txr`  r  r  r  r  r   r  r  r1  tuple[Any, ...] | Nonetorch_function_mode_stackr  compiler_fnr  r   r  export_constraintsframe_stater  r   rd  r7  r  r  rl  rk  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_scoper2  r  r]  r  rl  r`  r  r  r  r1  r  rV  rW  rX  rY  r  r  ra  r   r  rd  r  rl  z4Export without one graph - something has gone wrong.dynamismT)is_inputrb  )rc  is_derefed_cell_contents)rd  r   )+r  r   INFOr  r1  r2  r@   _throw_if_in_functorchr   r  r  r[  r  r  rV  r	  r{  r/   r  rn  r   	frozensetrv   rJ  rQ   r  rw  r  r  r  r  ry  rP   cell_contentsr  r   DeletedVariabletrack_cell_existingr   rX  r   rY  realize_all)r   r`  r  r  r  r  r1  r]  r  r^  r  r  r_  r`  r  rd  r  rl  r{  rb  r   ry  local_dynamismr  r  contents_sourcer  cell_varr  cell_sourcer4  r   r   r2  
  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_backendr5  getattr_staticr  r^  _C
_functorchpeek_interpreter_stackTransformTypeVmapGradJvpr  r   lowerr9   )r   rp  r^  ciforbidden_keysr   rG  r   r   r   rf    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   )r>  rQ   r  r  rN   r  r  r  )r   r  r   r   r   get_example_value  s
   

z'InstructionTranslator.get_example_valuec                 C  s6   | j  D ]}t|trt| tjjr dS qdS r   )	rV  r  r>  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 )Nrl  r  )r   r\  r>  rp   ry   r  r`   )r   r  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")NrW  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  ro  r   r  )#r  r   rg  rZ   rX  r   allow_empty_graphsr  r  rb  r  r  r  r   r  r   	SkipFramer5   r  r  r   re  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  ra  r   r  r0  r   r   r   ro    r`  z"InstructionTranslator.RETURN_VALUEc                 C  ra  r   r  r0  r   r   r   rp    r`  z"InstructionTranslator.RETURN_CONST)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   rd  r7  r  r  rl  rk  r   r   r   )r  rS   r   r   r  r  )r   r   r   r  r  rW  rX  r[  r2  rf  r~  r  r  r  ro  rp  r6  r   r   r4  r   r-    s     
&




.r-  r  c                 C  s<   g | ]\}}t td |v r|dd nd|dd  qS )INPLACEr  NBINARY_)ro  r-  )r   r   r   r   r   r   rN    s    $rN  r  r@   rv  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_countra  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  rv  r  caller_infor  trace_successstack_entrytrace_end_nsra  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  rU  r   ra   c                   sZ   d }t  j|  fdd |  |||}| W  d    S 1 s&w   Y  d S )Nc                     s
    j d S rO  ra  r   r  r   r   r   v  s   
 z;InliningInstructionTranslator.inline_call.<locals>.<lambda>)r  r  r  build_inline_tracerinline_call_)r   r  r  r   r  tracerr   r  r   r  l  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*  rq  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   r>  rs   r5  rs  get_functionr   check_verboseskippedtorch._dynamo.variables.miscr  r  r*  r  
SkipResultr   get_filenameget_namer   )r  rG  r  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- |rt|d }d#}t |t.r2|/ s2t0|1 tj2j3r0|4 }nd}|rtt |t5rWj6|j7}t |tj8j9rVt:;|t<=|j>j?d$< nt |t@rt|jA}t |tj8j9rtt:;|t<=|j>j?d$< t |tBr|J tC rtD |jEjFjG|}|S t |jEjFjG|}|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   rN    r  zEInliningInstructionTranslator.build_inline_tracer.<locals>.<listcomp>z; kwargs = z4Argument mismatch when attempting to trace function r=  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  rn  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  	positionsr   rY   r  r  )headerrt  rv  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, %sTr  r   )Hr>  rs   rq   ro   r  r  r  r   dont_skip_tracingpreviously_inlined_functionsrn  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_enabledrT  BytecoderB  r  r^  r  trace_call_logr  r]   r  r   rv   is_realizedr  	peek_typer  r  rg  r   r  r  r}  r  r  r  r/   r  forward__code__r   ry  rr   r,   &InliningGeneratorInstructionTranslatorrW  rX  rY  )r  r  r   r  r  tracing_ctxprevious_result
sub_localsr  r   r8  r  arg0should_checkmoduler  r   r  r   r    s   



"



	z1InliningInstructionTranslator.build_inline_tracerc              
   C  s  | j }d|_d|_| j}t }|jr| |j}z[z| |   W d    n1 s,w   Y  W n9 t	j
yM } zd| d| }t|  d }~w ttfy^ } zd|_ d }~w tyk   td|  w W | j|_d|_n| j|_d|_w | jjrtd 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#|rt | 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  rh  ri  r  rW  nullcontextrf  r  r  r   r   r  r  r:   r;   r  r  r   r  r  rg   rJ  r  r  rW  r  rb  r  traced_coder   r   r  r>  r  is_generator_from_ctx_managerr,   generator_exhaustedis_constant_noner  ri  ry   generated_itemsr`   )r   r  rv  
strict_ctxr  rG  r   r   r   r   r  J  s~   




z*InliningInstructionTranslator.inline_call_rv  r  rV  rW  rX  r   rY  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   )ro  r  rv  r   r   r     s    z:InliningInstructionTranslator.__init__.<locals>.<dictcomp>)r`  rY  r  r  r  r  r  rV  rW  rX  rY  r`  r  r  r  ra  r   r  rd  r  rl  rY  r   )get_globalsr>  r   __dict__r  r  inlined_code_cachern  r`  rY  r  r    r   r   r*   r   r1  r2  r  ra  r  rd  r  rl  r  r  r  r  r  r  r  )r   r  rv  rV  rW  rX  rY  r  r  r  r  cachedr`  rY  r  r4  r  r   r2    s~   

	

z&InliningInstructionTranslator.__init__r  c                 C  s   | j jS r   )r  r  r   r   r   r   r    s   z'InliningInstructionTranslator.fake_modec                 C  s   t | j S r   )r   r  r  r  r   r   r   r   r    rI  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  r1  r   r4  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  r1  r  r9   r  r4  r   r   r    s   
z3InliningInstructionTranslator.create_call_resume_atc                 C  s   |   | _d | _tr   )r  r  r   r(  r0  r   r   r   ro    s   
z*InliningInstructionTranslator.RETURN_VALUEc                 C  s   |  || _d | _tr   )r  r  r   r(  r0  r   r   r   rp    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  rQ  r  r|  rl  r.  r/  r   rc   rL   r  r  rN   rM   rD  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   )ra  r  r  r  r2  r1  r  r  r  r  r.  r  ra   rb  )r   r   r   r   r  r  ry  r4  r   r   r  5  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  r2  r  r1  r(  r  r>  r   r9   ra  r  r  
store_attr)r   r   ry  r   _fglobals_valuer  r   r4  r   r   r(  F  s   
z*InliningInstructionTranslator.STORE_GLOBAL)
r  r   r  rn   r   r  r  rU  r   ra   )r  rn   r   r  )
r  r   r  rn   r   r  r  rU  r   r  r  )r  r   rv  r  rV  rU  rW  rU  rX  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  r  r  r2  r  r  r  r  r  r  ro  rp  r  r  r(  r6  r   r   r4  r   r  e  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  )r1  r2  r  r  r  )r   r   r  r4  r   r   r2  ]  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   d  s    zEInliningGeneratorInstructionTranslator.inline_call_.<locals>.<lambda>)r  r  r  r1  r  r   r4  r   r   r  c  s   $z3InliningGeneratorInstructionTranslator.inline_call_r   c                 C  r  r  r   r   r   r   r   r  g  s   zCInliningGeneratorInstructionTranslator.should_compile_partial_graphr   r+   c                 C  sR   |   }| j| t| jtkrtj| t	d  t
js"| jr'|| _td S r   )r  r  r   r   ru   r   InfiniteGeneratorErrorr.  rg   rJ  r   r  r  r  r)  )r   r   topr   r   r   YIELD_VALUEk  s   z2InliningGeneratorInstructionTranslator.YIELD_VALUEc                 C  sF   | j d }t|ts!|   t| t| |gi }| | d S d S rl  )	r\  r>  ry   r  ra   rb  r  r   r.  )r   r   r  resr   r   r   GET_YIELD_FROM_ITERy  s   

z:InliningGeneratorInstructionTranslator.GET_YIELD_FROM_ITERc                      d| _ t |S r  )r  r1  ro  r0  r4  r   r   ro       z3InliningGeneratorInstructionTranslator.RETURN_VALUEc                   r  r  )r  r1  rp  r0  r4  r   r   rp    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  rl  Unreachable sub-generator coder   @Should only be encountered while implementing generator support.r  r   r   )r   r\  r  r  r9   rh  ri  r   rj  r>  r  r.  rg   rJ  ry  r   r   r  r   r   r=  r  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  rl  r  r  r   r  r  zSEND with bad typez
TOS type: z(Attempted to SEND with unsupported type r=  )r   r\  r  r>  rx   rp   r   ry  collectionsabcIteratorr  rh  ri  r   rj  rB  r  r.  rg   rJ  r  r9   r_   r  r   r   r   SEND  s>   



z+InliningGeneratorInstructionTranslator.SEND)r   r   r  r   r   r   r  r  r  )r   r   r   r   r2  r  r  r  r  ro  rp  r  r  r6  r   r   r4  r   r  Y  s   
 



&r  )r   r   r   r   )r   r  )r   r   r   r  )r*  r+  r   r,  )r;  r<  r   r   )rE  r   r   r   )r   r   r[  r\  r.  r   r   r   )ri  rj  r   r   )rx  )ry  ra   rz  r   r   r   )r[  r\  r.  r   r   r  )r   r   r  r0   r  r  r   r   )r.  r   r  r   r   r  )r  r@   rv  r  r  r  r   r  (  r   
__future__r   r  collections.abcrW  r  r   rT  r8  r   r5  r  r  r   r^  r  rB  	threadingr  r  r?  r  r   typingr   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   bytecode_transformationr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   codegenr0   comprehension_graph_breakr1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   funcname_cacher<   guardsr=   r>   output_graphr?   r@   rA   	polyfillsrB   rC   rD   rE   rF   replay_recordrG   rH   r   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   rf   variables.constantrg   variables.ctx_managerrh   ri   rj   rk   r  rm   variables.functionsrn   ro   rp   rq   rr   rs   rt   variables.iterru   variables.lazyrv   r  rw   rx   ry   rz   r{   r|   variables.miscr}   r~   r   r   r   r   r   variables.nn_moduler   r   variables.setsr   r  r   variables.tensorr   r   r   variables.torch_functionr   r   variables.user_definedr   r   r   r   r   r   r   r   torch._subclasses.fake_tensorr   rl  r   	getLoggerr   r  r  getArtifactLoggerr  r  r  r  r  rZ  r   r   r   containsr   r   r  r   r   cacher   	dataclassr   r   r   r   r   r  rX  r  r  r  r  r   r  r(  r)  r:  rD  rZ  rh  r  rw  r  r  r  r&  r  r'  r7  r   r-  r  _nb_opsry  r  r  r  r   r   r   r   <module>   sZ     D0(
,$	 $		

	L"


*
!C  "! 
c                            /  #	=   w