
    i                      U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlmZmZmZmZmZmZmZ ddl m!Z! ddl"Z"ddl#Z"ddl$m%Z%m&Z& ddl'm(Z(m)Z) dd	l*m+Z+m,Z,m-Z- dd
l.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7mZ8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO ddlPmPZP ddlQmRZR ddl6mSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ ddl\m]Z] ddl^m_Z_m`Z` ddlambZbmcZcmdZd ddlemfZfmgZgmhZhmiZimjZj ddlkmlZlmmZm ddlnmoZompZpmqZqmrZr ddlsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{ ddl9m|Z|m}Z} ddl~mZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZmZ ddlmZ dd lmZmZ dd!lmZmZmZmZ dd"lmZmZ dd#lmZmZmZmZmZmZmZ dd$lmZ dd%lmZ dd&lmZmZmZmZmZmZ dd'lmZmZmZmZmZmZmZ dd(lmZmZ dd)lmZ dd*lmZmZ dd+lmZmZ dd,lmZmZmZmZmZ erdd-lmZmZmZ dd.lmZ dd/lmZ  ej                  eѫ      Ze"j                  j                  ed0      Ze"j                  j                  ed1      Ze"j                  j                  ed2      Ze"j                  j                  ed3      Z ej                         Z ej                         D  ci c]  \  } }|  e|      j                   c}} Zd4ed5<    eej                        j                  Z eej                        j                  Zd6 ed7<   d8 ed9<   ee:jd                  eef   Zd:ed;<   e	j                  dpd<       Zej                   G d= d>             Zej                   G d? d@             Zej                   G dA dB             Zej                   G dC dD             Z G dE dF      Ze	j                  dqdG       Zej                  	 	 	 	 drdI       Zej                  	 	 	 	 drdJ       Zej                   G dK dL             Z G dM dNe      Z G dO dPe      Z G dQ dRe      ZdsdSZdtdTZe	j                  dudU       Ze	j                  dvdV       Ze	j                  dwdW       Zej                   G dX dY             Z	 	 	 	 	 	 	 	 dxdZZd[Z	 	 	 	 	 	 dyd\Z	 	 	 	 	 	 	 	 dzd]Z	 	 	 	 	 	 d{d^Z  G d_ d`e      Zej                   G da db             Z G dc dHed      Z G de dfe      Zej                  dgk\  r9ej                  D cg c]  \  }} eedh|v r|did ndj|did        ! c}}Z	ej                  	 	 	 	 	 	 	 	 d|dk       Z
 G dl dme      Z G dn doe      Zyc c}} w c c}}w )}a  
Core module responsible for converting Python bytecode into TorchDynamo's symbolic execution format.

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

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

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

This is a core part of TorchDynamo's tracing system that enables ahead-of-time
optimization of PyTorch programs.
    )annotationsN)deque)AnycastNoReturnOptionalTYPE_CHECKING	TypeAliasUnion)TypeIs)DynamoProfilerStateFunctionTraceTiming)ObservedExceptionTensorifyScalarRestartAnalysis)InlinedCodeCachetracingTracingContext)	dump_file)
guard_bool)cache_method   )configexcgraph_break_hintsloggingtrace_rules	variables)get_indexofJUMP_OPNAMESlivevars_analysispropagate_line_nums)cleaned_instructionscreate_binary_slicecreate_call_functioncreate_call_function_excreate_copycreate_dup_topcreate_instructioncreate_jump_absolutecreate_rot_ncreate_swapget_code_keysInstructionis_generatoris_jump_absolute	unique_id)code_context)	PyCodegen)	!augment_exc_message_with_hop_nameBackendCompilerFailedcollapse_resume_framesformat_frame_infoget_stack_above_dynamoResumePrologueTracingErrorStepUnsupportedunimplementedUnsupported)get_funcname)GuardBuilderinstall_guard)GraphCompileReasonOutputGraphStackLocalsMetadata)impl_CONTAINS_OP_fallbackimpl_IS_MAPPINGimpl_MATCH_CLASSimpl_MATCH_KEYSimpl_MATCH_SEQUENCE)DummyModuleExecutionRecorder)ContinueExecutionCache"IS_TRACING_RESUME_PROLOGUE_VARNAMEReenterWithTORCH_DYNAMO_RESUME_IN_PREFIX)
AttrSourceDictGetItemSourceGlobalSourceGlobalWeakRefSourceLocalCellSourceLocalSourceSkipGuardSourceSource)is_builtin_constantis_forbidden)	_get_error_on_graph_breakcountersget_fake_valueget_instruction_source_311get_metrics_contextgraph_break_dup_warning_checkeristype
LazyStringproxy_args_kwargs)typestrValueMutationNewVariableTracker)FrameStateSizeEntryVariableBuilderwrap_fx_proxy)BuiltinVariable)CONSTANT_VARIABLE_NONEConstantVariable)ContextWrappingVariableGenericContextWrappingVariableWithEnterFunctionVariableWithExitFunctionVariable)ConstDictVariableSetVariable)BaseUserFunctionVariableLocalGeneratorFunctionVariableLocalGeneratorObjectVariableNestedUserFunctionVariableSkipFunctionVariableUserFunctionVariableUserMethodVariable)MAX_ITERATOR_LIMIT)LazyVariableTracker)BaseListVariableIteratorVariableListIteratorVariableListVariableSliceVariableTupleVariable)CellVariableExceptionVariableGetAttrVariableNullVariablePythonModuleVariableTracebackVariableUnknownVariable)NNModuleVariableUnspecializedNNModuleVariable)SymbolicStreamState)supported_comparison_opsSymNodeVariable)SymbolicTorchFunctionStateTorchFunctionModeVariable)RemovableHandleVariableUserDefinedClassVariable!UserDefinedExceptionClassVariable"UserDefinedExceptionObjectVariableUserDefinedObjectVariable)Callable	GeneratorSequence)FakeTensorMode)CompilePackagegraph_breaks
trace_calltrace_sourcetrace_bytecodedict[str, Any]compare_op_handlersc                2    t        | g t        |      i       S N)handle_containsreversedtxargs_s      o/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py<lambda>r      s    (4.21     inc           
     J    t        | t        | g t        |      i       gi       S r   )
handle_notr   r   r   s      r   r   r      s(    J.x~.	34b5 r   znot inr
   ExceptionValsc                ,    t        j                  |       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)names    r   _import_moduler      s     ""4((r   c                  p    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ZddZy)SpeculationEntrystrfilenameintlinenoinstruction_pointerr-   instFbool_failedNzOptional[bool]error_on_graph_breakzOptional[GraphCompileReason]reasonc                    d| _         || _        | j                  | j                  j                  }nd}t        j                  |      )z\
        Start tracing of the current frame over again, and don't take this branch.
        Tz!Unknown fail_and_restart_analysis)restart_reason)r   r   r   r   SpeculationRestartAnalysis)selfr   r   s      r   fail_and_restart_analysisz*SpeculationEntry.fail_and_restart_analysis   sB     $8!;;"![[//N@N,,NKKr   c                \    | j                   r | j                  J | j                  |_        yyNTF)r   r   )r   r   s     r   failedzSpeculationEntry.failed  s/    <<,,888&*&?&?B#r   )r   r   returnNone)r   InstructionTranslatorBaser   r   )	__name__
__module____qualname____annotations__r   r   r   r   r    r   r   r   r      sC    MK
GT+/./+/F(/
Lr   r   c                      e Zd ZU dZ ej
                  e      Zded<   dZ	ded<   dZ
d	ed
<   ddZddZ	 	 	 	 	 	 	 	 	 	 ddZy)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_gradc                    d| _         y Nr   )r   r   s    r   restartzSpeculationLog.restart  s	    
r   c                F    | j                   j                          d| _        y r   )r   clearr   r   s    r   r   zSpeculationLog.clear"  s    
r   c                6   t        | j                        | j                  k(  r'| j                  j                  t	        ||||             | j                  | j                     }d}| j                  dk7  r]| j                  | j                  dz
     }d|j
                   d|j                   d|j                  j                   d|j                   d	}|j                  |k(  r|j
                  |k(  r|j                  |k(  st        d	| j                   d
t        | j                         d|j
                   d|j                   d|j                  j                   d|j                   d| d| d|j                   d| d| d      | xj                  dz  c_        |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_entrys           r   nextzSpeculationLog.next&  s    t||

*LL 63FM TZZ(::?djj1n5J()<)<(=Qz?P?P>QJOO**+3z/M/M.NcS 
 %%)<<(*&*""&**ZDLL8I7J K^^Aell^2ejj.?.?-@HaHaGb c*AfXR}G4G3H I  	 ( 	

a
r   N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     sn     '8k&7&7&MG#ME3N */ $.--%(-?B-JU-	-r   r   c                  F    e Zd ZU  ej                  e      Zded<   ddZy)
LocalStater   zdict[str, FrameStateSizeEntry]automatic_dynamicc                b    dj                  d | j                  j                         D              S )N
c              3  L   K   | ]  \  }}| d |j                            yw): N)render).0kvs      r   	<genexpr>z$LocalState.render.<locals>.<genexpr>]  s*      
%)QqcAHHJ< 
s   "$)joinr   itemsr   s    r   r   zLocalState.render\  s/    yy 
-1-C-C-I-I-K
 
 	
r   Nr   r   )	r   r   r   r   r   dictr   r   r   r   r   r   r   r   V  s%    8I8I8I95 
r   r   c                  0    e Zd ZU ded<   ded<   dZded<   y)DistributedStater   
compile_pgr   local_stateNzOptional[list[LocalState]]
all_states)r   r   r   r   r   r   r   r   r   r   c  s    O-1J*1r   r   c                  n    e Zd ZU  e       Zded<   edd       Zed	d       Zed
d       Z	edd       Z
y)TensorifyStatezset[str]force_specializationsc                :    | j                   j                  |       y r   )r  addclsr   s     r   
specializezTensorifyState.specializep  s    !!%%e,r   c                    || j                   v S r   )r  r  s     r   should_specializez TensorifyState.should_specializet  s    1111r   c                8    | j                   j                          y r   )r  r   r  s    r   r   zTensorifyState.clearx  s    !!'')r   c                2    t        | j                        dk(  S r   )r   r  r  s    r   emptyzTensorifyState.empty|  s    3,,-22r   N)r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   setr  r   classmethodr  r	  r   r  r   r   r   r  r  j  s_     '*e8+- - 2 2 * * 3 3r   r  c                 4    t        j                  t              S r   )torchdynamo_loggingget_step_loggerlogr   r   r   _step_loggerr    s    ..s33r   r   c              #  D  K   | j                   j                  }| j                   j                  }	 g | j                   _        d| j                   _        d  || j                   _        || j                   _        y # || j                   _        || j                   _        w xY wwr   )speculation_logr   r   )r   r   r   s      r    save_and_restart_speculation_logr    s        ((G$$E)%'"#$ %,"#(  &-"#( s   -B &A9 #B 9$BB c              #     K   	 | j                   j                  }d| j                   _        d  || j                   _        y # | j                   _        w xY wwNF)outputshould_exit)r   tmps     r   (temporarely_allow_writes_to_output_graphr    sA     $ii## %		 #				s   A+A AAAc                  ^    e Zd ZU ded<   ded<   ded<   dZded	<   dd
ZddZ	 	 	 	 	 	 ddZy)BlockStackEntryr-   r   zInstruction | Nonetargetr   stack_indexNzHOptional[Union[ContextWrappingVariable, GenericContextWrappingVariable]]with_contextc                    | j                   d uS r   )r#  r   s    r   can_restorezBlockStackEntry.can_restore  s      ,,r   c                *   | j                   J | j                  rbt        | j                  d      rL| j                  j                  r6t	        | j                   dz
  t        | j                  j                              S t	        | j                   dz
        S )Ntarget_valuesr   )r"  r#  hasattrr'  rK   tupler   s    r   	resume_fnzBlockStackEntry.resume_fn  s    +++))?;!!//  1$eD,=,=,K,K&L  t//!344r   c                    | j                   J |r| j                   j                         s|s| j                   j                  |      S y r   )r#  exit_on_graph_breakexit)r   r   is_graph_breaks      r   r-  zBlockStackEntry.exit  sG       ,,,t00DDF$$))"--r   r  )r   rK   )r   r   r.  r   r   zVariableTracker | None)r   r   r   r   r#  r%  r*  r-  r   r   r   r   r     sQ      	   -5+=A	r   r   c                      e Zd Zy)r   Nr   r   r   r   r   r   r   r         r   r   c                      e Zd Zy)ReturnValueOpNr0  r   r   r   r3  r3    r1  r   r3  c                      e Zd ZdZy)YieldValueOpzY
    Signal to the symbolic tracer to stop and return control flow to the
    caller
    N)r   r   r   r   r   r   r   r5  r5    s    r   r5  c                    t        t        j                  |       j                        t	        |       t        j                  |       dfd       }|S )Nc                h    | j                  j                  | | j                        i              y r   )pushcall_functionpopn)r   r   fn_varnargss     r   implzstack_op.<locals>.impl  s'    		&&&tTYYu-=rBCr   )r   InstructionTranslatorr   r-   r   r   )r   inspect	signature
parametersrf   	functoolswraps)fnr=  r;  r<  s     @@r   stack_oprE    sL    !!"%001ER F__RD D Kr   c                    t        | t        j                        sy| j                  j	                  d      d   t
        j                  v S )NF.r   )
isinstancetypes
ModuleTyper   splitsysstdlib_module_names)mods    r   	is_stdlibrO    s:    c5++,<<c"1%)@)@@@r   c                    | rdd}ndd}t        j                  |      D cg c]  }|j                   }}t        d t	        |      D              }|j                  d      }||dz   |dz    S c c}w )Nc                    | sJ d       y )Nmsgr   xs    r   rD  z(get_assert_bytecode_sequence.<locals>.fn  s    OeO1r   c                    | sJ y r   r   rS  s    r   rD  z(get_assert_bytecode_sequence.<locals>.fn  s	    H1r   c              3  J   K   | ]  \  }}|j                  d       s|  yw)POP_JUMPN)
startswith)r   ir   s      r   r   z/get_assert_bytecode_sequence.<locals>.<genexpr>  s     V71d$//*:UQVs   ##RAISE_VARARGSr   )rT  r   r   r   )disget_instructionsr   r   	enumerater   )with_msgrD  r   insts	begin_idxend_idxs         r   get_assert_bytecode_sequencerb    sr    		 &)%9%9"%=>TT[[>E> Vi&6VVIkk/*GQ1-- ?s   A/c                    t         j                  dk\  sJ dd} t        j                  |       D cg c]  }|j                   }}t        |      dz
  |ddd   j                  d      z
  }|j                  d      }||| S c c}w )	zNGet the bytecode instructions that precede BUILD_LIST in a list comprehension.      c                 >    t        d      D  cg c]  } |  c} S c c} w Nr   rangerY  s    r   rD  z._get_comprehension_bytecode_prefix.<locals>.fn       8$a$$$   	r   NLOAD_FAST_AND_CLEAR
BUILD_LISTr   z	list[int])rL  version_infor[  r\  r   r   r   )rD  r   r_  	start_idxra  s        r   "_get_comprehension_bytecode_prefixrt    s     w&&&% &)%9%9"%=>TT[[>E>E
Qtt!2!23H!IIIkk,'G7## ?s   Bc                     t         j                  dk\  sJ dd} dd}dd}dd}dd} ||       } ||      } ||      } ||      }|d   |d   d	|d   |d   d	|d   |d   d	|d   g d	d
S )a  Discover bytecode patterns for comprehension result handling.

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

    Returns patterns with:
        - pre_store_ops: opcodes between END_FOR and first STORE_FAST
        - post_store_op: first opcode after all STORE_FASTs (for disambiguation)
    rd  c                 @    t        d      D  cg c]  } |  }} |S c c} w rh  ri  )rY  results     r   	fn_storedz5_get_comprehension_result_patterns.<locals>.fn_stored  s#    "1X&!&& '   	c                 @    t        d      D  cg c]  } |  c}  yc c} w rh  ri  rk  s    r   fn_discardedz8_get_comprehension_result_patterns.<locals>.fn_discarded!  s    !Hq 	ry  c                 >    t        d      D  cg c]  } |  c} S c c} w rh  ri  rk  s    r   fn_returnedz7_get_comprehension_result_patterns.<locals>.fn_returned%  rl  rm  c                 P    t        t        d      D  cg c]  } |  c}       S c c} w rh  )sumrj  rk  s    r   fn_consumedz7_get_comprehension_result_patterns.<locals>.fn_consumed(  s    uQx(!A())(s   	#c                   t        t        j                  | j                              d   d   }g }d}t        j                  |       D ]e  }|r|j
                  r nU|j                  }|s"|j                  |k(  s2|xs t        |j
                        }|j                  |j                         g ||j                  d      dz   d }d}g }|t        |      k  r8||   dk7  r0|j                  ||          |dz  }|t        |      k  r	||   dk7  r0|t        |      k  r$||   dk(  r|dz  }|t        |      k  r	||   dk(  r||t        |      k  r||   fS dfS )zCExtract (pre_store_ops, post_store_op) from comprehension bytecode.r   FEND_FORNr   
STORE_FAST)r   r[  findlinestarts__code__r\  starts_line	positionsr   r   r   r   r   r   )	rD  target_liner_  startedinstrposopsidxpre_store_opss	            r   extract_patternz;_get_comprehension_result_patterns.<locals>.extract_pattern+  s_   3--bkk:;A>qA))"- 	+E5,,//Cszz[0!<T%*;*;%<U\\*	+ EKK	*Q.01CHnS\!9  S*1HC CHnS\!9 CHnS\!91HC CHnS\!9 #C.c#hBBdBBr   r   r   )r  post_store_op)stored	discardedreturnedconsumedrq  r   r   )rD  Callable[..., Any]r   ztuple[list[str], Optional[str]])rL  rr  )	rx  r{  r}  r  r  r  r  r  r  s	            r   "_get_comprehension_result_patternsr    s     w&&&%*C4 Y'F-I{+H{+H %+1Iq	J'0|iPQlS&.qkHQKP&.qkBG	 r   c                  N    e Zd ZU dZded<   ded<   ded<   ded	<   ded
<   ded<   y)ComprehensionAnalysisa9  Metadata about a comprehension's bytecode structure.

    Attributes:
        end_ip: Instruction pointer after all comprehension bytecode
        result_var: Name of result variable, or None if result stays on stack
        result_on_stack: True if result stays on stack (discarded, returned, or in expression)
        iterator_vars: Variables from LOAD_FAST_AND_CLEAR (need restoration)
        walrus_vars: Variables assigned via walrus operator (:=) inside comprehension
        captured_vars: Variables read from outer scope via LOAD_FAST inside comprehension
    r   end_ipzOptional[str]
result_varr   result_on_stack	list[str]iterator_varswalrus_varscaptured_varsN)r   r   r   r   r   r   r   r   r  r  R  s,    	 Kr   r  c                   |t         j                  us|ryt        | j                  t              sJ | j                  }dD ]  }t        |      }| j                  ||t        |      z    }|D cg c]  }|j                   }}||k(  sH|r.|j                  d      }| j                  ||z      j                  }	nd}	| j                  t        j                  |	              y yc c}w )NF)FT
LOAD_CONSTzassertion errorT)operatortruthrH  r   r   rb  instructionsr   r   r   argvalr8  rh   create)
r   truth_fnr8  current_instruction_pointerr^  assert_insts	cur_instsr   load_const_idx	error_msgs
             r   &_detect_and_normalize_assert_statementr  g  s     	&4d..444"&":":! 3H=%%'*E,+ 
	 .77TT[[7	7$!-!3!3L!A --/.@&  .	II&--i89!$  8s   -C"Fc                L     dd	 d	 	 	 	 	 	 	 	 	 dfdd fd}|S )Nc                L    t        dd|  dg t        j                  d       y )NzData-dependent branchingzattempted to jump with zyDetected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.z1Use `torch.cond` to express dynamic control flow.gb_typecontextexplanationhints)r:   r   FUNDAMENTALvalues    r   raise_jump_graph_breakz,generic_jump.<locals>.raise_jump_graph_break  s8    .-eW5D"..C		
r   c           	        | j                         sJ d }	  |       |J | j                         r| j                  | j                  |       | j                  | j                  t        |      |       | j                  |       t        j                  d       | j                  j                  | t        dt        |       | | j                         g      d      }| j!                          | j#                  | j$                  |      }
r| j                  |       |j&                  J | j#                  |j&                  |      }t(        j*                  dk\  r%| j                  j-                  t/        d      g       t/        |j0                  |d   	      }	|	j3                  |       | j                  j-                  |	g|z   |z          y # t        $ r}|}Y d }~d }~ww xY w)
Nr   r   zgeneric_jump triggered compilezgeneric_jump r   r   
stack_popsre     TO_BOOLr   )r!  )should_compile_partial_graphr;   maybe_has_backedgeraise_loop_graph_breakf_codelog_graph_breakcode_optionsr   r8  r  debugr  compile_subgraphr?   r`   frame_summarypopcreate_call_resume_atnext_instructionr!  rL  rr  add_output_instructionsr(   r   copy_positions)r   r   r  	extra_msgr   eall_stack_locals_metadataif_nextif_jump	jump_instr8  r  s             r   jump_graph_breakz&generic_jump.<locals>.jump_graph_break  s    00222	"5)  ""$''S9s8 	 	
 			%		23$(KK$@$@%/	{;d>P>P>R=S  %A %
! 	
,,!!%
 IIe{{&&&,,KK%

 w&KK//1CI1N0OP&t{{71:F	  &++YK',AG,KLY  	C	s   G 	G&G!!G&c                J   | j                         }t        j                  rBt        |       r4| j                         }|j	                         rmt        |j                               r| j                  |      S | j                         r | ||       n(t        dd| dg t        j                  ddd       |j                         rJ | j                  j                  dt        j                   gt#        ||fi         | j                  |       y t%        |t&              r|j(                  }t%        |t        j*                        s|d	k7  }t        j,                  j.                  j0                  j3                  |      }|s(t        d
t5        |      dg t        j6                         | j                  |       y  | j                  j                  dt        j8                  gt#        |fi        }t;        | |t=        |j>                  |             } | j                  j                  dt        j                   gt#        ||fi         | j                  |       y |j	                         rt%        |t@              r>|jB                  r2tE        |jB                  jG                  tH        jJ                                |j                               r%r| jM                  |       | j                  |       y y |j                         r| j                         r | ||       y t%        |tN              rS| j                  jQ                  |jR                        } |      r%r| jM                  |       | j                  |       y y t%        |tT              r	 |jW                  | d      }	t%        |	t^              rP|	ja                  | g i       }tc        tc        |	dd       dd       }
|j	                         r|j                         }|
dk(  rbt%        |t
              sRtd        jf                  ji                  dtk        |      jl                         }tY        jn                  tp        | |g       t%        |t
        tr        f      r |      rr| jM                  |       | j                  |       y t%        |t&              r5|ju                         rir| jM                  |       | j                  |       y t        dd|	 d| dg        y  d      r%r| jM                  |       | j                  |       y y y y y |j                         sW|jw                  |       rF ty        |j{                  |                   r%r| jM                  |       | j                  |       y y t%        |t&              r	 t%        |j(                  t        j*                        r|ju                  | j                        }nt}        |j(                  d	k7        } |      r%r| jM                  |       | j                  |       y y t%        |td        j                        r. d      r%r| jM                  |       | j                  |       y y ddl!mA} |jB                  N ||jB                        r< |j                               r%r| jM                  |       | j                  |       y y  |       y # tX        jZ                  $ r] tY        j\                  |        	 |jW                  | d      }	n0# tX        jZ                  $ r tY        j\                  |        d }	Y nw xY wY w xY w# tX        j~                  $ r*}| j                         r | ||d|       cY d }~S  d }~ww xY w)Nz>Data-dependent assertion failed (cannot compile partial graph)zvalue: zuDynamo has determined when encountering a data-dependent assert failure that it should not compile the partial graph.zUse `torch._assert()` to raise a hard AssertionError when the check fails. This error will propagate back the user code that called the compiled function (i.e. Dynamo will not trace any exception handling).zRemove the assert statement.zMove the assert statement outside of any context managers in order to graph break with partial graph compilation (if fullgraph=False).r  r9  r   z#Assertion failed on symbolic shapesr   )example_value__bool____len__rD  r   z&__bool__ should return bool, returned r   z3Data-dependent branching with non-constant __bool__zmethod: z
, result: z}Attempted to perform data-dependent branching on a user-defined object with a __bool__ method that did not return a constant.Tr   )r  r   )is_constant_source)Cr  r    rewrite_assert_with_torch_assertr  is_python_constantr   as_python_constantjumpr  r:   r   r  	is_tensorr  create_proxytorch_assert_asyncr_   rH  r   sym_numSymBoolfxexperimentalsymbolic_shapesexpect_truer   
USER_ERRORscalar_tensorre   rY   noderm   sourcer>   
make_guardr=   SEQUENCE_LENGTHr8  r   get_submodule
module_keyr   var_getattrr   ObservedAttributeErrorhandle_observed_exceptionru   r9  getattrr   rh   r  typer   raise_observed_exception	TypeErrorr   evaluate_exprhas_unpack_var_sequencer   unpack_var_sequencer   	UserErrorBackwardHookVariabler  get_real_value)r   r   r  r  sym_exprrw  scalar_to_tensor_proxyscalar_to_tensorrN  rT  method_nameresult_valuerR  eval_resultr  r  r  r8  r  r  s                   r   innerzgeneric_jump.<locals>.inner  s   !%336tXtL)-I'')002399T?*668$T47! `")% 1%H.::u
 ;N*  (((#'' 'y'92>
 		$%1 !==!(EMM:'1}H..>>JJ8T! E #H$&= 1 < <=	 		$%=T[[%=%=!4!4&7H%SU7V&"  -&,-C-H-H$O  %DKK$$## #$4i#@"E
 IIdO##% %!23ell55l6R6RST0023IIe$		$ 4 __4#D#D#FT4//0++++E,<,<=C}IIe$		$  89	%%dJ7 !/0r26%gat&<j$O,,.#)#<#<#>L"j0LRV9W'88??DT,EWE`E`Dab 44YC5Q!,s<,AW IIe,		$8++- IIe,		$! U"*1#Zx @%X  D>		%(IIdO " . BX<. "u'D'DT'JE55d;<=IIe$		$ > / emmU]];"'"5"5dkk"BK",U]]a-?"@K
 $IIe$		$ % y==>~IIe$		$ 
 3||',>u||,LE0023		%(IIdO 4
 'u-c -- --d3))$	:A11 11$7Av == 446+D$2aSRRs[   [2 ;A]% 2(]"\.-]".*]]"]]"!]"%^"8^^"^^")r  rb   r   r   )r   )
r   r   r   r-   r  rb   r  r   r   r   r   r   r   r-   r   r   r   )r  r8  r  r  r  s   `` @@r   generic_jumpr    s[    

  	7M'7M7M 7M 	7M
 
7Mrw. w.r Lr   c                6   g }| }| |j                  |       |j                  }| t        |      D ]  } | j                  D ]  }t	        |j
                  t              r:|j                  |j                         j                  |j                  |             W|j
                  J t	        |j
                  t              sJ |j
                  j                  |       |j                  |j                         j                  |j                  |               y)zsGenerates bytecode to restore the block stack for running the unsupported instruction
    in the compiled bytecode.N)r   parentr   block_stackrH  r#  r   extend_outputr*  try_except_torch_function_moder  ri   reconstruct_typetry_finally)r   cgcleanupall_txescur_txbs         r   _reconstruct_block_stackr    s     13H24F

 
 x  R 	RA !..*CD  KKM@@
 >>---ann/FHHHNN++B/Q[[]66rPQ	RRr   c                      	 	 	 	 d fd}|S )Nc                j     t        j                         d fd       }	 	 	 	 	 	 	 	 dfd|S )Nc           	        | j                   }| _         | j                         }|j                  |       r"|j                  J  | ||j                        S 	  | |      || _         S # t        $ r)}| j
                  rW| j                  s| j                  r |j                          t        dd| j
                   ddgt        j                  |       |j                  r | j                         s | j                         r| j                  | j                   |       | j#                  | j$                   dt'        |       |       |j                          |j)                  d       t+        |j,                  |j.                        |_        Y d }~nd }~ww xY w	 || _         n# || _         w xY w|j1                  | j                         y )	Nz0Graph break under GenericContextWrappingVariablez!Active generic context managers: z]Attempted to graph break in an active context manager(s) that doesn't support graph breaking.zEMove the offending context manager(s) to outside the compiled region.r  r  r  r  from_excz:

r  graph_break)current_instruction_push	speculater   r   r;   active_generic_context_managers	one_graphr   remove_from_statsr:   r   CAUSED_BY_EARLIER_GRAPH_BREAK
skip_framer  r  r  r  r  r  r   add_to_statsr?   rR  
real_stackr   )	r   r   	prev_pushspeculationexcphandle_graph_breakinner_fn
msg_prefixr8  s	        r   wrapperz>break_graph_if_unsupported.<locals>.decorator.<locals>.wrapper  s   55I,0D)..*K!!$'"))555)$k6H6HII):d+P 1:-O  %S77~~)B)B **,! R"CDDhDhCi j %Dc.LL "&	 ??88:**,//TB$$%%(\s4yk: %  &&(!!-0%7$//%R""K%SJ #09-	-11$2K2KLs+   A) )
F3DFF( FF( (	F1c                <   t         j                  dk\  rt         j                  dk  rs|j                  dk(  rdt        j                  t        j
                  d   |j                        t        j                  t        j
                  d   |j                        z   }n*t        j                  |j                  |j                        }t        j                  d|j                         | j                  j                  | |t        
      |z
        }t        | j                  j                        }g }t        | ||       | j                  j!                  |j#                                ~t         j                  dk\  r|j                  dk(  r| j$                  | j$                  j'                         nd}t)        |      dkD  r<t         j                  d	k  sJ | j                  j!                  t+        d
|      g       |j                  J t-        |j                  d      }|d   j/                  |       | j                  j!                  |       nF|j0                  J t3        j2                  |      }	d |	_        | j                  j!                  |	g       | j                  j!                  |       | j7                  t        
      |z
         
r| j9                  t;                      | j                  j!                  | j=                  | j>                  |             y )Nre     rd  CALLPRECALLz%s triggered compiler  r   r   r  KW_NAMESr  Frn  ) rL  rr  r   r[  stack_effectopmapargopcoder  r  r  r  r   r2   root_txr  r  r\  kw_namesr  r   r(   r$   r  r!  copyexn_tab_entryr:  r8  r   r  r  )r   r   r   r2  r  r  r  r7  
call_insts	inst_copyr8  s             r   r'  zIbreak_graph_if_unsupported.<locals>.decorator.<locals>.handle_graph_break  sy      G+$$w.KK6)  #//IIi($(( $$SYYv%6A B  #//TXXFII,dkk:(,(D(DVD	L0H )E )% 4;;../B)+G$T2w7KK//0C0C0EF7*t{{f/D }}0 MM446 
 x=1$++g555KK77+JxHI xx+++1$((EB
2--d333J? {{*** IIdO	*.	'33YK@KK//8IIc$i,./		/+,KK//**))-r   r  )r   r   r   r-   r   r?   r   r   )rB  rC  )r(  r*  r'  r)  r8  s   ` @r   	decoratorz-break_graph_if_unsupported.<locals>.decorator  sT     
	"2	M 
#2	Mh<	+<	<	 '<	 	<	| r   )r(  Callable[..., None]r   8Callable[[InstructionTranslatorBase, Instruction], None]r   )r8  r)  r<  s   `` r   break_graph_if_unsupportedr?    s$    
v%v	Avp r   c                  $     e Zd ZdZd fdZ xZS )BytecodeDispatchTableMetazTInstalls a `cls.dispatch_table` on every subclass to speed up calls to self.OPCODE()c                @   t         	|   |||       dd}t        j                  j	                         D ci c]'  \  }}|t        | |t        j                  ||            ) }}}t        d      D cg c]  }|j                  |       c}| _
        y c c}}w c c}w )Nc                ^    t        d|  d| d|  dd|  dgt        j                         y )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  )r:   r   SUPPORTABLE)r   r   s     r   _missingz4BytecodeDispatchTableMeta.__init__.<locals>._missing]  sS    2!(+dV4[\b[ccef;F8 D_ _ '22		r      )r   r   r   r   r   r   )super__init__r[  r3  r   r  rB  partialrj  getdispatch_table)
r  r   basesdctrF  r   oprL  rY  	__class__s
            r   rI  z"BytecodeDispatchTableMeta.__init__Z  s    uc*
	 "iioo/
 VY%6%6x%HII
 

 >C4[In003I

 Js   ,B4B)
r  r  r   r   rM  r   rN  r   r   r   )r   r   r   r   rI  __classcell__rP  s   @r   rA  rA  W  s    ^J Jr   rA  c                      e Zd ZU dZ ej
                  e      Zded<    ej
                  d      Z	ded<   dd	Z
dd
ZddZddZ	 	 	 	 	 	 ddZddZ	 	 	 	 ddZddZddZddZddZddZeZy)ExceptionStackzU
    Exception stack that it is shared among all InstructionTranslator instances
    r   zlist[ExceptionVals]
_exc_stackN)defaultzOptional[ExceptionVals]_current_exceptionc                    d | _         y r   rW  r   s    r   clear_current_exceptionz&ExceptionStack.clear_current_exception  s
    "&r   c                4    | j                  |       || _        y r   )._set_context_and_break_context_reference_cyclerW  r   vals     r   set_current_exceptionz$ExceptionStack.set_current_exception  s    ;;C@"%r   c                v    | j                   J | j                  | j                          | j                          y r   )rW  r   rZ  r   s    r   move_current_exception_to_stackz.ExceptionStack.move_current_exception_to_stack  s2    &&222D++,$$&r   c                6    | j                   J | j                   S r   rY  r   s    r   get_current_exceptionz$ExceptionStack.get_current_exception  s     &&222&&&r   c                    |j                   x}rt        |      t        ur|S t        | j                        |z   dkD  r5| j                  |   }| j                  ||dz
         |j                  |       |S Nr   r   )__context__r  rh   r   rU  _set_context_recursiveset_context)r   r^  prev_idxctxprevs        r   rg  z%ExceptionStack._set_context_recursive  sm     ??"C"S	9I(IJt(*Q.??8,D''hl;OOD!
r   c                    |x}}d}	 |j                   }t        |      t        u ry ||u r|j                  t               y |}||u ry |r|j                   }| }Qr  )rf  r  rh   rh  rg   )r   r^  oslow_oslow_update_toggler  s         r   _break_context_reference_cyclez-ExceptionStack._break_context_reference_cycle  st    
 F"mmGG} 00#~45AF{ !++%7!7% r   c                v    | j                  |t        | j                        dz
         | j                  |       y rh  )rg  r   rU  rp  r]  s     r   r\  z=ExceptionStack._set_context_and_break_context_reference_cycle  s0     	##CT__)=)AB++C0r   c                6    | j                   j                         S r   )rU  r  r   s    r   r  zExceptionStack.pop  s    ""$$r   c                :    | j                   j                  |       y r   )rU  r   r]  s     r   r   zExceptionStack.append  s    s#r   c                ,    t        | j                        S r   )r   rU  r   s    r   r  zExceptionStack.__len__  s    4??##r   c                     | j                   |   S r   )rU  )r   r   s     r   __getitem__zExceptionStack.__getitem__  s    u%%r   c                :    d| j                   d| j                  S )Nzself._exc_stack=z - self._current_exception=)rU  rW  r   s    r   __str__zExceptionStack.__str__  s"    "$//##?t'>'>&@AAr   r   )r^  r   r   r   )r   r   )r^  r   ri  r   r   r   r  )r   r   r   r   r   )r   r   r   r   r   r   r   rU  r   rW  rZ  r_  ra  rc  rg  rp  r\  r  r   r  rv  rx  __repr__r   r   r   rT  rT  q  s     '8k&7&7&MJ#M2C+2C2CD2Q/Q'&'
'	 	,/			861 1	1%$$&B Hr   rT  c                      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<   dd4Zdd5Zdd6Zdd7Zdd8Zdd9Z		 	 	 	 	 	 	 	 dd:Z
	 	 	 	 	 	 	 	 dd;Z	 	 	 	 	 	 	 	 dd<Zddd=Zd d>Zdd?Zdd@Zej$                  dAk\  rddBZnddCZeddD       ZddEZddFZddGZddHZddIZddJZd	dKZddLZddMZddNZddOZ ddPZ!eZ"d
dQZ#ddRZ$ddSZ%e&jN                  ddT       Z(ddUZ)ddVZ*e+ddW       Z,ddXZ-d dYZ.ddZZ/e/Z0dd[Z1e+dd\       Z2dd]Z3dd^Z4e4Z5e4Z6 e7e8jr                  d_      Z: e7e8jv                  d_      Z< e7e8jr                  d`      Z= e7e8jv                  d`      Z>ddaZ?ddbZ@ddcZAdddZBddeZCddfZDddgZEddhZFddiZGddjZHddkZIddlZJddmZKddnZLddoZMddpZNddqZOddrZPddsZQddtZRdduZSddvZTddwZUddxZVddyZW eXd`dz{      dd|       ZY eXd`d}{      dd~       ZZ eXd`d{      dd       Z[ddZ\ddZ]ddZ^ddZ_ddZ`ddZa eXd_d{      dd       ZbddZced	 	 	 	 	 	 dd       Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZf	 	 	 	 	 	 ddZged	 	 	 	 	 	 	 	 dd       ZhddZi eXd_d{      dd       ZjddZkddZlddZmddZnddZoddZpddZqerfddZsddZtetZuddZvddZwewZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZddZ eXd_d{      dd       ZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZeZddZddZddZddZddZddZddZddZ ee8j:                        Z ee8j>                        Z ee8jr                        Z ee8jD                        Z ee8jH                        Z ee8jL                        Z ee8jP                        Z ee8jT                        Z ee8jX                        Z ee8j\                        Z ee8j\                        Z ee8jb                        Z ee8jf                        Z  eXd`d{       ee8jj                              Z ee8jn                        Z ee8jr                        Z ee8jv                        Z ee8jz                        Z ee8j~                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        Z ee8j                        ZېddZej$                  dAk\  rddZݐddZސddÄZߐddĄZdddńZ eXd`dƬ{      ddǄ       ZddȄZddɄZe4Ze4Z e7e8jv                  d_      Z e7e8jv                  d_      Z e7e8jr                  d_      Z e7e8jr                  d_      ZddʄZdd˄Z	 	 	 	 	 	 dd̄Zedd d̈́       Zdd΄ZddτZddЄZddфZdd҄ZddӄZddԄZddՄZddքZddׄZdd؄Z eXd`d٬{      ddڄ       ZddۄZdd܄Zdd݄ZddބZdd߄ZeZ eZeZdZddZddZdZddZddZ	 d	 	 	 d!dZ	d"dZ
ddZd#dZed$d       Zej                  	 	 	 	 d%d       Zd&dZddZd'dZd(dZddZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 d)dZ	 	 	 	 	 	 d*dZ	 	 	 	 	 	 	 	 d+dZ	 	 	 	 d,dZ	 	 	 	 	 	 	 	 d-dZedd.d       Z	 	 	 d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0 fdZ xZS (1  r   r@   r  dict[str, VariableTracker]symbolic_localssymbolic_globalsr   symbolic_torch_function_stater   symbolic_stream_statez$Optional[dict[str, VariableTracker]]post_prune_cell_and_freevarslist[VariableTracker]stackOptional[int]r   r-   current_instructionr   r  zlist[BlockStackEntry]r
  r   r   zOptional[ConstantVariable]r7  accept_prefix_instlist[Instruction]prefix_instsinline_depthinconsistent_side_effectszOptional[SpeculationEntry]current_speculationz	list[Any]rL  rT  exn_vt_stackzOptional[ExecutionRecorder]exec_recorderz+Optional[Callable[[VariableTracker], bool]]strict_checks_fnstart_pointhas_no_inlined_callsz#Optional[InstructionTranslatorBase]r	  is_child_tracer_activez3list[tuple[VariableTracker, list[VariableTracker]]]debug_localsOptional[CompilePackage]packagez
deque[str]latest_bytecode_queuec                    d| _         y)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)r  r   s    r   mark_inconsistent_side_effectsz8InstructionTranslatorBase.mark_inconsistent_side_effects  s     *.&r   c                   | }||j                   j                  }|j                  J |j                  |j                  d  D ]8  }|j                  dv r n(|j                  t
        v s&|j                  }||k  s8 y |j                  }|y)N)RETURN_VALUERETURN_CONSTTF)r  offsetr   r  r   r   r  r	  )r   r  
cur_offsetr   jump_offsets        r   r  z,InstructionTranslatorBase.maybe_has_backedge  s    * 7; 33::J--999++F,F,F,HI $;;"BB;;,."&++K"Z/#$ ]]F   r   c                     | j                   d   S )Nco_cellvarsr  r   s    r   cellvarsz"InstructionTranslatorBase.cellvars$        //r   c                     | j                   d   S )Nco_freevarsr  r   s    r   freevarsz"InstructionTranslatorBase.freevars'  r  r   c                ~    t        | d      s&| j                         | j                         z   | _        | j                  S )N_cell_and_freevars)r(  r  r  r  r   s    r   cell_and_freevarsz+InstructionTranslatorBase.cell_and_freevars*  s2    t12&*mmo&GD#&&&r   c                V   | j                   j                         D ci c]  \  }}|| j                         v r|| c}}| _        t	        | j
                  | j                        }| j                   j                         D ci c]  \  }}||v s|| c}}| _         y c c}}w c c}}w r   )r|  r   r  r  r    r  r  )r   r   r   readss       r   prune_dead_localsz+InstructionTranslatorBase.prune_dead_locals/  s     ,,224-
1D**,, qD-
) "$"3"3T5M5MN!11779 
QQ%ZAqD 
-
 
s   BB%B%c                   t        |t              sJ t        |t              sJ t        |t              sJ t	        d t        j                  ||j                               D              sJ d }t        |d      r|j                  }t        |d      r|j                  }|r$t        |      rt        |      rt        d|       | j                  |j                  | ||             y )Nc              3  <   K   | ]  }t        |t                y wr   )rH  rb   )r   rT  s     r   r   z:InstructionTranslatorBase.call_function.<locals>.<genexpr>E  s      
 q/*
   r  rD  z$Attempt to trace forbidden callable )rH  rb   r   r   all	itertoolschainvaluesr(  r  rD  callablerV   AssertionErrorr8  r9  )r   rD  r   kwargsr(  s        r   r9  z'InstructionTranslatorBase.call_function<  s     "o...$%%%&$''' 
__T6==?;
 
 	
 
 2wxxH2tuuH*|H/E #Gz!RSS		"""4v67r   c                ^    t        |t              st        |      }|j                  | ||      S )zD
        Redirect the call to the generator "call_function"
        )rH  rp   r9  r   rD  r   r  s       r   inline_generator_functionz3InstructionTranslatorBase.inline_generator_functionR  s.     "<=/3BdF33r   c                    t         j                  r,t        |j                               r| j	                  |||      S t
        j                  | |||      S )zF
        A call to some user defined function by inlining it.
        )r   "enable_faithful_generator_behaviorr.   get_coder  InliningInstructionTranslatorinline_callr  s       r   inline_user_function_returnz5InstructionTranslatorBase.inline_user_function_return_  sF     44bkkm9T11"dFCC0<<T2tVTTr   c                    || j                   }| j                  dkD  rd| j                   dnd}t        | j                  j                  |      }|dnd| d}| j                  j                   d| d| j                  j
                   | | S )Nr   z (inline depth: )r   r   r   z in )r   r  r<   r  co_filenameco_name)r   r   inline_depth_strfuncnamefuncname_strs        r   get_line_of_code_headerz1InstructionTranslatorBase.get_line_of_code_headerm  s    >[[F7;7H7H17Lt0013RT 	   7 7@%-rRz3C++))*!F848K8K7L\N[kZlmmr   c                    d| j                          d}t        j                  | j                  j                  | j
                        j                         }|d| z  }|S )NzTRACE starts_line r   z    )r  	linecachegetliner  r  r   rstrip)r   log_strlines      r   get_log_starts_line_log_strz5InstructionTranslatorBase.get_log_starts_line_log_strw  sX    &t'C'C'E&FbI  !8!8$++FMMOT$= r   c                   | j                   |k(  ry || _         t        j                  | j                  j                  || j                  j
                         | j                  r*t        j                  dt        | j                               y y )N%s)r   r   set_current_locr  r  r  is_trace_source_log_enabledtrace_source_logr  r^   r  )r   r   s     r   r  z%InstructionTranslatorBase.starts_line}  sl    ;;& &&KK##VT[[-@-@	
 ++""4D4T4T)UV ,r   c                   t               | _        | j                  }|y| j                  |   x| _        }|dz   | _        |j
                  r| j                  |j
                         | j                  sb| j                         rR| j                         rB| j                         | _
        | j                  j                  |       r| j                  |       y| j                  r?t        j                  d|j                   |j"                  t%        | j                               t&        j(                  rW	 t%        | j                        }| j,                  j/                  d|j                    dt%        |j"                         d|        | j1                  |       	  | j2                  |j4                     | |       | j6                  j8                   S # t*        $ r d}Y w xY w# t:        $ r  t<        j>                  $ r}| jA                  |       Y d}~yd}~wtB        tD        f$ r Y ytF        tH        f$ r}| jJ                  s4| j                  s(| jL                  stO        |tF              r>|jP                  r2tO        |tH              r!tS        d	d
dddgtT        jV                          | j                  atX        j                  d       tO        |tH              r"tS        dd
dddgtT        jV                  d       tO        |tF              sJ d|_(         dt[        |       }| j]                  | j^                  ||       Y d}~nd}~ww xY w| j                  ja                  | j                         y)z<Process exactly one instruction, return False we should exitNFr   zTRACE %s %s %sz0<self.stack repr truncated due to large integer>zTRACE  Tz3cannot resume from torch._dynamo.step_unsupported()r   ztraced torch._dynamo.step_unsupported(), but Dynamo is instructed to error on graph break. This graph break is used for debugging only.z1Remove the torch._dynamo.step_unsupported() call.z9Make sure fullgraph=False and error_on_graph_break=False.r  z1empty checkpoint - cannot resume from graph breakz6torch._dynamo.step_unsupported() with empty checkpointztraced torch._dynamo.step_unsupported(), but there is no checkpoint to step_graph_break from. This graph break is used for debugging only.zInclude at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some line of code that is not in a try/with block, and has an empty Python stack.)r  r  r  r  r!  zEncountered graph break that we cannot resume from. Compiling up to the previous resumable state, then skipping the rest of the function. Graph break encountered:

r  )1rW   r   r   r  r  r  r  r  is_non_empty_graphr  r  r   step_graph_breakis_trace_bytecode_log_enabledtrace_bytecode_logr  r   r  reprr   verbose
ValueErrorr  r   update_block_stackrL  r5  r  r  r   r   r   exception_handlerr3  r5  r;   r9   r  is_tracing_resume_prologuerH  r!  r:   r   
DYNAMO_BUGr  r   r  r  r   )r   ipr   
stack_reprr  r   s         r   stepzInstructionTranslatorBase.step  s4   $=$?!%%:*.*;*;B*?? 4#%6 T--. 

113'')'+~~'7D$''..t4%%d+--$$ $++t{{D<L >>P!$**-
 &&--QtDKK'8&9:,G 	%B	,D,T48{{....  PO
P . 	$$ 	""1%|, 	_- 8	 ,,22q+.1<<a1! U "%` PW /99
 ''/		MNa1! X "%a Pk /99	 $( "![111#/ 031vh8    !! !  i8	t 	  ::4;T;TUs=   0G 6G  GG M
<HM
&M
5DMM
r,  c                   |j                   }|rt        | j                        dk\  rg|j                  | j                  d   j                  urA|j                  | j                  d   j                  u r| j                  j	                          y y y y | j                  rD|j
                  dvr5t        | j                        dk(  sJ | j                  j	                          y y y )N   rn  )NOPJUMP_BACKWARD	NOT_TAKENr   )r9  r   r
  r!  r  r   )r   r   r   s      r   r  z,InstructionTranslatorBase.update_block_stack  s     &&E (()Q.D,<,<R,@,G,GG(8(8(<(C(CC $$((* D H /" ## < ) t//0A555$$((*)#r   c                     y r   r   r   r   s     r   r  z,InstructionTranslatorBase.update_block_stack)  s    r   c                P    | j                   J | j                  | j                      S r   )r   r  r   s    r   r  z*InstructionTranslatorBase.next_instruction,  s+    ''333  !9!9::r   c           	     >
   | j                   j                  rJ | j                  J | j                  rJ t        j                  d       | j                   j                  | t        d| j                         g            }| j                  rTddl
m} t        j                  sJ t        | j                   j                        }|j!                  g t#        d      |j%                  d      |j'                         t)        dd	      t#        d      |j%                  d      |j'                         t)        dd	             | j+                  d||d   g |d
d      \  }} ||       g }t-        | j                  ||       | j/                  |g|g|       |j!                  |       |j!                  g t#        d      |j%                  d      t)        d      t#        d      |j%                  d      t)        d             |d   j0                  }|j!                  g t#        d      |j%                  d      |j'                         t3        d|             |j!                  g t5        d      t)        dd	             | j                  j7                  t9                      |d   xj0                  dz  c_        |dkD  rz|j!                  g t#        d      |j%                  d      |j'                         t;               t3        |d       t5        d      |j%                  d      t)        d             |j!                  t)        d|dz   	      t)        d|dz   	      t)        d|dz   	      g       | j                   j=                  |j?                         | j                  jA                  | j                  jB                  |dd        z          y | j                   j=                  g t5        d      t)        d             t        | j                   j                        }| j                   j=                  |j%                  d      |j'                         g       |d   jD                  jG                         D ]X  \  }	}
| j                   j=                  t;               |j%                  |
      |j'                         |jI                  |	      g       Z | j                   j=                  t)        d      tK        |      g| jL                         y )Nzstep triggered compilestep_unsupported)r   r   	skip_coder  r   rp  r4  TFDELETE_SUBSCRre  LIST_APPENDSTORE_SUBSCRUNPACK_SEQUENCEPOP_TOPrn  )'r  output_instructionsr  r  r  r  r  r?   r  r	  
eval_framer  r   nested_graph_breaksr2   r6  r  r&   create_load_constcreate_binary_subscrr(   create_resumer  codegen_call_resume	num_stackr#   r+   r8  r   r'   r  r\  r  r  locals_namesr   create_storer)   r  )r   continue_instr  r  r  leaf_resume_codeleaf_resume_namer  r  localr  s              r   r  z*InstructionTranslatorBase.step_graph_break1  sF   ;;2222''333 ::~ 			*+$(KK$@$@%&84;M;M;O:PQ %A %
! ;;- ----4;;../B 	 ^	((+	 ++-	 '|;		
 !^	 ((+	 ++-	 '|;	 261C1C=";A">Be2.. &')+G$T[["g> $$&6%7:J9KRPW%  ^((+ '7 !^	
 ((+ '7	 2!4>>I ^((+ ++- )I6	  ^&}!< KK_./%a(22a72
 1}  	$Q	,,Q/	 //1	 '(		
 -Y=	 %Q	 ,,Q/	 +>:	" &'8i!mL&|QG&'8i!mL" KK//##%++33KK002KAB2O KK// ^&y1 4;;../BKK//((,++- 8;HHNNP 
s33&(,,S1//1.	 KK//&y1(7 &&r   c                ,    t        j                  d       S r   )r   current_framer   s    r   run_ctx_mgrz%InstructionTranslatorBase.run_ctx_mgr  s     ++D11r   c           
        | j                         5  t        | j                  j                         	 | j                  j                  |        | j                  | _        	 | j                         r	 | j                         r| j                  jO                          t)        | t,              r5| j                  jQ                          | j                  jS                          	 d d d        y # t        $ rY}| j                  rGt        dt        |      j                   dt        |             j                  |j                         d  d }~ww xY w# t"        $ r  t$        $ r  t&        $ r}t)        |t*              rTt)        | t,              rD| j.                  s8| j0                  s,dt        |       }| j3                  | j4                  ||       t7        |d      rpd|j8                  v rbt:        j<                  j?                  | j                  j@                  | j                  jB                        jE                  ddd	      }||_#          d }~wt        $ r1}| jH                  r| jH                  jK                         |_&         d }~ww xY w# | j                  jO                          t)        | t,              r5| j                  jQ                          | j                  jS                          w w xY w# 1 sw Y   y xY w)
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  rR  zData-dependentFT)print_outputinclude_strideinclude_device)*r  r   r  r  r  push_txr   r  r  	Exceptionr  r8   r  r   r   with_traceback__traceback__r   r4   RuntimeErrorrH  r;   r>  r   r  r  r  r(  rR  r  r  GraphModule
nn_modulesgraphprint_readablepartial_fx_graphr  
get_recordexec_recordpop_txr  mark_bytecode_tracing_stop)r   r  r   readable_graphs       r   runzInstructionTranslatorBase.run  s    G	=dkk--.E=##D)#'#;#; 
))+ ))+j ""$ d$9:KK'')
 KK::<OG	= G	= ! 668_#Aw334Bs1vh@ ).9t	D
  2 (    q+."4)>? 55 NN77:1vh@ 
 (())% )  1e$)9QUU)B%*XX%9%9..0A0A&$n%*4PT %  #
 *8A& %%$($6$6$A$A$CAM	 ""$ d$9:KK'')
 KK::< ;CG	= G	=sh    K.,E!C)AK.)	E2AEEEJ)C!I

J,JJJ

A!K++K..K7c                    |#t        |t              sJ dt        |              | j                  j	                  |       y )Nz"push expects VariableTracker, got )rH  rb   r`   r  r   r]  s     r   r8  zInstructionTranslatorBase.pushE  s?    {jo> 	
0?	
> 	

#r   c                4    |D ]  }| j                  |        y r   r8  )r   valsr^  s      r   	push_manyz#InstructionTranslatorBase.push_manyK  s     	CIIcN	r   c                6    | j                   j                         S r   )r  r  r   s    r   r  zInstructionTranslatorBase.popO  s    zz~~r   c                p    g t        t        |      D cg c]  }| j                          c}      S c c}w r   )r   rj  r  )r   nr   s      r   r:  zInstructionTranslatorBase.popnR  s*    :uQx8!488:89::8s   3
c           	        |j                   }| j                  r7|| j                  v r)| j                  j                  || j                  |          	 | j	                  | j
                  |   j                                |j                  d      r| j
                  j                  |       y y # t        $ r |j                  d      rh	 |j                  dd      }| j	                  | j
                  |          n\# t        $ r* t        dd| d| ddgt        j                         Y n*w xY wt        d	d| d
| dg t        j                         Y w xY w)NrG  implicitz5Attempted to read undefined local variable (implicit)z
LOAD_FAST z5Could not find an implicit local variable with name ``z(This happens in dict/list comprehensionsr  z*Attempted to read undefined local variablez+Could not find a local variable with name `__stack)r  r  f_localsadd_local_varr8  r|  unwrapKeyErrorrX  replacer:   r   r  r  )r   r   r   new_names       r   	LOAD_FASTz#InstructionTranslatorBase.LOAD_FASTU  sP   {{$$--"7,,T4==3FG	IId**40779:4 ??9%  $$T* &3  	s##||C<HIId228<= 	! W",TF 3&[\`[aab$cF.99		 H(/"MdVST U9-889	#	s6   ,B+ +E0C76E70D*'E)D**)EEc                   |j                   | j                         v sJ | j                  |j                      }| j                  j                  j                  |      }| j                  |       | j                  rW|j                   | j                  v r>| j                  j                  |j                   | j                  |j                             y y y r   )
r  r  r|  r  side_effects	load_cellr8  r  r&  r'  )r   r   cellcontents_vars       r   
LOAD_DEREFz$InstructionTranslatorBase.LOAD_DEREFx  s    {{d446666##DKK0{{//99$?		,$++">,,T[[$--:TU #?r   c                    |j                   }| j                         }|j                  |       || j                  |<   |t        k(  r+|j                         }t        |      t        u sJ || _        y y r   )	r  r  set_name_hintr|  rJ   r  r  r   r  )r   r   r   	loaded_vtr^  s        r   r  z$InstructionTranslatorBase.STORE_FAST  sj    {{HHJ	%%.T"55..0C9$$$.1D+ 6r   c                2    | j                   |j                  = y r   )r|  r  r  s     r   DELETE_FASTz%InstructionTranslatorBase.DELETE_FAST  s      -r   c                R   |j                   | j                         v sJ | j                  |j                      }| j                         }| j                  j
                  j                  ||       t        |t              sJ |j                  |j                  |j                         y y r   )r  r  r|  r  r  r.  
store_cellrH  r~   
local_namer4  )r   r   r0  r^  s       r   STORE_DEREFz%InstructionTranslatorBase.STORE_DEREF  s    {{d446666##DKK0hhj  ++D#6$---??&doo. 'r   c                   |j                   }| t        j                  |j                        S | j                  |   }|s<t        j                  |j                        | j                  |<   | j                  |   }|J |S )Nr  )r4  rh   r  r  _constants_cache)r   r   rY  r^  s       r   _load_constz%InstructionTranslatorBase._load_const  sv    HH9#**==##A&'7'>'>T[['QD!!!$''*C
r   c                D    | j                  | j                  |             y r   )r8  r>  r  s     r   r  z$InstructionTranslatorBase.LOAD_CONST  s    		$""4()r   c           	        |j                   }| j                  rn|| j                  v r*| j                  j                  || j                  |          n6|| j                  v sJ | j                  |   | j                  j
                  |<   || j                  vr| j                  |      S || j                  v r\| j                  j                  | j                  |      }| j                  | j                  j                  j                  ||             y | j                  |   }| j                  t        j                  | |t        |                   y r   )r  r  	f_globalsadd_global_var
f_builtinsbuiltinsload_builtinr}  r  r.  r8  load_globalrb   buildrO   )r   r   r   variabler  s        r   _load_globalz&InstructionTranslatorBase._load_global  s   {{t~~%""11$t8LMt...48OOD4I""++D1t~~%$$T**4((({{//0E0Ed0KLHIIdkk..::8TJKt$		/''e\$5GHIr   c                l    d}| j                  |      }t        |      }t        j                  | ||      S )Nztorch.nn.modules.module)import_sourcer   rb   rG  )r   module_namemodule_sourcefglobals_values       r   nn_modules_globals_vtz/InstructionTranslatorBase.nn_modules_globals_vt  s6    /**;7'4$$T>=IIr   c                8   |j                   J t        j                  dk\  r3t        j                  dk  r |j                   dz  r| j                  |       | j	                  |       t        j                  dk\  r"|j                   dz  r| j                  |       y y y )Nr,  r  r  )r4  rL  rr  	PUSH_NULLrI  r  s     r   LOAD_GLOBALz%InstructionTranslatorBase.LOAD_GLOBAL  s~    xx###w&3+;+;g+E$((UV,NN4 $w&488a<NN4  ,8&r   c                   | j                         }|j                  }t        |      }|| j                  vrt	               | j                  |<   | j
                  j                  j                  || j                  |         }t        |t              rt        d|dg        | j
                  j                  j                  |||       y )Nz%Storing Tensor hook handle in globalsThis is not supported.r  )r  r  rO   r}  objectr  r.  track_global_existingrH  r   r:   store_global)r   r   r  r   r  rH  s         r   STORE_GLOBALz&InstructionTranslatorBase.STORE_GLOBAL  s    
{{d#t,,,*0(D!!$';;++AAD))$/
 e45?4	 	  --heDr   c                   d|v rZt         j                  j                  j                  |   }|j	                  dd      j	                  dd      j	                  dd      }n t        |      }d|j	                  dd       }| j                  | j                  j                  ||       || j                  j                  |<   | j                  j                  }||vs	||   |u sJ |||<   | j                  j                  |       t        |      S )z-Create an alias to a module for use in guardstorch_package>r   <rG  _dot_	__import_)r  r  package_importer_package_imported_modulesr*  r   add_import_sourcer  import_sourcesglobal_scopeupdate_co_namesrO   )r   rL  r  aliasrA  s        r   rK  z'InstructionTranslatorBase.import_source  s    k)MM22LLE ##C-55c3?GGWU  #;/E 3 3C ABCE<<#LL**5+>,7""5)KK,,	I%5)9U)BBB 	%##E*E""r   c                ~    |j                  d|dz
        }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
        rG  r   z2attempted relative import beyond top-level packager   )rsplitr   ImportError)r   r   r  levelbitsbases         r   resolve_namez&InstructionTranslatorBase.resolve_name  sQ     ~~c519-t9uRSSAw#'$q1T1r   c                   | j                   j                  d      }| j                   j                  d      }|6|2||j                  k7  r#t        j	                  d||j                  d       |S ||j                  S t        j	                  dd       | j                   d   }d| j                   vr|j                  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__z)__package__ != __spec__.parent (%r != %r)re  )
stacklevelzYcan't resolve package from __spec__ or __package__, falling back on __name__ and __path__r   __path__rG  r   )rA  rK  r	  r  warning
rpartition)r   r  specs      r   calc_packagez&InstructionTranslatorBase.calc_package  s    
 ..$$]3~~!!*-Gt{{$:?KK 	   N;;KK8  
 nnZ0G/!,,S1!4r   c           
     l   | j                  d      \  }}|j                         }|j                         }|j                  }t        j                   d| d| d| }|| j
                  v r| j
                  |   }t        |      }n{	 t        |||| j
                        }|d
k7  r#| j                         }| j                  |||      }|s&|j                  d      d
   }	| j                  |	      }n| j                  |      }| j                   r| j                   j#                  |       t%        t&        j(                  t*        f      r| j-                  t/        ||             y t        dt1        |      dg 	       y # t        $ r, t        dd| d| d| dg t        j                  	       Y w xY w)Nr  r   )fromlistri  globalszImport failurezmodule_name: z, fromlist: z, level=z"Failure when attempting to import.r  r   rG  r  zBad import resultz%Import result is not a Python module.)r:  r  r  rH   LOCAL_MOD_PREFIXrA  rO   
__import__rh  r:   r   r  ru  rl  	partitionrK  r  add_local_modr]   rI  rJ  rG   r8  r   r`   )
r   r   ri  rw  rL  recorded_namer  r  pkgtop_level_module_names
             r   IMPORT_NAMEz%InstructionTranslatorBase.IMPORT_NAME   s   ))A,x((*..0kk !112!E7!H:Q{mT 	 DNN*NN=1E!-0F"% NN	 z'')"//S%H (3(=(=c(B1(E%++,AB++K8,,]EB %%**K89II*5@A+CA  ,+K=XJhW\V]^ D9-889	 s   E> >1F32F3c                \    | j                  |       | j                  |j                         y r   )DUP_TOP
_load_attrr  r  s     r   IMPORT_FROMz%InstructionTranslatorBase.IMPORT_FROM`  s    T$r   c                b   || j                   vr#t        ddd| dg t        j                         | j                   |   }t	        |      rBt        | j                  j                        }t        ||      }t        j                  | ||      S t        |      sJ t        j                  |      S )Nz%failed to find name in frame builtinsr   zFailed to find name `z` in frame's builtins.r  r  )rC  r:   r   r  r  rO   r  %name_of_builtins_dict_key_in_fglobalsrN   rb   rG  rU   rh   r  )r   r  r^  builtins_source
var_sources        r   load_builtin_from_argvalz2InstructionTranslatorBase.load_builtin_from_argvalf  s    (?3F8;QR&11	 oof%C=*AAO +?FCJ"((sJ??&s+++#**55r   c                X    | j                  | j                  |j                               y r   )r8  r  r  r  s     r   rE  z&InstructionTranslatorBase.load_builtin}  s    		$//<=r   c                   | j                   J | j                  J |j                  J t               j	                  d| j                   | j                  z
         | j
                  |j                     | _         | j                   | _        y )Nir_count)r   r  r!  r[   	incrementindexofr  s     r   r  zInstructionTranslatorBase.jump  s    ''333+++{{&&&''0043C3CC	
 $(<<#< 33r   FTc           	         |j                   J | j                  j                  t        ||j                   t	        | j
                                     y r   r!  r
  r   r   r   r  r  s     r   
SETUP_LOOPz$InstructionTranslatorBase.SETUP_LOOP  ;    {{&&&dkk3tzz? STr   c           	         |j                   J | j                  j                  t        ||j                   t	        | j
                                     y r   r  r  s     r   SETUP_EXCEPTz&InstructionTranslatorBase.SETUP_EXCEPT  r  r   c                8    | j                   j                          y r   )r
  r  r  s     r   	POP_BLOCKz#InstructionTranslatorBase.POP_BLOCK  s    r   c                &    | j                  |       y r   setup_or_before_withr  s     r   
SETUP_WITHz$InstructionTranslatorBase.SETUP_WITH      !!$'r   c           	         |j                   J | j                  j                  t        ||j                   t	        | j
                                     y r   r  r  s     r   SETUP_FINALLYz'InstructionTranslatorBase.SETUP_FINALLY  s;    {{&&&dkk3tzz? STr   c                &    | j                  d        y r   r  r  s     r   BEGIN_FINALLYz'InstructionTranslatorBase.BEGIN_FINALLY  s    		$r   c                    | j                  d      \  }}|J | j                  |       | j                  |j                  | t        gdz  i              y )Nr  re  )r:  r8  r9  rg   )r   r   r-  r   s       r   WITH_CLEANUP_STARTz,InstructionTranslatorBase.WITH_CLEANUP_START  sL    IIaL	c{{		#		$$$T,B+Ca+GLMr   c                H    | j                  d       | j                  d        y Nr  )r:  r8  r  s     r   WITH_CLEANUP_FINISHz-InstructionTranslatorBase.WITH_CLEANUP_FINISH  s    		!		$r   c                   | j                         j                         }| j                  |       	 |j                  |       }| j                  |       y # t        t
        j                  f$ r}t        |t
        j                        rt        j                  |        t        j                  dk\  r| j                  t               n| j                          | j                  |       Y d }~y d }~ww xY wNrd  )r  realizer8  next_variableStopIterationr   ObservedUserStopIterationrH  r  rL  rr  rg   r  )r   r   itr^  r  s        r   FOR_ITERz"InstructionTranslatorBase.FOR_ITER  s    XXZ!		"	""4(CIIcNs<<= 	!S::;--d37*
 		01 
IIdOO	s   "A C0-A9C++C0c                l    t        |t        j                  t        f      r|j	                  | g i       }|S r   )rH  r   rf   r   r9  r]  s     r   _create_exception_typez0InstructionTranslatorBase._create_exception_type  s6    )++-NO

 ##D"b1C
r   c                    | j                         } |j                  | d      }t        |t        t        f      sJ t	        j
                  ||      } |j                  | dt        d      |gi        y )Nr  __setattr__)r  r  rH  rh   r   from_frame_summarycall_method)r   r   r  tbnew_tbs        r   _attach_traceback_to_exceptionz8InstructionTranslatorBase._attach_traceback_to_exception  s~    **,S__

 !#45
 	
 
 #55mRHo.7	
r   c                   | j                  |      }t        | j                        rVt        |t        j
                        r<|j                  t        u r*t	        j                  t              j                  | g i       }| j                  |      r:t        |dd       -t        j                  j                  j!                         |_        | j                  |      rT| j$                  j'                  |       t)        j*                  |j                        }t        |dd       } |d| |      t-        dt/        t(              dg t0        j2                         y )Npython_stackraised exception )r#  zFailed to raise exceptionz.Attempted to raise a non-Exception type/value.r  )r  r.   r  rH  r   r   exc_typer  rf   r  r9  _isinstance_exceptionr  r  _guardsr   extract_stackr  r  r_  r   get_dynamo_observed_exceptionr:   r   r   r  )r   r^  observed_exception_typer  s       r   _raise_exception_variablez3InstructionTranslatorBase._raise_exception_variable  s    ))#.
 %3	 ; ;<-++L9GGbRTUC &&s+^T2:$}};;IIKC %%c*33C8&)&G&G&U#"3=L)#C5)l  	/HH1%001		
r   c                "   |j                   dk(  rt        | j                        s(t        d      }t	        j
                  t        | |g       t        | j                        sJ | j                  d   }| j                  |      sJ |       | j                  |       y |j                   dk(  rM| j                  d   }	 | j                  |       | j                  j                         }| j                  |       y | j                         }| j                         }	 | j                  |       | j                  j                         }| j                  |       | j                  |      }|j                  | t        d      |       y # | j                  j                         }| j                  |       w xY w# | j                  j                         }| j                  |       | j                  |      }|j                  | t        d      |       w xY w)Nr   zNo active exception to reraiser  rn  r   	__cause__)r4  r   r  rh   r   r  r  r  r  r  rc  r  r  r  call_setattr)r   r   rR  r^  curr_excfrom_vtcauses          r   rZ  z'InstructionTranslatorBase.RAISE_VARARGS	  s   88q=t(()&'GH,,\4seL t(()))##B'C--c27C72**3/XX]**R.C>..s3  ,,BBD33H= hhjG((*CR..s3  ,,BBD33H=33G<%%d,<[,I5Q  ,,BBD33H=  ,,BBD33H=33G<%%d,<[,I5Qs   <F F4 -F14AHc                    | j                   d   }t        |t              sJ |j                  t        u rt        dddg        y | j                  |       y )Nrn  z CLEANUP_THROW with StopIterationr   zRReceived StopIteration when handling generator.throw/close. This is not supported.r  )r  rH  r   r  r  r:   RERAISEr   r   toss      r   CLEANUP_THROWz'InstructionTranslatorBase.CLEANUP_THROW7	  sN    jjn#0111<<=(:p	 LLr   c                n   t         j                  dk\  ra| j                         }|j                  r"| j                         }| j	                  |       y | j                  |       | j	                  |       y | j                         }| j                         }| j                         }| j	                  |       y )Nr,  )rL  rr  r  r  r  r8  )r   r   r^  r   _exc_tbs         r   r  z!InstructionTranslatorBase.RERAISEE	  s     w&((*C{{HHJ..s3 		#..s388:D((*C((*C**3/r   c                "    t        |t              S r   )rH  r   r]  s     r   r  z/InstructionTranslatorBase._isinstance_exception\	  s    #}--r   c                   g }t         j                  dk\  rt         j                  dk  rdnd}t        | j                        |k\  sJ | j                  |    }| j                  d   }| j	                  |      sJ t        |j                        }|j                  | d      }t         j                  dk\  rt        | j                  d   t              s|j                  | j                  d          nrt        | j                        dk\  sJ | j                  d	   }| j                  d
   }| j	                  |      sJ t        |j                        }|j                  | d      }||||gz  }| j                  ||i        y )Nr,  re           rn  r     ir  )rL  rr  r   r  r  rf   r  r  rH  r   r   r9  )r   r   r   fn_locrD  r^  typr  s           r   WITH_EXCEPT_STARTz+InstructionTranslatorBase.WITH_EXCEPT_START_	  sN   &(w&**W4Q!F tzz?f,,,VG$B**R.C--c222!#,,/CB
 7*!$**R.,?KK

2/tzz?a'''BB**R.C--c222!#,,/C7Bc22tR(r   c           	     	   	 d	d	 fd}t         j                  dk\  rK j                  j                  }|rt	         j
                        |j                  kD  r3 j                          t	         j
                        |j                  kD  r3|j                  r8 j                  t        j                   j                  j                                j                   j                  j                                 j                  |       y  j
                  j!                           j                  j                         } j#                  |       t%               t&        u r |        t	         j(                        r7 j(                  j                         }|j*                  j,                  dk(  rЉ j/                  d        j                  j                          t	         j(                        dk(  rY j
                  j!                          t%               t&        u r,t1        dt3              	dz   g t4        j6                  	        j(                  j                         }|j*                  j,                  dk(  rЉ j                  j                         } j                  j9                          t	         j
                        |j:                  kD  r3 j                          t	         j
                        |j:                  kD  r3t=        t?        d
      dd d      } j(                  jA                  tC        |d t	         j
                                     t	         j                        dk\  rr j                  d   } j                  t        jD                                 j                  |        j                  t        jF                  |jH                               n] j                  t        jJ                          j                  t        jJ                          j                  t        jJ                          j                  t        jD                                 j                  |        j                  t        jF                  |jH                                j                  |       y  j
                  j!                          t%               t&        u r |        )NzDynamo found no exception handler at the top-level compiled function when encountering an exception. Exception will propagate outside the compiled region.c                 :   j                   j                         } t        j                  | j	                               }t        |      sJ t        dd| j                          d| j                   dg t        j                  t        j                         y )NzObserved exceptionr  r   r  r  )r  rc  r   r  python_typerH  r:   python_type_namer   r   r  rE  )r  
dynamo_excobserved_exn_gb_explanationraised_exceptionr   s     r   bubble_exception_to_interpreterzTInstructionTranslatorBase.exception_handler.<locals>.bubble_exception_to_interpreter	  s    ((>>@H::8;O;O;QRJ.
;;;,+H,E,E,G+H(--XYZ7&11&22 *	r   r,  EXCEPT_HANDLERre  r   z#Observed exception (EXCEPT_HANDLER)z  This graph break is unexpected.r  g    .Ar  r  r   )&rL  rr  r  r9  r   r  depthr  lastir8  r   rh   r  r  rc  r  r   r  r  r>  r
  r   r   r:  r:   r   r   r  ra  r"  r-   r   r   r   r   rf   r  rg   )
r   r  r  r9  r  block_stack_entryexception_varexcept_handler_instold_exceptionr  s
   ``       @r   r  z+InstructionTranslatorBase.exception_handler	  s   d 	$
	  w& 44BBM
 $**o(;(;;HHJ $**o(;(;; !&&II!2243K3K3R3RS
 		$++AACD 		-( 

  "  ,,BBD33H=:!6635&&4##$ %)$4$4$8$8$:!',,337GG IIaL%%))+4++,1 

((*:)>>)(M(+,<(=,G"D-E&E(9(D(D&E)9 /.(,(8(8(<(<(>%) (,,337GG, !% 1 1 G G I!!AAC $**o(9(E(EEHHJ $**o(9(E(EE
 '2#c(<LdTU&V#  ''#$7s4::O
 t(()Q.$($5$5b$9M IIi779:IIm,IIi778N8NOP IIi>>?IIi>>?IIi>>? 		)3356		-(		)33M4J4JKL 		+, 

  ":!6635&&r   c                    | j                         }t        | j                        dk(  rt        }n| j                  d   }| j	                  |       | j	                  |       | j                  j                          y )Nr   rn  )r  r   r  rg   r8  ra  )r   r   r^  prev_excs       r   PUSH_EXC_INFOz'InstructionTranslatorBase.PUSH_EXC_INFO
  s`    ( hhjt  !Q&(>H((,H		(		#99;r   c                   t         j                  dk\  rB| j                         }t        | j                        sJ | j                  j                          y t        | j
                        dkD  sJ | j
                  d   j                  j                  dk7  rt        d      | j
                  j                          | j                  d       t        | j                        sJ | j                  j                          y )Nr,  r   rn  r  zYBug in Dynamo tracing of exception handling.Top of the block stack is not EXCEPT_HANDLER.re  )
rL  rr  r  r   r  r
  r   r   r  r:  )r   r   r   s      r   
POP_EXCEPTz$InstructionTranslatorBase.POP_EXCEPT%
  s    w&
At(()))!!#t''(1,,,#((//3CC$D    "IIaL t(()))!!#r   c                   t        | j                        dk\  sJ | j                         }t        j                  dk\  r| j                  d   }n| j                  j                         }t        |t        t        t        t        f      s,t        dt        |      d| dg t        j                         t        j                  dk\  r=| j                  |      s,t        dt        |      d	| dg t        j                         t        |t              r|j                  }n|g}|D ]  }t        |t        t        t        f      s,t        d
t        |      d| dg t        j                         | j                  |      r"t!        |j"                  |j$                        r yt        |t&        j                        st!        |j$                  |j$                        s y y)Nr  r,  rn  z Exception with bad expected typez"`except ...` has unsupported type rG  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  rL  rr  rH  rf   r}   r   r   r:   r   r   r  r  r   
issubclassr  rD  r   )r   expected_exc_typesexc_instanceexpected_typesexpected_types        r   check_if_exc_matchesz.InstructionTranslatorBase.check_if_exc_matches:
  s   4::!###!XXZw&  ::b>L
  ::>>+L 12	
 :./@AS@TTUV5)445	 w&--l;8-"efresst u9-889	 (-8/55N #N , 	M#65 A."CM?RS T9-889	 )),7J%%  = L)*C*CD  J
 3	6 r   c                h    | j                  t        j                  | j                                      y r   )r8  r   rh   r  r  s     r   CHECK_EXC_MATCHz)InstructionTranslatorBase.CHECK_EXC_MATCH
  s"    		),,T-F-F-HIJr   c                H    | j                         s| j                  |       y y r   )r  r  r  s     r   JUMP_IF_NOT_EXC_MATCHz/InstructionTranslatorBase.JUMP_IF_NOT_EXC_MATCH
  s    ((*IIdO +r   c                    |j                   dk(  r| j                  |       y | j                  t        |j                      | | j	                  d      i              y )Nzexception matchr  )r  r  r8  r   r:  r  s     r   
COMPARE_OPz$InstructionTranslatorBase.COMPARE_OP
  sD    ;;++  &II)$++6tTYYq\2NOr   c                b    | j                  t        t              | j                         gi        y r   )r9  rf   iterr  r  s     r   GET_ITERz"InstructionTranslatorBase.GET_ITER
  s!    ?40488:,Cr   zjEncountered graph break when attempting to trace CALL_FUNCTION: a call to a regular function, e.g. f(x, y))r8  r)  c                    | j                  |j                        }| j                         }| j                  ||i        y r   r:  r  r  r9  )r   r   r   rD  s       r   CALL_FUNCTIONz'InstructionTranslatorBase.CALL_FUNCTION
  s3    
 yy%XXZ2tR(r   zjEncountered graph break when attempting to trace CALL_FUNCTION_EX: a variadic function call, e.g. f(*args)c           	     v   |j                   dk(  rt        i       }| j                         }n|j                   dk(  st        j                  dk\  r<| j                         }t        |t              rt        i       }| j                         }n9t        dd|j                    d|j                    g t        j                         t        j                  dk\  r"| j                         }t        |t              sJ | j                         }t        j                  d	k\  r5t        j                  dk  r"| j                         }t        |t              sJ t        t              s+|j                  |       rt        |j                  |             }t        t              rt        j                   | t"        |      }t        |t              rt        |t              s7t        d
dt%        |       dt%        |       dg t        j&                         |j)                         }| j+                  ||j,                  |       y )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)r  rm   r  rL  rr  rH  r   r:   r   r  rx   has_force_unpack_var_sequencer}   force_unpack_var_sequencer   rf   call_custom_dictr   r`   r  keys_as_python_constantr9  r   )r   r   
kwargsvarsargsvarsnullrD  s         r   CALL_FUNCTION_EXz*InstructionTranslatorBase.CALL_FUNCTION_EX
  s    ;;!*2.JxxzH[[A!1!1W!<J*l3.r2
xxzH?!$++/fgkgrgrfst5)445	 w&88:DdL111XXZw&3+;+;g+E88:DdL111

 44T:$X%G%G%MNH j";<(99$jQJ ($45Z>

 J%gh&7%8PZH[G\]P5)445  779
2x~~z:r   zyEncountered graph break when attempting to trace CALL_FUNCTION_KW: a function call with keyword arguments, e.g. f(x=True)c                   | j                         }| j                  |j                        }| j                         }t        |t              r|j                         sJ |j                         }|d t        |        |t        |       d  }}t        t        ||            }t        |      t        |      k(  sJ | j                  |||       y r   )r  r:  r  rH  r}   r  r  r   r   zipr9  )r   r   argnamesr   rD  kwargs_listr  s          r   CALL_FUNCTION_KWz*InstructionTranslatorBase.CALL_FUNCTION_KW
  s     88:yy%XXZ(M2x7R7R7TTT..0 !1CM>2D#h-9I4Jkc(K016{c(m+++2tV,r   c                (   | j                  t        j                  |d             |j                  d   }| j                  d   |   }t
        j                  dk  r| j                  |       y | j                  t        j                  ||             y )Nr  r1  r   co_namesr,  )	r   r   r*  r  r  rL  rr  r  LOAD_METHODr   r   r4  r  s       r   LOAD_METHOD_SUPERz+InstructionTranslatorBase.LOAD_METHOD_SUPER
  st    ;..tA>?kk!n"":.s3g%OOF#[00fEFr   c                    | j                  t        j                  |d             |j                  d   }| j                  d   |   }| j                  |       y )Nr  r1  r   r  )r   r   r*  r  r  r  r  s       r   LOAD_ATTR_SUPERz)InstructionTranslatorBase.LOAD_ATTR_SUPER  sK    ;..tA>?kk!n"":.s3r   c                v   | j                  |j                         | j                         }t        j                  dk\  r#| j                  |       | j                  |       y t        j                  dk\  r#| j                  |       | j                  |       y | j                  |       | j                  d        y )Nr  r,  )r  r  r  rL  rr  r8  rQ  r   r   objs      r   r  z%InstructionTranslatorBase.LOAD_METHOD	  s    $hhjw&IIcNNN4 ( NN4 IIcNIIcNIIdOr   c                    | j                  |j                        }| j                         }|J | j                         }| j                  ||i        y r   r  )r   r   r   dummyrD  s        r   CALL_METHODz%InstructionTranslatorBase.CALL_METHOD  sF    yy%
}}XXZ2tR(r   c                    | j                         }t        t              j                  | |t	        j
                  |      gi       }| j                  |       y r   )r  rf   r  r9  rh   r  r8  )r   attrr  rw  s       r   r  z$InstructionTranslatorBase._load_attr   sJ    hhj )77"))$/0

 			&r   c                    t         j                  dk\  r!|j                  dz  r| j                  |       y | j	                  |j
                         y )Nrd  r  )rL  rr  r4  r  r  r  r  s     r   	LOAD_ATTRz#InstructionTranslatorBase.LOAD_ATTR)  s<    w&xx!|  &$r   zkEncountered graph break when attempting to trace STORE_ATTR: storing an object's attribute, e.g. x.attr = yc                    | j                  d      \  }}t        t              j                  | |t	        j
                  |j                        |gi        y r  )r:  rf   setattrr9  rh   r  r  )r   r   r^  r  s       r   
STORE_ATTRz$InstructionTranslatorBase.STORE_ATTR1  sH    
 99Q<S .."))$++6<	
r   c                    | j                         }t        t              j                  | |t	        j
                  |j                        gi        y r   )r  rf   delattrr9  rh   r  r  r  s      r   DELETE_ATTRz%InstructionTranslatorBase.DELETE_ATTR=  s>    hhj .."))$++67	
r   c                   g }|dk  sJ |dk(  r|j                  t        d             | j                  dk(  rt        d      nt        d| j                        }|j                  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   re  r  r  r1  r  )extendr+   r   r(   r  )r   r  r_  return_insts       r   codegen_return_with_popsz2InstructionTranslatorBase.codegen_return_with_popsE  s      A~~>LLQ( {{n, ~.#N4;;G 	
 		*,>y,I;W	
 r   c                    |rt        |j                  |j                        D ]  \  \  }}	}
t        t         j
                  |
         }|j                  t                      |j                  |       |j                  g t        d      |j                  |      |j                         |j                  |      t        d              |j                  D ]  \  }}	t        t         j                  |         }|j                  t                      |j                  |       |j                  g t        d      |j                  |      |j                         |j                  |j                   |j"                  |   z         t        d              t%        |      r|j&                  sJ |j&                  }t)        d|j*                         }|rlt-         j.                  |      t1         fd j                  D              }t3        |j4                        t1        fd|D              }t1        fd|D              }|j                  t               |j                  |      |j                         t               g       |D ]`  }|j                  t               |j                  |j                   |j"                  |   z         |j                         gt        d             b |j                  t        d      t        dt7        |      	      gt        d      t9        |j                   d
d             n8t1        |j"                  j;                               }t1        |j4                        }t<        j>                  dk  rt7        |      dk(  sJ d       t7         j
                        t7        |j@                        z
  } jB                  j*                  J tE        jF                   jH                   jJ                   jB                  j*                  |j*                  t1        d  jL                  D              |||t1        d  jL                  D              |t1        |j                        t1        |j                        t1        |j@                        t1        |       jN                         } tQ        jR                   jH                        jU                  dd              }|+tW        jX                  |      tQ        jR                  |      d<   |jZ                  r j\                  j_                  ||       d
}n= j\                  j_                  |ta        jb                  | jd                  |             |} jf                  * jf                  ji                  | jd                  d   |       tj        d   |jl                  xx   dz  cc<   ||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  N   K   | ]  }|v r|j                         vr|  y wr   r  )r   r   r  r   s     r   r   z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>  s0      !:!4+A+A+C"C !s   "%c              3  ,   K   | ]  }|vs|  y wr   r   r   r   argnames_null_sets     r   r   z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>  s     S1AR8RQS   	c              3  ,   K   | ]  }|v s|  y wr   r   r/  s     r   r   z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>  s     !TQBS=S!!Tr1  r  rp  r  NTrd  r   z&variables should not be NULL in < 3.12c              3  H   K   | ]  }|j                   j                    y wr   )r!  r  r   r  s     r   r   z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>  s     <a!((//<s    "c              3  <   K   | ]  }|j                           y wr   )r*  r4  s     r   r   z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>  s     :A!++-:r  orig_graphmodulec                      y r   r   r   r   r   r   z9InstructionTranslatorBase.create_resume.<locals>.<lambda>      r   r   resumesr   )7r  stack_ctx_argsstack_ctx_idxes_origr   ri   r  append_outputr'   r  r  r+   r  r  r(   locals_ctx_argsr|  r  r  r/   r!  r0   r  r    r  r)  r  locals_null_keysr   r#   keysrL  rr  stack_null_idxesr  rI   lookupr  r   r
  r  r1   get_contextrK  weakrefrefr  r  install_global_unsaferI  FunctionTyperA  r  add_resume_functionrX   r  )r   r  resume_instmetaresume_codesr  is_leafhandle_inactive_ctxjr   j_origrj  r   resume_nameall_argnamesr  argnames_nullr4  	stack_lennew_codeorig_graphmodule_maybepackage_namer0  r  s   `                     @@r   r  z'InstructionTranslatorBase.create_resumee  sl   T "%d&9&94;T;T"U A2DJJv4FG  !12$$R(  $Q,,S1 //1 ,,Q/	
 +>:   // a2D4H4H4NO  !12$$R(  $Q,,S1 //1 ,,T^^d>O>OPT>U-UV	
 +>:( K(%%%%%,,K,{/A/A.B CD %d&7&7EE  !--! L
 !$D$9$9 :SSSH!!T\!TTM "$((-++-"$	   	  &(,,T^^d>O>OPS>T-TU//1 %Q		 &y1&|XG !^
 )tD	 T..3356H!$"7"78Mg%}%*T,TT* 

Oc$*?*?&@@	''..:::#9#@#@KKKK$$++<4+;+;<<:)9)9::$%%&$&&'$''(,---!$
*"
!9!9$++!F!J!J"
 " "-EL[[&FL$$X./AB
 KK--k8DL KK--""8T^^[I 'L<<#LL,,$..4l 	H,,-2-$$r   c           
        d| _         t        | j                  j                        }g }g }g }| }d}|i|| u r|}	n|j                  }	|	j
                  dk7  r3|j                  |       |j                  |       |j                  |	       |j                  }|dz  }|it        | j                        t        |d   j                        z
  }
|s{|
dk\  sJ |j                  t        |
dz                t        |
dz         D ]  }|j                  t        d              |j                  t        d             |j!                         S |d   | u r)|j                  t        d|
             d}|
|d   _        n|j                  t        |
             t        |
dz
        D ]  }|j                  t        d              |j                  t        dd             ||d      j"                  }||d      xj"                  dz  c_        |d   j%                  t'                      |j                  g t)        d      |j+                  |d         |j-                         t/        ||d	             g }|D ]F  }|j1                  t3               |j+                  |      |j-                         gt        d             H |j1                  t        d      t        dt        |            g       |j                  |       |j                  g t        d      t5        j6                  |      t        d             g }g }t9        |      D ]L  \  }}|j;                  |||   |||      |||| u d	      \  }}|j                  |       |j                  |       N | j=                  |||       |j                  t        d             |j!                         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   r  r   r  r  rp  r  T)r   r2   r  r6  r  r   r   r	  r   r  r@  r  r+   rj  r<  r(   r\  r  r8  r   r&   r  r  r#   r'  r'   r8  deepcopyr]  r  r  )r   r   r  r  txesidxesresume_instsr  r  rH  current_num_stackr   stack_insert_idxfilter_instsrJ  resume_namesrY  resume_coderO  s                      r   r  z/InstructionTranslatorBase.create_call_resume_at(  s   6 $( t{{**+ 13*,6: ~"$55!!^3F#S!##K0]]F1HC    

Oc%a(99/
 

 
 %)))[):Q)>?@,q01 @  !3I!>?@/?@&&(( 7d? /BSTU 5F%a(2
 [):;<,q01 @  !3I!>?@/!DE8qBLL%eAh/99Q>9GLL*+ 	Q $$U1X. '')	
 %%57GN
	
  	C"$((-++- !^		 	"9-"<SZ@	
 	& 	Q|, Q	
 .0"4 	-IAv'-';';Q)%(3$($K ,,	- 	  |R@
+N;<""$$r   c           	     H   |j                  t        d             t        t        ||             D ]  \  }\  }}|t	        |      dz
  k(  r n|j
                  rL|j                  t               |j                  |      |j                         g       |j                  ||       n"|j                  |j                  |dd             |j                  t        d              |j                  t        d      t        dt	        |       dz
        g       |j                  t        d             | d	   j
                  re|j                  |j                  d	      |j                         g       |j                  |d	   | d	          |j                  g t        d             n;|j                  t        d      g|j                  |d	   d      t        d             |j                  t               t               |j                  d	      |j                         gt        d      |j                  d	      t        d
             |j                  g t        d      t        dd      t        d      t        dd             |j                  t        dd             y)a  
        Calls the provided resume functions.

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

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

        Args:
            - resume_codes: list of resume function code objects to call
            - resume_names: list of the corresponding names of the resume functions
            - cg: PyCodegen object to output instructions to
        r  r   Fr   r  rp  r  re  rn  r  LIST_EXTENDTN)r  r&   r]  r  r   r  r'   r  r  make_function_with_closureload_function_namer+   r(   r*   r%   )rJ  r^  r  rY  r   codes         r   r  z-InstructionTranslatorBase.codegen_call_resume  s   4 	Q((\<)HI 	-OA|dC%))  &(,,Q///1 --dD9  !6!6tUA!FG[^,	-  	"9-"<S5F5JK	
 	Q(''((,++- )),r*:L<LM!!_ &y1**<+;UC "!_( 	  $$R('') Q $$R( #?3	
  	a"<Q7 Q
 #=a8	
 	0=>r   c                   t         j                  dk\  rJ| j                  j                  }|r2| j                  r%|j
                  | j                  d   j
                  uryt        d | j                  D              xrl | j                   xr] | j                  xs | j                   xr@ | j                   xr1 | j                   xr" | j                  j                  j                  d u S )Nr,  rn  Fc              3  <   K   | ]  }|j                           y wr   r%  r4  s     r   r   zIInstructionTranslatorBase.should_compile_partial_graph.<locals>.<genexpr>N       :A:r  )rL  rr  r  r9  r
  r!  r  r  r  r   r  r  r  current_tracerr	  )r   r   s     r   r  z6InstructionTranslatorBase.should_compile_partial_graphE  s    w&,,::E$$D<L<LR<P<W<W(W:)9)9:: :NN": ,,MD4M4M0M: 333	:
 888: **11T9		
r   ziEncountered graph break when attempting to trace STORE_SUBSCR: trying to store subscript, e.g. x[key] = yc                Z    | j                  d      \  }}}|j                  | d||gi        y )Nre  __setitem__r:  r  )r   r   r^  r  keys        r   r  z&InstructionTranslatorBase.STORE_SUBSCRX  s-    
 		!S#mc3Z<r   c                V    | j                  d      \  }}|j                  | d|gi        y )Nr  __delitem__rl  )r   r   r  rm  s       r   r  z'InstructionTranslatorBase.DELETE_SUBSCR`  s'    99Q<SmcUB7r   c                n    | j                  |j                        }| j                  t        |             y r   )r:  r  r8  r}   r   r   r   s      r   BUILD_TUPLEz%InstructionTranslatorBase.BUILD_TUPLEd  s%    		$++&		-&'r   c                r    | j                  |j                        }| j                  t        ||              y )N)r   )r:  r  r8  r|   rq  s      r   BUILD_SLICEz%InstructionTranslatorBase.BUILD_SLICEh  s'    		$++&		-$/0r   c                     y)zCheck if comprehension speculation is allowed in nested context.

        For the base class (non-inlined), this always returns False.
        Fr   r   s    r   #_can_speculate_comprehension_nestedz=InstructionTranslatorBase._can_speculate_comprehension_nestedl  s    
 r   c                   t         j                  dk\  r|j                  dk(  sy| j                         syt	        d | j
                  D              xr^ | j                   xrO | j                   xr@ | j                   xr1 | j                   xr" | j                  j                  j                  du }|r| j                  | j                         }|rI| j                  dk(  r:| j                         }|j!                  |       r| j#                  |       y|| _        | j'                         }|dk\  sJ | j(                  j+                  |       | xj                  dz  c_        y)z
        Handle comprehension start for Python 3.12+ BUILD_LIST/BUILD_MAP with argval 0.
        Returns True if a graph break was triggered and the caller should return early.
        rd  r   Fc              3  <   K   | ]  }|j                           y wr   rg  r4  s     r   r   zSInstructionTranslatorBase._maybe_setup_comprehension_speculation.<locals>.<genexpr>  rh  r  NTr   )rL  rr  r  _is_comprehension_startr  r
  r  r   r  r  r  ri  r	  rv  _comprehension_depthr  r   !_handle_comprehension_graph_breakr  _find_comprehension_end_for_ip_comprehension_end_for_ipsr  )r   r   can_speculater%  
end_for_ips        r   &_maybe_setup_comprehension_speculationz@InstructionTranslatorBase._maybe_setup_comprehension_speculations  sP   
   G+q0@++- :)9)9:: :NN":---: 333: 888	:
 **11T9 	 T[[4 DDFMT66!;..*K!!$'66t<'2D$88:
Q''++J7!!Q&!r   c                    | j                  |      ry | j                  |j                        }| j                  t	        |t                            y Nmutation_type)r  r:  r  r8  r{   ra   rq  s      r   rp  z$InstructionTranslatorBase.BUILD_LIST  s<    66t<		$++&		,u4D4FGHr   c                    t         j                  rt        dddg        | j                  |j                        }t        |t                     }| j                  |       y )Nzmissing BUILD_SET handlerr   z:Missing BUILD_SET bytecode handler (for testing purposes).r  r  )r   +inject_BUILD_SET_unimplemented_TESTING_ONLYr:   r:  r  rn   ra   r8  )r   r   r   new_sets       r   	BUILD_SETz#InstructionTranslatorBase.BUILD_SET  sO    ==3X	 		$++&e3C3EF		'r   c           	     D   | j                  |j                        }g }|D ]#  }	 |j                  |j                  |              % | j                   ||t                            y # t        $ r. t        dt        |      | dg t        j                         Y ~w xY w)Nz-Failed to unpack object for BUILD_LIST_UNPACKzU cannot be unpacked into a list for the BUILD_LIST_UNPACK bytecode (`[*x, *y, ...]`).r  r  )r:  r  r'  r  NotImplementedErrorr:   r   r   r  r8  ra   )r   r   r  seqsr   seqs         r   BUILD_LIST_UNPACKz+InstructionTranslatorBase.BUILD_LIST_UNPACK  s    yy% 
	C	S::4@A
	 			#e+;+=>? ' KH#&% (2 !29-889s    A((4BBc                2    | j                  |t               y )Nr  )r  r}   r  s     r   BUILD_TUPLE_UNPACKz,InstructionTranslatorBase.BUILD_TUPLE_UNPACK  s    t7r   c           	         | j                  |      ry | j                  |j                  dz        }t        t	        |d d d   |dd d               }| j                  t        |t                            y )Nr  r   r  )r  r:  r  r   r  r8  rm   ra   )r   r   r   ds       r   	BUILD_MAPz#InstructionTranslatorBase.BUILD_MAP  sd    66t<		$++/*U3Q3Zqt!t-.		#A5E5GHIr   c                T   | j                  |j                        }|D cg c]#  }t        t              j	                  | |gi       % }}i }|D ]/  }t        |t              sJ |j                  |j                         1 | j                  t        |t                            y c c}w r  )r:  r  rf   r   r9  rH  rm   updater   r8  ra   )r   r   r   rT  rw  s        r   BUILD_MAP_UNPACKz*InstructionTranslatorBase.BUILD_MAP_UNPACK  s    		$++&MRS&44TA3CSS!# 	#Aa!2333MM!''"	# 			.0	
 Ts   (B%c           
     d   | j                         }| j                  |j                        }t        |t              sJ |j                         sJ |j                  |       }t        |      t        |      k(  sJ | j                  t        t        t        ||            t                            y r  )r  r:  r  rH  r}   r  r  r   r8  rm   r   r  ra   )r   r   r?  r  s       r   BUILD_CONST_KEY_MAPz-InstructionTranslatorBase.BUILD_CONST_KEY_MAP  s    xxz4;;'$...&&(((--d34yCK'''		Sv&'.0	
r   c                
   | j                  d      \  }}|j                  dkD  sJ |j                  J | j                  |j                      j	                         }t        |t              sJ |j                  | d||fi        y )Nr  r   rk  )r:  r  r4  r  r  rH  rm   r  )r   r   r   r   r  s        r   MAP_ADDz!InstructionTranslatorBase.MAP_ADD  sw    yy|1{{Qxx###jj$((#++-#0111maVR8r   c                   | j                         }|j                  dkD  sJ |j                  J | j                  |j                      }t	        |t
              sJ |j                         sJ |j                  | d|gi        y )Nr   r  r  r  r4  r  rH  rn   
is_mutabler  r   r   r   r  s       r   SET_ADDz!InstructionTranslatorBase.SET_ADD  su    HHJ{{Qxx###jj$((##{+++~~eaS"-r   c                   | j                         }|j                  dkD  sJ |j                  J | j                  |j                      }t	        |t
              sJ |j                         sJ |j                  | d|gi        y Nr   r  r  r  s       r   
SET_UPDATEz$InstructionTranslatorBase.SET_UPDATE  su    HHJ{{Qxx###jj$((##{+++~~hR0r   c                z   | j                         }|j                  dkD  sJ |j                  J | j                  |j                      j	                         }t        |t              sJ |j                         sJ | j                  j                  j                  |       |j                  j                  |       y r   )r  r  r4  r  r  rH  r{   r  r  r.  mutationr   r   r  s       r   r  z%InstructionTranslatorBase.LIST_APPEND  s    HHJ{{Qxx###jj$((#++-#|,,,~~  ))#.		r   c                b   |j                   }t        j                  dk  r| j                         }| j                         }t        j                  dk\  rBt	        |j
                  d      sJ t        j                  |j
                  j                        }d }d }d }d }t        j                  dk  rV|T|dz  r| j                         }|dz  r| j                         }|dz  r| j                         }|dz  r| j                         }| j                  t        || j                  ||||             y )	Nr,  co_qualnamer  r     r  r  r   )r4  rL  rr  r  r(  r  rh   r  r  r8  rr   rA  )	r   r   flagsfn_namerd  defaultsclosurer   
kwdefaultss	            r   MAKE_FUNCTIONz'InstructionTranslatorBase.MAKE_FUNCTION  s
   g%hhjGxxzw& 4::}555&--DJJ4J4JKG
g% 4<"hhjG4<"&((*K4<!%J4<#xxzH		&
	
r   c           	     0   | j                         }|j                         r'|j                  | t        |j                              }nt        |t              rx|j                  j                         r^t        |j                  j                         |j                        }t        |j                        D cg c]  }t        | ||          }}nN|j                  |       r|j                  |       }n+t        dt        |      | dg t         j"                         t%              |j                  k7  r;t        dd|j                   dt%        |       | dg t         j&                         t)        |      D ]  }| j+                  |        y c c}w )	N)rY  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  rj  r  rH  r   r  r  as_proxyr   re   r  r  r:   r   r   r  r   r  r   r8  )r   r   r  r^  proxyrY  s         r   r  z)InstructionTranslatorBase.UNPACK_SEQUENCE2  sX   hhj==?))$eDKK6H)IC_-#''2C2C2ECGG,,.9E:?:LMQ=uQx0MCM..t4//5CEC"e $( (5)445 s8t{{"S+DKK=
3s8*M"e $? ?5)445 # 	AIIaL	- Ns   7Fc                n   d|j                   cxk  rdk  sJ  J |j                   dz  }|j                   dz	  }| j                         }|j                  |       rt        |j	                  |             }t        |      ||z   k\  sJ |d | }||t        |      |z
   }|t        |      |z
  d  }t        |      D ]  }	| j                  |	        | j                  t        |             t        |      D ]  }	| j                  |	        y t        dt        |      | dg t        j                         y )Nr   i     r  z%Failed to unpack object for UNPACK_EXz; cannot be unpacked into a list for the UNPACK_EX bytecode.r  )r  r  r  r   r  r   r   r8  r}   r:   r   r   r  )
r   r   prefixsuffixr  r  vals_prefix	vals_listvals_suffixitems
             r   	UNPACK_EXz#InstructionTranslatorBase.UNPACK_EXR  s2   DKK)6)))))t#!hhj,,T255d;<Dt9///w-KVc$i&&89Is4y6134K -  		$ IImI./ -  		$  ?C"e#^_5)445	r   z-Encountered intentional debugging graph breakc                >    | j                   rt        ddddg       y y )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  )r  r:   r  s     r   graph_break_on_leaf_functionz6InstructionTranslatorBase.graph_break_on_leaf_functionj  s0     $$=6 ^ %r   c                F    |j                   dk(  r| j                  |       y y )NGRAPH_BREAK_IF_LEAF)r  r  r  s     r   r  zInstructionTranslatorBase.NOPy  s"    ;;//--d3 0r   c                $    | j                          y r   r  r  s     r   r  z!InstructionTranslatorBase.POP_TOP~      
r   c                    | j                         }| j                         }| j                  |       | j                  |       y r   r  r8  r   r   ar  s       r   ROT_TWOz!InstructionTranslatorBase.ROT_TWO  s.    HHJHHJ		!		!r   c                    | j                         }| j                         }| j                         }| j                  |       | j                  |       | j                  |       y r   r  )r   r   r  r  cs        r   	ROT_THREEz#InstructionTranslatorBase.ROT_THREE  sD    HHJHHJHHJ		!		!		!r   c                   | j                         }| j                         }| j                         }| j                         }| j                  |       | j                  |       | j                  |       | j                  |       y r   r  )r   r   r  r  r  r  s         r   ROT_FOURz"InstructionTranslatorBase.ROT_FOUR  sZ    HHJHHJHHJHHJ		!		!		!		!r   c                h    | j                         }| j                  |       | j                  |       y r   r  )r   r   r  s      r   r  z!InstructionTranslatorBase.DUP_TOP  s#    HHJ		!		!r   c                    | j                         }| j                         }| j                  |       | j                  |       | j                  |       | j                  |       y r   r  r  s       r   DUP_TOP_TWOz%InstructionTranslatorBase.DUP_TOP_TWO  sD    HHJHHJ		!		!		!		!r   c                    |dk(  r!t        t              j                  | |gi       S |dk(  r!t        t              j                  | |gi       S |dk(  r!t        t              j                  | |gi       S |S )Nr   r  re  )rf   r   r9  r  ascii)r   r  flags      r   _convert_valuez(InstructionTranslatorBase._convert_value  sp    19"3'55dUGRHHQY"4(66teWbIIQY"5)77ugrJJr   c                   | j                         }t        |t              r?ddlm}m}  |j                   |||      |j                        }| j                  |       y | j                  ||dz        }t        j                  d|j                         z   dz         }| j                  t        t        j                        ||gi        y )Nr   )LazySymNodeFormatStringrw   ry  re  z{:})r  rH  r   torch._dynamo.variables.lazyr  rw   r  r  r8  r  rh   r  r9  rf   r   format)r   fmt_specr  r  r  rw   fmt_vars          r   _format_valuez'InstructionTranslatorBase._format_value  s    
e_-
 /'..'x8E IIe##E54<8"))$1L1L1N*NQT*TU?3::6%8H"Mr   c                    |j                   }|J |dz  dk(  r| j                         }nt        j                  d      }| j	                  ||      S )Nr  r   )r4  r  rh   r  r  )r   r   r  r  s       r   FORMAT_VALUEz&InstructionTranslatorBase.FORMAT_VALUE  sQ       DLT!xxzH'..r2H!!(E22r   c           
     \   g }g }i }|j                   J | j                  |j                         D ]:  }|j                         r#|j                  d       |j                  |       7t	        |t
        j                        r|j                  |j                         |j                  |j                         t        |j                               t        |j                  j                               z  r2t        dd| d| d|j                   dg t        j                         |j!                  |j                         t        dt#        |      d	g t        j                         = | j%                  t
        j                  j'                  d
j)                  |      ||             y )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   )r4  r:  r  r   rH  r   StringFormatVariableformat_stringr'  sym_argsr  r?  
sym_kwargsr:   r   r  r  r   r8  r  r   )r   r   format_string_partsr   r  parts         r   BUILD_STRINGz&InstructionTranslatorBase.BUILD_STRING  su   )+&(-/xx###IIdhh' 	D&&(#**40D!D)"@"@A#**4+=+=>DMM*v{{}%DOO,@,@,B(CC! ;"78K7LJW]V^^qrv  sB  sB  rC  !D$W= 1 < <=	 doo.5I n9-889	!	, 			**11+,dF	
r   c                    |j                   dk(  s|j                   dk(  sJ |j                   dk(  rd}nd}t        d|      }| j                  |       y )Nr   r   iszis notr  r1  )r  r(   r  )r   r   
new_argvalnew_insts       r   IS_OPzInstructionTranslatorBase.IS_OP  sM    {{a4;;!#333;;!J!J%l:F!r   c           	        |j                   dk(  s|j                   dk(  sJ | j                  d      \  }}|j                   }	 | j                  |j                  | d|gi              |dk(  r| j                  |       y y # t        j
                  t        f$ rs}t        |t              r|j                  r |j                          | j                  | j                  t        j                  | t              ||gi              Y d }~d }~ww xY w)Nr   r   r  __contains__)r  r:  r8  r  r   ObservedTypeErrorr;   rH  r!  r  r  rb   rG  rB   	UNARY_NOT)r   r   leftrightrO  r&  s         r   CONTAINS_OPz%InstructionTranslatorBase.CONTAINS_OP  s    {{a4;;!#333iile[[	IIe''ntfbIJ* 7NN4  % !! 
 	 $,??&&(II00#))$0IJ5M 	s   $A> >D
A)DD
c                   | j                         }|j                  dkD  sJ |j                  J | j                  |j                      }t	        |t
              sJ |j                         sJ |j                  | d|gi        y )Nr   r'  )r  r  r4  r  rH  r{   r  r  r  s       r   ra  z%InstructionTranslatorBase.LIST_EXTEND  su    HHJ{{Qxx###jj$((##|,,,~~hR0r   c                    | j                  t        t              j                  | | j	                         gi              y r   )r8  rf   r)  r9  r  r  s     r   LIST_TO_TUPLEz'InstructionTranslatorBase.LIST_TO_TUPLE  s*    		/%(66tdhhj\2NOr   c                d   | j                   d   }| j                  |      sJ |j                  t        u r|t	        j
                  t              j                  | t        d      gi       }|j                  | t        d      |       |j                  | t        d      |       || j                   d<   y y )Nrn  zgenerator raised StopIterationrf  r  )
r  r  r  r  r   rf   r  r9  rh   r  )r   r   r^  new_vals       r   STOPITERATION_ERRORz-InstructionTranslatorBase.STOPITERATION_ERROR   s     jjn))#...<<=(//=KK!"BCDG
   '7'FL  '7'DcJ$DJJrN )r   c                $   | j                         }|j                  dkD  sJ |j                  J | j                  |j                      j	                         }t        |t              sJ |j                         sJ |j                  | d|gi        y r  )	r  r  r4  r  r  rH  rm   r  r  r  s       r   
DICT_MERGEz$InstructionTranslatorBase.DICT_MERGE2  s    HHJ{{Qxx###jj$((#++-#0111~~hR0r   c                $    | j                          y r   r  r  s     r   	GEN_STARTz#InstructionTranslatorBase.GEN_START=  r  r   c                    | j                   d   }|j                         r<| j                  t        j                  t        |j                                            y | j                  |j                  | dg i              y )Nrn  r  )r  r  r8  rh   r  r   r  r  r  s      r   GET_LENz!InstructionTranslatorBase.GET_LEN@  s\    jjn!!#II&--c#2H2H2J.KLMIIcoodIr2>?r   c                    | j                   d   }| j                  | j                  t        j                  | t
              |gi              y)zr
        If STACK[-1] is an instance of collections.abc.Mapping, push True.
        Otherwise, push False
        rn  N)r  r8  r  rb   rG  rC   r  s      r   MATCH_MAPPINGz'InstructionTranslatorBase.MATCH_MAPPINGG  sC    
 jjn		,,%%dO<	
r   c                    | j                   d   }| j                  | j                  t        j                  | t
              |gi              y Nrn  )r  r8  r  rb   rG  rF   r  s      r   MATCH_SEQUENCEz(InstructionTranslatorBase.MATCH_SEQUENCEU  sB    jjn		,,%%d,?@	
r   c           	        | j                  d      \  }}}t        j                  |j                        }| j	                  | j                  t        j                  | t              ||||gi              t        j                  dk  rC| j                  d   }| j	                  t        j                  t        |t                            y y )Nre  r,  rn  )r:  rh   r  r4  r8  r  rb   rG  rD   rL  rr  r  r]   )r   r   subjectr  namesr4  r  s          r   MATCH_CLASSz%InstructionTranslatorBase.MATCH_CLASS_  s    "iile%%dhh/		,,%%d,<=#sE*	
 g%**R.CII&--&>N2O.OPQ &r   c                   | j                   d   }| j                   d   }t        |t              sJ | j                  | j	                  t        j                  | t              ||gi              t        j                  dk  rC| j                   d   }| j                  t        j                  t        |t                            y y )Nrn  r  r,  )r  rH  r}   r8  r  rb   rG  rE   rL  rr  rh   r  r]   )r   r   r?  r  r  s        r   
MATCH_KEYSz$InstructionTranslatorBase.MATCH_KEYSo  s    zz"~jjn$...		,,%%dO<sDk2	
 g%**R.CII&--&>N2O.OPQ &r   c                D    | j                  | j                  d             y )Nr  r8  r  r  s     r   LOAD_ASSERTION_ERRORz.InstructionTranslatorBase.LOAD_ASSERTION_ERROR  s    		$//0@ABr   c                D    | j                  | j                  d             y )N__build_class__r  r  s     r   LOAD_BUILD_CLASSz*InstructionTranslatorBase.LOAD_BUILD_CLASS  s    		$//0ABCr   z`Encountered graph break when attempting to trace BINARY_SUBSCR: a binary subscript, e.g. x[attr]c                p    |j                   dk(  r| j                  |       d| _        y | j                  rJ y )Nr   F)r4  append_prefix_instr  r  s     r   RESUMEz InstructionTranslatorBase.RESUME  s5    88q=##D)&+D#.....r   c                P    |j                   J t        |j                      | |      S r   )r4  _binary_op_lookupr  s     r   	BINARY_OPz#InstructionTranslatorBase.BINARY_OP  s(    88'''$TXX.tT::r   c                     y r   r   r  s     r   r/  z!InstructionTranslatorBase.PRECALL      r   c                    | j                   d   |j                     }t        |t              sJ |D ]  }t        |t              rJ  | j
                  J t        j                  |      | _        y )N	co_constsr  )r  r4  rH  r)  r   r7  rh   r  )r   r   r7  r   s       r   r0  z"InstructionTranslatorBase.KW_NAMES  sl    $$[1$((;(E*** 	)DdC(((	)}}$$$(//h?r   c                6    | j                  t                      y r   )r8  r   r  s     r   rQ  z#InstructionTranslatorBase.PUSH_NULL  s    		,.!r   c                   |rXt         j                  dk\  sJ | j                         }t        |t              r|j                         sJ |j                         }n$| j                  r| j                  j                  nd}|j                  J | j                  |j                  dz         }t         j                  dk\  r!|d   }t        |d   t              rg n|d   g}n&t        |d   t              r|d   }g }n|d   }|d   g}|rO||dt        |        z   }|t        |       d  }t        t        ||            }t        |      t        |      k(  sJ ||dd  z   }i }	 | j                  |||       d | _        y # d | _        w xY w)Nr  r   r  r   r   )rL  rr  r  rH  r}   r  r  r7  r  r4  r:  r   r   r   r  r9  )	r   r   call_kwr7  contentsrD  r   r  r  s	            r   _callzInstructionTranslatorBase._call  s~    ##w...xxzHh68;V;V;XXX224H.2mmt}}**Hxx###99TXX\*w&!B#HQK>2Xa[MD(1+|4a[a[ }(1H~66D"CM>#34K#h45Fv;#h-///(12,&DF	! r40 DMDDMs   !E< <	FzTEncountered graph break when attempting to trace CALL: a function call, e.g. f(x, y)c                &    | j                  |       y r   r  r  s     r   r.  zInstructionTranslatorBase.CALL  s    
 	

4r   c                r    |j                   J | j                  | j                  |j                              y r   )r4  r8  r  r  s     r   COPYzInstructionTranslatorBase.COPY  s-    xx###		$**dhhY'(r   c                    |j                   J | j                  |j                       | j                  d   c| j                  d<   | j                  |j                    <   y r  )r4  r  r  s     r   SWAPzInstructionTranslatorBase.SWAP  sM    xx###04

DHH90EtzzRT~-

2

DHH9-r   c                     y r   r   r  s     r   CACHEzInstructionTranslatorBase.CACHE  r  r   c                &    | j                  |       y r   r  r  s     r   BEFORE_WITHz%InstructionTranslatorBase.BEFORE_WITH  r  r   c           	     
   t        |t              r+|j                         s| j                  j	                  |       t
        j                  dk\  r|j                  r>| j                  r/|j                  j                  | j                  d   j                  urd }nE| j                  j                  J | j                  j                  j                  }n|j                  }|rt        | t              st        j                  r;| j                  j	                  t        ||t        | j                         |             n9| j                  j	                  t        ||t        | j                                      |j#                  |       S )Nr,  rn  )rH  rj   supports_graph_breaksr  r   rL  rr  r9  r
  r!  r  r>  r   r  r   r   r  enter)r   rj  r   r!  s       r   	enter_ctxz#InstructionTranslatorBase.enter_ctx  s(    s:;--/0077<w&
 !!$$%%,,D4D4DR4H4O4OO,,::FFF..<<CC[[F$ 56&:T:T  ''#D&#djj/3G   ''fc$**o(VWyyr   c                P    t        dd|  d| j                          dg d       y )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  )r:   r  )rj  s    r   unsupported_ctx_graph_breakz5InstructionTranslatorBase.unsupported_ctx_graph_break:  s3    1GuM?@T@T@V?WWij		
r   c                .   | j                         }t        |t        t        f      s| j	                  |       t        |t        t        f      sJ | j                  t        ||j                               | j                  | j                  ||             y r   )	r  rH  ri   rj   r*  r8  rl   r!  r(  )r   r   rj  s      r   r  z.InstructionTranslatorBase.setup_or_before_withK  s    hhj)+IJ
 ,,S1 )+IJ
 	
 
 			*3<=		$..d+,r   c                V    | j                   sJ | j                  j                  |       y r   )r  r  r   r  s     r   r  z,InstructionTranslatorBase.append_prefix_instZ  s%    &&&&  &r   c                .   t         j                  dk\  rq| j                  set        | j                  |j
                     t              sJ | j                  j                  j                         | j                  |j
                  <   y | j                  |       y r  )rL  rr  r  rH  r|  r  r   r  r.  track_cell_newr  r  s     r   	MAKE_CELLz#InstructionTranslatorBase.MAKE_CELL^  ss    w&t/F/F d224;;?NNN((779   - ##D)r   c                &    | j                  |       y r   r  r  s     r   COPY_FREE_VARSz(InstructionTranslatorBase.COPY_FREE_VARSi      %r   c                &    | j                  |       y r   r1  r  s     r   RETURN_GENERATORz*InstructionTranslatorBase.RETURN_GENERATORl  r3  r   c                2   t         j                  dk\  r| j                          n| j                  d       t         j                  dk\  rO| j                  |   }|| j
                  v r1| j
                  j                  |       | xj                  dz  c_        y y y )Nr  r  rd  r   )rL  rr  r  r:  r  r}  discardrz  )r   r   
current_ips      r   r  z!InstructionTranslatorBase.END_FORs  s    w&HHJIIaL w&d+JT<<<//77
C))Q.) = 'r   c                    t        | j                  j                  |j                  d       t              r6t        d|j                  d|j                   g t        j                         | j                  |       y )Nz)LOAD_FAST_CHECK on uninitialized variablez/Attempted to load uninitialized local variable r  )	r]   r|  rK  r  r   r:   r   r  r,  r  s     r   LOAD_FAST_CHECKz)InstructionTranslatorBase.LOAD_FAST_CHECK  s`    $&&**4;;=|LCMdkk][5)445	 	tr   c                    |j                   | j                  vr| j                  t                      n| j	                  |       t               | j                  |j                   <   y r   )r  r|  r8  r   r,  r  s     r   ro  z-InstructionTranslatorBase.LOAD_FAST_AND_CLEAR  sD    ;;d222IIln%NN4 ,8NT[[)r   c                    | j                  t        j                  |d             |j                  J |j                  dz  r| j	                  |       y | j                  |j                         y )Nr  r1  r   )r   r   r*  r4  r  r  r  r  s     r   LOAD_SUPER_ATTRz)InstructionTranslatorBase.LOAD_SUPER_ATTR  sV    ;..tA>?xx###88a<T"OODKK(r   c                   |j                   dk(  r| j                  |       y |j                   dk(  r| j                  |       y |j                   dk(  r8| j                  t	        | j                         j                  |                    y t        dd|j                    d|j                    dg t        j                         y )	Nre  r     z Missing CALL_INTRINSIC_1 handlerzCALL_INTRINSIC_1 operand: z,No handler implemented for CALL_INTRINSIC_1 z instruction.r  )
r  r  UNARY_POSITIVEr8  r}   r  r  r:   r   rE  r  s     r   CALL_INTRINSIC_1z*InstructionTranslatorBase.CALL_INTRINSIC_1  s    ;;!$$T*[[A%[[AIImDHHJ$H$H$NOP:4T[[MBJ4;;-Wde6)556	r   c                f    | j                         }| j                          | j                  |       y r   r  r  s      r   END_SENDz"InstructionTranslatorBase.END_SEND  s!    hhj
		#r   zpEncountered graph break when attempting to trace CALL_KW: a function call with keyword arguments, e.g. f(x=True)c                *    | j                  |d       y )NT)r  r  r  s     r   CALL_KWz!InstructionTranslatorBase.CALL_KW  s     	

4
&r   c                8    | j                   j                  dv sJ y )N)POP_JUMP_IF_TRUEPOP_JUMP_IF_FALSEr  )r  r   r  s     r   r  z!InstructionTranslatorBase.TO_BOOL  s'     $$++ 0
 
 	
 
r   c                J   |j                   }|J | j                         }t        |t              sJ | j                         }|dz  rDt        j
                  dk\  sJ |j                  | t        j                  d      gi       }||_	        n|dz  r||_
        nz|dz  r\t        |t              sJ |j                  }t        t        t        |d d d   |dd d   d            t!               	      }||_	        n|dz  r||_        n|dz  r||_        | j'                  |       y )
N   r  r   r  r  r  T)strictr  )r4  r  rH  rr   rL  rr  r9  rh   r  r   r  r}   r   rm   r   r  ra   r  r  r8  )r   r   r  rD  r  r   anns          r   SET_FUNCTION_ATTRIBUTEz0InstructionTranslatorBase.SET_FUNCTION_ATTRIBUTE  s      XXZ"8999xxz4<##w... %%d-=-D-DQ-G,H"MD!BNT\BJT\dM222 JJE#SssU14a4[>?.0C !BNT\ BMT\BK		"r   c                v    | j                  | j                  | j                         |j                               y r   )r8  r  r  r  r  s     r   CONVERT_VALUEz'InstructionTranslatorBase.CONVERT_VALUE  s%    		$%%dhhj$++>?r   c                N    | j                  t        j                  d      d       y )Nr   r   )r  rh   r  r  s     r   FORMAT_SIMPLEz'InstructionTranslatorBase.FORMAT_SIMPLE  s    +2226:r   c                D    | j                  | j                         d       y r   )r  r  r  s     r   FORMAT_WITH_SPECz*InstructionTranslatorBase.FORMAT_WITH_SPEC  s    488:q)r   )	__enter____exit__
__aenter__	__aexit__c                `   t        |j                  t              sJ d       | j                  |j                     }|dv r| j	                         }t        |t
        t        f      s| j                  |       t        |t
        t        f      sJ |dk(  r,| j                  t        |             | j                  |       y | j                  t        |d              | j                  |       y | j                  |       | j	                         }| j                  |       | j                  |       y )Nz*expected LOAD_SPECIAL arg to be set to int)rT  rU  rT  )rH  r4  r   _load_special_namesr  ri   rj   r*  r8  rk   rQ  rl   r  )r   r   r  rj  r  s        r   LOAD_SPECIALz&InstructionTranslatorBase.LOAD_SPECIAL  s   $((C(V*VV(''1,,((*C-/MN 005 -/MN   {"		3C89t$ 		23=>t$ OOD!((*CIIcNNN4 r   c                `    | j                  t        j                  |j                               y r   )r8  rh   r  r  r  s     r   LOAD_SMALL_INTz(InstructionTranslatorBase.LOAD_SMALL_INT  s    		"))$++67r   )r  r  r)  r  anyc                    t        |j                  t              sJ d       | j                  | j	                  | j
                  |j                                  y )Nz2expected LOAD_COMMON_CONSTANT arg to be set to int)rH  r4  r   r8  r  _common_constantsr  s     r   LOAD_COMMON_CONSTANTz.InstructionTranslatorBase.LOAD_COMMON_CONSTANT)  sH    $((C( 	
@	
( 			$//0F0Ftxx0PQRr   c                P    | j                   j                         dkD  r	d | _        yy)Nr   c                      yNTr   r   r   r   r   z>InstructionTranslatorBase.is_non_empty_graph.<locals>.<lambda>2  r8  r   TF)r  count_callsr  r   s    r   r  z,InstructionTranslatorBase.is_non_empty_graph/  s%    ;;""$q(&2D#r   c           
         |g }dj                  t        j                  | j                         gt	        t        |            z               S )Nr   )r   	tracebackformat_listr  r   r   )r   additional_stack_framess     r   format_frame_summaryz.InstructionTranslatorBase.format_frame_summary6  sN     #*&(#ww!!##%&h7N.O)PP
 	
r   c           	         t        j                  t        | j                  dd      | j                  t        | j                  dd      d      S )Nr  	<unknown>r  F)lookup_line)rf  FrameSummaryr  r  r   r   s    r   r  z'InstructionTranslatorBase.frame_summaryA  s?    %%DKK<KKDKKK8	
 	
r   c                    t        | j                  dd      }t        j                  d      }|j	                  |      d uS )Nr  rk  z.*torch/nn/modules.*)r  r  recompilematch)r   r   nn_modules_patterns      r   is_co_filename_from_nn_modulesz8InstructionTranslatorBase.is_co_filename_from_nn_modulesI  s:    4;;{CZZ(?@!''1==r   c                    | j                   j                  |t        j                  |            }t	        t        |      j                  t        j                               |S r   )	r  install_global_by_idrC  rD  r>   rP   r  r=   WEAKREF_ALIVE)r   r  r  global_names       r   store_global_weakref_by_idz4InstructionTranslatorBase.store_global_weakref_by_idN  sJ    kk66vw{{5?QR,778R8RS	
 r   c                B    | j                   j                  j                  S r   )r  tracing_context	fake_moder   s    r   r{  z#InstructionTranslatorBase.fake_modeU  s    {{**444r   c              #  b   K   | j                   }|| _         	 d || _         y# || _         w xY ww)zx
        Strict mode is enabled on a per-VariableTracker level depending on the return value of check_fn(node).
        N)r  )r   check_fnpriors      r   strict_translation_modez1InstructionTranslatorBase.strict_translation_modeY  s3      %% (	*$)D!ED!s   /# /	,/c                   | j                   J | j                   dkD  sJ | j                  j                  | j                  j                  | j
                  | j                   dz
  | j                  | j                   dz
           S re  )r   r  r   r  r  r   r  r   s    r   r  z#InstructionTranslatorBase.speculateg  s|    ''333''!+++##((KK##KK$$q(d66:;	
 	
r   c                    t         j                  dk\  sJ | j                  J | j                  dz
  }t               }| j                  |t        |      z
  | D cg c]  }|j                   }}||k(  S c c}w )zDetect if we're at the start of a list/dict comprehension in 3.12+.

        In Python 3.12+, comprehensions are inlined with a bytecode pattern that
        precedes BUILD_LIST/BUILD_MAP.
        rd  r   )rL  rr  r   rt  r  r   r   )r   r  patternr   r  s        r   ry  z1InstructionTranslatorBase._is_comprehension_startq  s     7***''333%%)46*.*;*;BW<MPR*ST$$++TT   Us   A4c                .   t         j                  dk\  sJ | j                  J d}t        | j                  t	        | j
                              D ]D  }| j
                  |   }|j                  dk(  r|dz  }'|j                  dk(  s7|dz  }|dk(  sB|c S  y)zPFind the instruction pointer of the outermost END_FOR for current comprehension.rd  r   r  r   r  rn  )rL  rr  r   rj  r   r  r   )r   nesting_depth	search_ipr   s       r   r|  z8InstructionTranslatorBase._find_comprehension_end_for_ip  s    7***''333t77T=N=N9OP 	%I$$Y/D{{j("	)" A%$$	% r   c                    t         j                  dk\  sJ  j                  J t                j                  dz
  }g }g }g }t	               }|dz
  }|dk\  r[ j
                  |   }|j                  dk(  r"|j                  d|j                         |dz  }n|j                  dv r|dz  }nn|dk\  r[|j                  |        j                         }|dk(  rt        dd	d
g        t         fdt        ||      D              }	t        |	dz   |      D ]+  }
 j
                  |
   }|j                  dk(  rn|j                  dk(  r_|
dz   |k  rW j
                  |
dz      }|j                  dk(  r6|j                  }||vr&||vr"|j                  |       |j!                  |       |j                  dk(  r|j!                  |j                         |j                  j#                  d      st%        |j                  t&              r|j                  n|j                  f}|D ]  }||vs||vs|j                  |        . g |dz   }|t)         j
                        k  r~ j
                  |   j                  dk7  rbj                   j
                  |   j                         |dz  }|t)         j
                        k  r j
                  |   j                  dk7  rb|}|t)         j
                        k  rV j
                  |   j                  dk(  r:|dz  }|t)         j
                        k  r j
                  |   j                  dk(  r:|t)         j
                        k  r j
                  |   j                  nddfd}d} |d      r j
                  |   j                  }d}nI |d      rd}d}d   d   r|dz   n|}n- |d      sd   d   k(  rd}d}nt        dd d dg        t+        |||||      S )zDAnalyze comprehension bytecode to determine result handling pattern.rd  Nr   r   ro  )r   r  rn  z)Comprehension analysis failed: No END_FORr   z=Could not find END_FOR instruction in comprehension bytecode.r  c              3  Z   K   | ]"  }j                   |   j                  d k(  r| $ yw)r  N)r  r   )r   rY  r   s     r   r   zCInstructionTranslatorBase._analyze_comprehension.<locals>.<genexpr>  s2      
  #**j8 
s   (+r  r  r,  c                B    |    }|d   k(  xr |d   k(  xs |d    S )Nr  r  r   )r   patpatternsr  r  s     r   matcheszAInstructionTranslatorBase._analyze_comprehension.<locals>.matches  s=    4.C C$88 _!55QS=Q9Qr   r  Fr  r  r  r  r  Tz)Comprehension analysis failed: No matcheszpre_store_ops=z, post_store_op=z8Comprehension does not match any known bytecode pattern.)r  r  r  r  r  r  )r   r   r   r   )rL  rr  r   r  r  r  r   insertr  r  r|  r:   r   rj  r4  r   r  rX  rH  r)  r   r  )r   start_ipr  r  r  defined_insideiter_scan_ipr   r  for_iter_ipbody_ip	next_instvar_name	var_namesscan_ipstore_fast_ipr  r  r  r  r  r  s   `                  @@@r   _analyze_comprehensionz0InstructionTranslatorBase._analyze_comprehension  s>   7***''33357++a/#%!##%#&5  !|a$$\2D{{33$$Q4! 44! a 	m,88:
C[	  
8Z0
 
 [1_j9 	7G$$W-D {{f$Q7Q;;S --gk:	##|3(//H}49T#**84&**84 {{l*""4;;/ ''4#-dkk5#ADKK~  !* 7H~5(-:W%,,X67+	74 $&q.c$++,,!!'*11\A  !2!27!;!B!BCqLG	 c$++,,!!'*11\A
   c$++,,!!'*11\AqLG c$++,,!!'*11\A T..// g&-- 		 %)
8**=9@@J#O[!J#O%-k%:?%KgkQXGJ 4_ EEJ"OC(7GWV	 %!+'#'
 	
r   c           	     `   t         j                  dk\  sJ | j                         }| j                  j                  j                  t              r.|j                  r"t        dt        |j                        dg        | j                  J | j                  dz
  }dt        |j                        z   }t        d| j                         g      }t        j!                  d       | j"                  j%                  | ||	      }t'        |      D cg c]8  }t)        | j*                  t        | j*                        |z
  |z      t,              : }}| j/                  |       |d
   }	t1        | j"                  j2                        }
t5        d |D              }t        | j*                        t        |	j6                        z
  }|
j9                  g t;        ||z   dz         |
j=                  d
      |
j?                                tA        t'        |            D ]^  }|
j9                  tC        d             ||   r |
j9                  |
jE                                B|
j9                  tG        dd      g       ` |
j9                  tG        d      g       | jI                  ||||||	      \  }}|
j9                  g t;        |dz         |
j=                  d
      |
j?                         tG        dd      t;        |dz         |
j=                  d
      |
j?                         tG        dd             | jK                  |g|g|
       |d
kD  r|dz   dz   }|
j9                  g t;        |      |
j=                  d
      |
j?                         tM               |
j=                  |       |
j=                  d      tG        dd      tG        d      tG        d             |jN                  |jP                  r|jP                  gng z   }i }|D ]\  }tS               | jT                  |<   ||	jV                  v r|	jV                  |   ||<   ;t        |	jV                        |	jV                  |<   ^ |dz   }|jN                  r1|
j9                  g t;        |      |
j=                  d
      |
j?                                tY        |jN                        D ]  \  }}|
j9                  g t;        d      |
j=                  |dz         |
j?                                ||v r<|
j9                  g t;        d      |
j=                  ||         tG        d             |
j9                  tG        dd      g        |
j9                  tG        d      |
j=                  d
      |
j?                         g       |jZ                  r| j]                  tS                      n|jP                  r|
j9                  g t;        |      |
j=                  d
      |
j?                                |jP                  |v r9|
j9                  |
j=                  ||jP                           tG        d      g       nP|
j9                  g tC        d      tG        dd      tG        d             n|
j9                  tG        d      g       | j"                  j_                  |
ja                                | jb                  |jd                     }| j"                  j_                  | jg                  ||             d| _
        yc c}w )zHandle list/dict comprehension graph break.

        Builds a synthetic function wrapping the comprehension bytecode,
        calls it via codegen_call_resume, then chains into the resume
        function for the post-comprehension code.
        rd  zDComprehension graph break in resume function with captured variableszCannot use comprehension optimization inside a resume function when there are captured variables. This can cause issues with deeply nested source chains.r  Nr   comprehension_graph_breakzcomprehension triggered compiler  r   c              3  &   K   | ]	  }|rd   yw)r   Nr   )r   ms     r   r   zNInstructionTranslatorBase._handle_comprehension_graph_break.<locals>.<genexpr>G  s     E!1AEs   r  r  r  r  rp  rt  r  r  )4rL  rr  r  r  r  rX  rL   r  r:   r   r   r   r  r?   r  r  r  r  r  rj  rH  r  r   r:  r2   r6  r  r@  r  r&   r  r  r   r+   pop_nullr(   _build_comprehension_fnr  r'   r  r  r   r|  r  r]  r  r8  r  r\  r  r  r  )r   r   analysisr  r  r   r  rY  stack_pops_null_maskrI  r  nonnull_countlive_stack_depthrS  r  frame_values_posvars_to_passexisting_varsr  fv_depthrM  
walrus_varrH  s                          r   r{  z;InstructionTranslatorBase._handle_comprehension_graph_break  s    7***..0 ;;))*GH%%b 6 67!8  ''333++a/X3344
#$?$BTBTBVAWX		34 %)KK$@$@! %A %
! :& 
 tzz#djj/J">"BC\R 
  

 			*(+t{{**+ E';EE tzz?S1F1F-GG 	-
:Q>? $$Q' '')		
 %
+, 	MA[^,#A&  /  "4]"J!KL	M 	,Y789
 !88 
' 		-12	$$Q'	 '')	 #<Q7		
 -12	 $$Q'	 '')	 #<Q7		
  	  (gY;
 1/!3a7 !12((+ ++-
 #$ ((-8 ((. '}!< '7 'y1&  ++%-%8%8X  !b
 )+$ 	EH-<->D  *4,,,*.*;*;H*Eh'.1$2C2C.D!!(+	E $a'  *((+ ++- "+8+?+?!@ Q:  $Q,,QU3 //1 .$$(^00z1JK /~> $$&8A&N%OP'Q* &y1((+++-	 ##IIo'(   *((+ ++- ""m3  ,,]8;N;N-OP*>:   $Q*=a@ +95 0;<= 	++B,?,?,AB ''8++&&{4MN	
 $( } 
s   =\+c                    ddl m} ddlm} ddlmm t         fd|j                  D              }	ddgt        |	      z   t              D 
cg c]  }
d|
 	 c}
z   t        t        t         j                  j                  xs g       t         j                  j                  xs g       z                j                   j                  n j                  j                   t#        d	 j                  j$                   d
       j&                  j(                  z   j*                  rj*                  gng z   j,                  z   	 	 	 	 	 	 d fd} | j                  |      \  }} ||       |j                  r  j.                  j1                  |       |fS  j.                  j1                  t3        j4                  | j6                               |fS c c}
w )a  Build a synthetic function wrapping comprehension bytecode.

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

        Returns (code, name) where name is the global name for the function.
        r   )transform_code_objectr  )
CO_VARARGSCO_VARKEYWORDSc              3  H   K   | ]  }|j                         vs|  y wr   r-  )r   r   r   s     r   r   zDInstructionTranslatorBase._build_comprehension_fn.<locals>.<genexpr>  s&      
AT5K5K5M,MA
s   ""__nested_resume_fns__nested_frame_values___stack__comprehension__at_c           	     L   |d<   t         j                  dk\  r|d<   |d<   d|d<   |d<   t              |d<   d	|d
<   d	|d<   t        D cg c]	  }|vs| c}z         |d<   |d   	
z   z  |d<   g }r%|j	                  t        dt                           |j	                  t        dd	             dz
  }t              D ]F  }|   r|j	                  t        d             #|j	                  t        dd|              |dz  }H j                  j                        }g }j                  sOj                  r'|j	                  t        dj                               n|j	                  t        dd              j                  r_j                  D ]  }|j	                  t        d|               |j	                  t        ddt        j                        z                |j	                  t        d             ||z   |z   | d d  y c c}w )Nr  r,  r  co_firstlinenor   r  r  co_argcountr   co_posonlyargcountco_kwonlyargcountco_varnamesco_flagsr2  r  r  r   rQ  r,  r  r1  r  rr  r  )rL  rr  r   r)  r   r(   rj  _copy_comprehension_bytecoder  r  r  r  )r  r  r   r  	nonnull_irY  
comp_instsepiloguer  r  r  r  r   comprehension_body_varsr  r  r   r  r   r  r  r  s            r   r  zAInstructionTranslatorBase._build_comprehension_fn.<locals>.update-  s?    '.L#7*.5]+-3L)**,L'*2L'*-d)L'12L-.01L,-*/#:LaatmLL+L' (4J'?^+C (L$ )+F01As8}UVMM,X1=> &)I:& #'*MM"4["ABMM*;)?UV NI# ::8X__UJ +-H++&&OO*;x?R?RS OO$6|D$QR## ( 4 4 VHOO$6{8$TUV&%H$8$8 99 OO.~>?$z1H<LOa Ms   	H!
H!
)r  r  r  r   r   r   )bytecode_transformationr  r  r  resume_executionr  r  r)  r  r   rj  sortedr  r  r  r   r  r0   r  r  r  r  r  r  rE  rI  rF  rA  )r   r  r  r  r  r  rI  r  r  r  rY  r  rS  r   r  r  r   r  r  r  r   s   ``````        @@@@@@@r   r  z1InstructionTranslatorBase._build_comprehension_fn  s   $ 	C)@
  
((
 
 #$;<8n',]';<!!~<= 	 T[[,,23t{{..4"56
 !% 7T[[=W=W.t{{/B/B.C4xPQ """"#(0(;(;##$E $$% 	 =	=+=	=;I=	==	= =	= =	=~ ,DKK@!( KK--gx@    KK--""8T^^WE
    =s   G<c                    i }g }t        ||      D ]C  }| j                  |   }t        j                  |      }d|_        |||<   |j	                  |       E |D ]2  }|j
                  |j
                  |v s||j
                     |_        4 |S )z@Copy comprehension bytecode instructions, updating jump targets.N)rj  r  r8  r9  r   r!  )r   r  r  inst_mapcopied_instsr  original_instcopied_insts           r   r  z6InstructionTranslatorBase._copy_comprehension_bytecodez  s     46*,&) 	-B --b1M))M2K(,K%&1H]#,	- ( 	BK!!-+2D2D2P%-k.@.@%A"	B r   c                     ||dk  r||fS ||fS r   r   )r   r   r   fallback_linenos       r   _make_frame_locz)InstructionTranslatorBase._make_frame_loc  s%     >VaZo..&!!r   c                d   g }t         j                  rs| j                  }|e| j                  |j                  j
                  |j                  |j                  j                        }|j                  |       |j                  }|e|j                          |j                  |       t        |      S r   )r   r  r	  r  r  r  r   r  r   reverser)  )r   	frame_locframe_loc_chain_list
current_txparent_frame_locs        r   _get_frame_loc_chainz.InstructionTranslatorBase._get_frame_loc_chain  s     79%%>BkkJ(#'#7#7%%11%%%%44$ 
 %++,<='..
 ( 	$$&##I.)**r   c                   |j                   ry t        |dd       }|(t        j                  j                  j                         }	 t        j                  rR| j                  F| j                  | j                  j                  | j                  | j                  j                        }n-| j                  |d   j                  |d   j                  d      }| j!                  |      }d}t        j"                  r/t%               }dj'                  t)        j*                  |            }nt%               |z   }t-        |      }dj'                  t)        j*                  |            }	|t/        ||      }d|d    d|d	    d
| dt        j"                  r| d|	 dz  nt1        |	      z  t        j2                  j5                  dd fd       t7        |t8              r|j:                  n
t=        |      }
t>        jA                  tB        jD                        rptF        sjtI        jJ                  |
|f      rSt        j"                  r&dz  dj'                  | jL                        dz   z  t>        jO                         d|_         y t>        jO                  d|d   |d	   |       d|_         y # t        $ r |d   |d   f}Y w xY w)Nr#  rn  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                     dddS )Ndynamo_graph_break_reasonstring)r   encodingr   r   r   r   r   z;InstructionTranslatorBase.log_graph_break.<locals>.<lambda>  s    3$! r   c                 6      dt        j                          S )Nr   )rf  
format_exc)user_stack_traces   r   r   z;InstructionTranslatorBase.log_graph_break.<locals>.<lambda>  s    "2!32i6J6J6L5MN r   )metadata_fn
payload_fnz4
Most recent bytecode instructions traced (max 20):
r   zmGraph break (user stack suppressed due to duplicate graph break) in user code at %s:%s
Graph Break Reason: %sT)(loggedr  r  r  r   r  r   r  r	  r  r  r  r   r  r   
IndexErrorr  r  r7   r   rf  rg  r5   r3   r   _loggingtrace_structuredrH  r;   r  r  graph_break_logisEnabledForr   DEBUGexplainr\   r  r  r  )r   r  r   r   
user_stackr  frame_loc_chainstack_above_dynamo_formattedstack_above_dynamouser_stack_formattedr  r  s              @r   r  z)InstructionTranslatorBase.log_graph_break  s    ::S,5
55CCEJ	))dkk.E 00KK++KKKK..	 !00rN++rN))	 33I>')$>>!7!9+-77%%&89,( 01J>J/
;J!wwy'<'<Z'HI ?6sFCF +9Q<.)A, H##)( +'' 	 >>/0 1e'( )LL $8 99'' O 	( 	
 ",C!=#++49((7/33Wo4NO
 ~~ L  !DIId.H.H$ID$PP !!  
 !! A!!	 
c  	 ]+-.I	s   BJ4 4K
Kc                ^    t        ddt        |        dg t        j                  |d       y )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!  )r:   r6   r   r   )rd  r   s     r   r  z0InstructionTranslatorBase.raise_loop_graph_break  s9    )%&7&=%>?hD%CCD	
r   c                   t         |           || _        || _        || _        || _        || _        |	| _        |
| _        d | _	        g | _
        d| _        d | _        t        d      | _        d| _        g | _        g | _        d| _        d | _        d| _        g | _        || _        t/        d      | _        d| _        t5               | _        || _        ||nt;        | j8                        | _        || _        || _         || _!        || _"        || _#        || _$        |$tJ        jL                  rtO        |||      | _(        nd | _(        i | _)        i | _*        || _+        d| _,        d| _-        d| _.        d | _/        d | _0        d| _1        d | _2        d| _3        g | _4        || _5        d	d
l6m7}m8}m9}m:} |jv                  ||z  |z  |z  z  r| jy                  t{        d              || _>        d| _?        d gt        |j                        z  | _B        t        j                  t        j                        | _G        t        j                  t        j                        | _I        t        j                  |j                  |       y )Nr   r  Trn     )maxlen)rd  r  r  Fr   )CO_ASYNC_GENERATORCO_COROUTINECO_GENERATORCO_ITERABLE_COROUTINE)MrH  rI  r  distributed_stater  r|  r}  r~  r  r  r  r   r  r(   r  r  r
  r  r   r7  r  r  r  r   r  rz  r  r}  r  r   r  r&  rA  rC  r  r  r  r   replay_record_enabledrH   r  nn_module_stack	num_callsexportr  r   r  r  r  r  r	  r  r  r  r  r  r  r  r  r  r8  rf   r  r  r   r  r=  r  r  r   r  r  r  r  r  	lazycacher  )r   r  r  r&  rA  rC  r  r|  r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rP  s                           r   rI  z"InstructionTranslatorBase.__init__#  s   0 	.!2 . 0-J*%:" -1),.
#$ #5e#< (,%UW,"&(%*"%5"$%!47E' 0<*GD<M<M0N 	  	 *3*4,8&, 6#?#?!2W<"D "&D BD)+ $)!*/'#'  $$(!&+#	
 	
 ??<'*??BTT
 IIod+,().& FS))** 	
 ++GMM: 	* ))'--8 	( 	F..	:r   r   r  r   r  )rD  rb   r   r  r  r{  r   r   )rD  ro   r   Sequence[VariableTracker]r  r{  r   rb   )rD  ro   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^  Optional[VariableTracker]r   r   )r  r  r   r   r   rb   )r!  r   r   r  )r   r-   r   rb   )rL  r   r   rO   )r   r   r  r   ri  r   r   r   )r  r   r   rb   )r   zInstruction | BlockStackEntryr   r   )r^  rb   r   rb   )r   r   r   r   )r^  rb   r   r   )r^  rb   r   zTypeIs[ExceptionVals])r  r   r   r   )r  r   r   r   )r   r-   r  r   r   r  )r  r   rH  r-   rI  rA   rJ  list[types.CodeType]r  r2   rK  r   rL  r   r   tuple[types.CodeType, str]r   r-   r  zlist[StackLocalsMetadata]r   r  )rJ  r  r^  r  r  r2   r   r   )r   r-   r   r   )r   r-   r  r  r   r   )r  rb   r  r   r   rb   )r  rb   r  r   r   r   )F)r   r-   r  r   r   r   )rj  z>Union[ContextWrappingVariable, GenericContextWrappingVariable]r   r-   r   rb   )rj  rb   r   r   )rh  zOptional[list[Any]]r   r   )r   ztraceback.FrameSummary)r  r   r  r   r   r   r   zOptional[FakeTensorMode])r}  z!Callable[[VariableTracker], bool]r   r   )r   r   r  )r   r  )r  r  r  r   r  r   r  z
list[bool]r  r   rI  rA   r   r  )r  r   r  r   r   r  )r   r   r   r  r  r   r   tuple[str, int])r  r  r   ztuple[tuple[str, int], ...])r  r   r   r   r   zUnsupported | StepUnsupportedr   r   )rd  types.CodeTyper   r;   r   r   )NNN)(r  r@   r  r  r&  r   rA  r   rC  r   r  r   r|  r{  r}  r{  r~  r   r  r   r  r   r  r   r  r   r  r   r  rT  r  Optional[DistributedState]r  zOptional[tuple[types.CellType]]r  r  r  z Optional[dict[Instruction, int]]r   r   (  r   r   r   r   r  r  r  r  r  r  r9  r  r  r  r  r  r  rL  rr  r  propertyr  r  r  r  r8  r  r  r:  r,  r2  r  r7  r;  LOAD_CLOSUREr>  r  rI  rB  cached_propertyrO  rR  rX  r   rK  rl  ru  r  EAGER_IMPORT_NAMEr  r  rE  r  JUMP_FORWARDJUMP_ABSOLUTEr  r  not_rH  r  rG  JUMP_IF_FALSE_OR_POPJUMP_IF_TRUE_OR_POPr  r  r  r  r  r  r  r  r  r  r  r  rZ  r  r  r  r  r  r  r  r  r  r  r  r  r?  r   r	  r  r  r  r  r  r  r  r"  r%  staticmethodr)  r  r  r  r  r  r  rr  rt  rv  r  rp  r  r{   r  r  BUILD_TUPLE_UNPACK_WITH_CALLr  r  BUILD_MAP_UNPACK_WITH_CALLr  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  DICT_UPDATEr  r  r  r  r  r  r  r  rE  r  r@  negUNARY_NEGATIVEr  invertUNARY_INVERTpowBINARY_POWERmulBINARY_MULTIPLYmatmulBINARY_MATRIX_MULTIPLYfloordivBINARY_FLOOR_DIVIDEtruedivBINARY_TRUE_DIVIDErN  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_ORr  r  r/  r0  rQ  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*  r  r  r/  r2  r5  r  r:  ro  r=  rA  rC  rE  r  rM  rO  rQ  rS  LOAD_FAST_BORROWr  POP_ITERrY  rZ  r\  r_  r`  r  ri  r  rs  rx  r{  
contextlibcontextmanagerr  r  ry  r|  r  r{  r  r  r  r  r  r  rI  rQ  rR  s   @r   r   r     s(    //00#==.."FF  &&$$""&&K((####33  ..AA// ! EE%%%%.!F00'

88 $8 +	8
 
8,4$4 (4 +	4
 
4U$U (U +	U
 
Un	Wob 7"*	+\	 ; ;BH2H=T ;!+FV2./ L	*J* J J!E( # #,
2:;| $% 6 6,>4 LM$X]]E:#HNNE:'t<&x~~t<U
U
(UN*
(-
^ RD0..$)LA'F<:$*QfKPD  )	)
  >;	>;@  A
	-
	-G  )%   A
	

 &)	 >A%A% !A% "	A%
 +A% A% A% "A% 
$A%Fg%g% $=g% 
	g%R q?*q?:Cq?IRq?	q? q?f
&  ~=	=8(1!FI
 @L @ 8 $6 J
 "2
 9.1%
N@0  N

4

N(3
B"!:1P%$1 K@

R R"CD hll+Nhll+N'IHOO,LHLL)Lx||,O%hoo6"8#4#45!("2"23X\\*M-(,,'Jx||,O.u x "M X__-MX__-M(--(J&I(,,'JX]]+M.&x'7'78#H$6$67"8#4#45hmm,N /8==)K.h../Nh../N8==)K8==)K(,,'J/ 7"	;@"-!^  i	)V M!%+HNNEB ,X^^U C ,X]]E B!-hmmU!C(#K# # 
	#J 
 
 -'	*&&/;)$  A
'
'
B@;* !IH
!88S >B	
':	
		

>
 5 5 *9*	* *
!  A
Fd(L~!'~! ~! 	~!
 )~! ~! "~! 
$~!@%(	(""%2"EH"	"+(+	$+(l$l l +	l
 
l\ 	
 	
< 48,048-@;@; (@; !	@;
 "@; #@; %@; 4@; 5@; (B@;  3@; @; @; @; (@;  %!@;" 6#@;& 1'@;( *)@;, 2-@;. 
/@; @;r   )	metaclassc                       e Zd Zedd       Zej                  dd       Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZ	ddZ
ddZddZddZdd	Zdd
Z xZS )r>  c                 "    t         j                  S r   )tlsr  r   r   r   r  z InstructionTranslator.current_tx  s    ~~r   c              #     K   t        t        dd       }| t        _        	 d  |t        _        y # |t        _        w xY ww)Nr  )r  rU  r  )r   r~  s     r   set_current_txz$InstructionTranslator.set_current_tx  s1     \40	#"CNUCNs   A 0 A =A c                    t               t        j                  d|j                   d|d    d|d           t        |   t        ||	| ||||||||
|      ||||||i i d d ||d||||       | j                          t        | j                  j                        5  | j                         5  |
| _        || _        | j                  r| j                  sJ d	       i | _        t        | j!                               }t#        j$                  |      j'                  d
d       }|j)                         D ]h  \  }}||vsd }|r)t+        |j'                  |i       j)                               }t-        j.                  |t1        |d|            }|| j                  |<   j | j                  j2                  }| j5                         D ]x  }||v rL||   }t1        |dd      }t-        j.                  ||      }|j7                         }|j9                  ||       n|j7                         }||_        || j                  |<   z |J t=        | j?                         |      D ]g  \  }}tA        |      }t1        |d      }	 t-        j.                  |jB                  |      }|jK                  |||      }||_        || j                  |<   i tM        |      | _'        tQ               | _)        |r.tF        j,                  jU                  | j                        | _        d d d        d d d        y # tD        $ r tG        jH                         }Y w xY w# 1 sw Y   5xY w# 1 sw Y   y xY w)Nztorchdynamo start tracing r  r  r   r  )local_scoperc  r  torch_function_mode_stackr  r  r   )r  r  r&  rA  rC  r  r  r|  r}  r~  r  r  r  r  r  r  r  r  z4Export without one graph - something has gone wrong.dynamismT)is_inputr[  )r\  is_derefed_cell_contents)r]  )+r  r   INFOr  rH  rI  r@   _throw_if_in_functorchr   r  rz  rW  r  r  r|  r  r  r1   rB  rK  r   	frozensetrw   r  rR   r.  r  r.  r9  r:  r  r  rQ   cell_contentsr  r   DeletedVariabletrack_cell_existingr   r~  r   r  realize_all)r   r  r  r&  rA  rC  r  rZ  r  compiler_fnr  r  export_constraintsframe_stater  r  r  r  r  r[  r   r  local_dynamismvarr.  contents_sourcer1  cell_varr0  cell_sourcerP  s                                 r   rI  zInstructionTranslator.__init__  s   ( 	LL((8,}:U9VVWXdeuXvWwx	
 	"$&*C# &!%*."&+%/A 	 !	
F 	##% T[[001 d	43F3F3H d	#,DN DK{{~~ J~ $&D *-d.D.D.F*G#//7;;JMH'~~/ 5e00%)N)28<<b3I3O3O3Q)R-44# %)%3C 25D((.5"  ;;33L %68#$TNE* '2!%15'O
 5H4N4N5L  ,::<H ++HlC+::<H&*#-5$$T*K%6R &&&!$--/7; 6
d-d3"-dT"R?#6#=#=**O$L (;;| '+#-5$$T*6  2L)2D. *=)>D& (1'D'D'P'P((($Ed	 d	 d	` " ?#,#<#<#>L?ad	 d	 d	 d	sQ   M0BM
>D=M
< L'A:M
M'M	M
M	M

M	MMc                   t         j                  j                  d      }t        j                  | j
                  j                  d| j
                  j                        }t         j                  j                  j                         }t         j                  j                  j                  j                  t         j                  j                  j                  j                  t         j                  j                  j                  j                  f}|\|j                         |v rI||urD|j                         j                  j!                         }d| d| d| d}t#        dd|g 	       y y y y )
Neagerre  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_backendr?  getattr_staticr  re  _C
_functorchpeek_interpreter_stackTransformTypeVmapGradJvprm  r   lowerr:   )r   rn  re  ciforbidden_keysr   rR  s          r   r_  z,InstructionTranslator._throw_if_in_functorchY  s0   ,,W5,,KK##]DKK4K4K
 XX  779HH--22HH--22HH--11
 >bffh.8[PU=U668==&&(D((,v .**. 0  !%v%WY  ?	 >V8>r   c                    t        |t              r| j                  |j                     S t        |t              r| j
                  |j                     S t        r   )rH  rR   r&  r:  rO   rA  rw  r)  )r   r  s     r   get_example_valuez'InstructionTranslator.get_example_valuex  sE    fk*==!2!233fl+>>&"4"455r   c                    | j                   j                         D ]G  }t        |t              st	        |j                         t        j                  j                        sG y yr   )	r|  r  rH  r   r  r  r  nnModule)r   r   s     r   $symbolic_locals_contain_module_classz:InstructionTranslator.symbolic_locals_contain_module_class  sR    %%,,. 	A!56:$$&< 		
 r   c                    t        | j                        rU| j                  d   x}rCt        |t              r2t	        |j                  |       t                     | j                  d<   y y y y )Nrn  r  )r   r  rH  rq   rz   r  ra   )r   r  s     r   "replace_tos_if_return_is_generatorz8InstructionTranslator.replace_tos_if_return_is_generator  s`    

O

2&&3 <=1--d3.0DJJrN > ' r   c                   | j                          | j                  J | j                  J t               j	                  d| j                  | j                  z
         t
        j                  s| j                  j                         dk(  rw| j                  sk| j                         s[| j                  sO| j                  sC| j                  s7| j                  s+t        j                   dt#        | j$                               d | _         t'               t(        j*                  d| j$                  j,                   d|j.                   d       t0        j3                  d       | j                  j5                  | t7        d| j9                         gd	
      |j.                  dk(  rdnd      }t;        |      dk(  sJ |d   j<                  rJ | j                  j?                  | jA                  ||d   jB                               tD        )Nr  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  r  r   r  )#r  r   r  r[   r  r   allow_empty_graphsr  rd  r  r  r  r  r   r  r   	SkipFramer6   r  r  r   r^  r  r   r  r  r  r?   r  r   r@  r  r)  r  r3  )r   r   r  s      r   _returnzInstructionTranslator._return  s   //1''333+++''0043C3CC	

 ))'')Q.22==?KKNN--33 --0=>@ 
 $( LL'(;(;'<Bt{{m1M	
 			,-$(KK$@$@%!3!3!5 6E !KK>9qq %A %
! ,-222,Q/@@@@++))$0I!0L0V0VW	
 r   c                &    | j                  |       y r   r  r  s     r   r  z"InstructionTranslator.RETURN_VALUE      Tr   c                &    | j                  |       y r   r  r  s     r   r  z"InstructionTranslator.RETURN_CONST  r  r   )r   r>  r  )$r  r  r  r   r&  r   rA  r   rC  r   r  zOptional[tuple[Any, ...]]rZ  r   r  r   re  r   r  r   r  r   rf  r   rg  r   r  r   r  rT  r  r  r  r  r   r   r   )r  rT   r   r   r  r  )r   r   r   r  r  rP  rQ  rW  rI  r_  r}  r  r  r  r  r  rQ  rR  s   @r   r>  r>    s     # #c'c c !	c
 "c #c +c $'c %c c c c  c c (c  %!c" 6#c$ *%c& 
'cJ>	-^r   r>  r,  INPLACEre  BINARY_c              #  d  K   t         j                  sd y| j                  t               | _        | j                  j	                         }| j                  j                         }| j                  j                  |j                  |j                  |j                  t        j                                d}	 d d}| j                  j                         }t        j                         }|r| |       }||j                  z
  }	|	|j                  z
  }
t        |j                   |j"                  |j$                  |	|
t'        |j(                        ||r|d   nd|r|d   nd|r|d   nd|j*                  |      }| j                  j-                  |       | j                  j/                  |	       yyy# | j                  j                         }t        j                         }|r| |       }||j                  z
  }	|	|j                  z
  }
t        |j                   |j"                  |j$                  |	|
t'        |j(                        ||r|d   nd|r|d   nd|r|d   nd|j*                  |      }| j                  j-                  |       | j                  j/                  |	       w w w xY 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_countr  caller_func_namecaller_filenamecaller_firstlinenois_primitive_call
call_stack)r   dynamo_profilerprofiler_stater   get_current_callerget_call_stackr8  r  r  r  timetime_nsr  start_time_nschild_time_nsr   r  r   r  r   co_coder  record_timingadd_child_time)r  rd  get_inline_depthcaller_infor  trace_successstack_entrytrace_end_nsr  r  r  timings               r   profile_inline_callr    sn    " !!$ 3 5''::<K&&557J
d&&(;(;T\\^ M=++//1||~[4+-L%(A(AAJ#k&?&??J(%//$--'33%%"4<<0)3>QD2=A45@;q>d"-"?"?%F !!//7!!00<) 5= ++//1||~[4+-L%(A(AAJ#k&?&??J(%//$--'33%%"4<<0)3>QD2=A45@;q>d"-"?"?%F !!//7!!00<) 5=s    B5J08F5 >C7J05C8J--J0c                  F    e Zd ZU dZded<   ded<   e	 	 	 	 	 	 	 	 	 	 dd       Ze	 	 	 	 dd       Ze	 	 	 	 	 	 	 	 	 	 dd       Z	dd	Z
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd
Zedd       ZddZddZd fdZ	 	 	 	 	 	 d fdZddZddZ	 	 	 	 ddZd fdZd fdZ xZS ) r  z Trace and inline a called methodr  symbolic_resultr   r	  c                    d }t        j                  |j                         fd      5  | j                  |||      }|j	                         cd d d        S # 1 sw Y   y xY w)Nc                 "     j                   dz   S rh  r  )r	  s   r   r   z;InliningInstructionTranslator.inline_call.<locals>.<lambda>!  s    F4G4G!4K r   )r  r  r  build_inline_tracerinline_call_)r  r	  funcr   r  tracers    `    r   r  z)InliningInstructionTranslator.inline_call  s]      MM4==?,K
 	) ,,VT4HF&&(		) 	) 	)s   $AA#c                   | j                         rt        dt        |       dg        t        | t              rt        j                  | j                         dd      rat        j                  | j                         dd       }t        dt        | j                               d| j                          d	| d
dg       t        j                  | d      }|j                  rddlm} t        | d      rDt        | j                  d      r.| j                  j                  |u rt        j                   dd      S t        | d      r| j                  j"                  nd}d| dg}d| j%                         vr|d| ddgz  }t        dd| d| j'                          d| j%                          d|j(                   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_applyrD  _originz"allowlist in dynamo known functionr   zAvoid calling the function `rD  ro  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_selfr:   r   rH  rt   r?  rq  get_functionr   check_verboseskippedtorch._dynamo.variables.miscr  r(  rD  r  
SkipResultr   get_filenameget_namer   )r  rR  rw  r  fn_qualnamer  s         r   check_inlineablez.InliningInstructionTranslator.check_inlineable&  s    ==?6D	k d01g6L6L!77
 ((!!#%?C LD--/05d6G6G6I5J K::=aA ? **4F>>V
 d#DGGY/GGOO'HH #--?  3:$2E$''..2K.{m2>E  1 1 33PQ\P] ^h h 7	  H$[M$--/9J K"//122B6==/S]^i]j k( ( r   c                t	    t        |t        t        t        f      sJ |j	                         d } j
                  j                  }t        j                  s"|r |j                  j                  d       x}r|}|Ft        j                  |      }|j                  du sJ t        j                  s|r||j                  <   d }	 |j                   ||      }|J t/        j0                  |j3                               D ]8  }
t        |
t4              rt!        dd| d|
 dg t*        j6                         : j8                  dv rL|rt        |d   t:        j<                        s-t!        ddj8                   d| dj8                   dg        d}t>        j@                  jB                  jD                  jG                  d      r&dtI        jJ                        jI                          }tL        jN                  dk\  r@ jP                   jR                  d fd}tT        jW                  dtY        |             tZ        jW                  d||j\                         |rt        |d   t^              r j
                  ja                  |d   jb                        }t        |t>        jd                  jf                        r?ti        jj                  |      tm        jn                  |jp                  jr                        d<   |rt        |d   tt              rr|d   jv                  }t        |t>        jd                  jf                        r?ti        jj                  |      tm        jn                  |jp                  jr                        d<   t        |tx              rJ t{              r1t}         | j~                   j                   j                  |      }|S t         | j~                   j                   j                  |      }|S # t        $ r}t!        dd|j#                          d|j%                          d|j	                         j&                   d|D 	cg c]  }	|	j)                          nc c}	w c}	 d| 
d|j#                          d	g t*        j,                  |
       Y d }~d }~ww xY w) NFz2failed to bind arguments when attempting to inlinezfunc='z' r   z	; args = z; kwargs = z4Argument mismatch when attempting to trace function rG  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  )rk  r  r   z2Unsupported __setitem__/__setattr__ inline attemptzcode name: z, args: zAttempted to inline z: where first argument (self) is not a user-defined object.r   bytecoder   r,  c                     j                  j                  j                        } t              j	                         }dj
                   d|  d| S )N)r   zTRACE inlined call z from r   )r  r  r   rZ   r  r  )headerr  rd  cur_instr	  parent_codes     r   get_trace_call_log_strzQInliningInstructionTranslator.build_inline_tracer.<locals>.get_trace_call_log_str  s[    77#--44 8  2+xHOOQ,T\\N&4&QQr   r  zINLINING %s%s, %sr6  r   )BrH  rt   rr   rp   r  r  rz  r   dont_skip_tracingpreviously_inlined_functionsrK  r  r  r  	bind_argsr  r:   r  r  r  r  r   r  r  r  r  rb   r  r  r   r   r  r  	_internal	log_stateis_artifact_enabledr[  BytecoderL  rr  r  r  trace_call_logr  r^   r  r   r   r  r  r  r  rC  rD  r1   rB  forwardr  r   r  rs   r.   &InliningGeneratorInstructionTranslatorr}  r~  r  )r	  r  r   r  rw  tracing_ctxprevious_result
sub_localsr  r4  r   r  r  moduler  rd  r  r  s   `              @@@r   r  z1InliningInstructionTranslator.build_inline_tracerh  sX    $*.
 	
 
  $}}mm33
 ''K"-"J"J"N"Nd#   )>2CCDIF>>U***++AG88>
	f=J %%%!2!2!45 	Aa1X$TF'!5 y9-889		 <<99ZQ)L)LML%dll^8D6B24<<.@z{	  >>##--AA*M#,,t,00234Fw&11H --KR R   z2H'IJ		%tVV]]C JtAw(89]]00a1C1CDF&%(("6"67
 KK' (()@)@A& JtAw(EF!W]]F&%(("6"67
 KK' (()@)@A& d$8999;''44,,F&  3''44,,F }  
	L  1D4E4E4G3H$--/JhJhIi j8<=3??,==>k&SRSWS`S`SbRccde&11 	 	
	s%   P 	R7AR2Q548R22R7c                $   | j                   }d|_        d|_        | j                  }t	        j
                         }|j                  r| j                  |j                        }	 |5  | j                          d d d        | j                   |_        d|_        | j"                  j$                  rt&        S | j(                  J | j*                  |j*                  u r%|j,                  j/                  | j,                         |xj0                  | j0                  z  c_        t        j                  d|       | j"                  j2                  j4                  j7                  |       t8        j:                  st=        | t>              r| j@                  rtC        |      rtt=        | t>              rd| jD                  rXt=        | t>              sJ g }| j(                  jG                         s| j(                  g}t        jH                  tJ        | |       y | j(                  S tC        |      rMt=        | t>              sJ | j(                  jG                         sJ tM        | jN                  tQ                     S | j(                  S # 1 sw Y   xY w# t        j                  $ r#}d| d| }t        j                  |        d }~wt        $ r}d|_         d }~wt        $ r t        j                  d|        w xY w# | j                   |_        d|_        w xY w)	NFTz!Observed exception DURING INLING z : zFAILED INLINING %szDONE INLINING %sr  r  ))r	  r  r  r  rP  nullcontextr  r  r  r   r   r  r  r;   r!  r  r   r  r  rg   r  rA  r}  r  r  rz  traced_coder   r   r  rH  r  is_generator_from_ctx_managerr.   generator_exhaustedis_constant_noner  r  rz   generated_itemsra   )r   r	  rd  
strict_ctxr  rR  r   s          r   r  z*InliningInstructionTranslator.inline_call_  s   &+#(,%{{$002
""55f6M6MNJ	2 
& +/*C*CF',1F);;""))##///>>V---##**4+@+@A((D,J,JJ(		$d+##//66t<44tCD22 T"t%KL,,!$(NOOO ++<<> 001D,,]DtL+++D!!$(NOOO++<<>>>+(("2"4 
 +++A $$ 	5dV3qcBCIIcN 	 !AL 	II*D1	 +/*C*CF',1F)sH   #J	 %I<6J	 <JJ	 	K2J::K2K$K22K5 5Lc                j   |j                         }|d   }	t        |	t              s|	j                  }	|j                  j
                  }
|
r|
j                  j                  |      nd }|%|j                  }|j                  }|j                  }n`t        |      }t        |       t        |      }t               D ci c]  }|t        ||       }}|
rt!        |||      |
j                  |<   t"        | I  |j                  i ||	||||||||j&                  |j(                  dz   |j*                  |j,                  |j.                  |j0                  |       || _        || _        |j6                  | _        d | _        |j:                  j=                         | _        |j>                  | _        y c c}w )N__builtins__)r  r  r  r   )r  r&  rA  rC  r|  r}  r~  r  r  r  r  r  r  r  r  r  r  r  ) get_globalsrH  r   __dict__r  rz  inlined_code_cacherK  r  r  r  r"   r!   r   r,   r  r   rH  rI  r  r  r  r  r  r  funcvarr	  r  r  r  r8  r  )r   r	  rd  r|  r}  r~  r  r  rA  rC  r  cachedr  r  r  r   rP  s                   r   rI  z&InliningInstructionTranslator.__init__;  s    '')	~.
*d+#,,J mm33=H//33D9d!..LnnG!..L/5L-!,/G9FIAAwtQ//ILI7G!-#!-8..t4 	==!+-*G"7%%==,,q0"22,,$66NN% 	 	
( ))#%55::<))C Js   <F0c                .    | j                   j                  S r   )r	  r{  r   s    r   r{  z'InliningInstructionTranslator.fake_modez  s    {{$$$r   c                \    t        j                  | j                  j                               S r   )r   r  r	  r  r   s    r   r  z)InliningInstructionTranslator.run_ctx_mgr~  s     ++DKK,E,E,GHHr   c                    t         j                  sy| j                  j                         sy| j                  j                         syy)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   s    r   rv  zAInliningInstructionTranslator._can_speculate_comprehension_nested  s9    
 ))||<<>{{779r   c                    t         j                  rD| j                  j                         sy| j                  j                         syt        |          S yr  )r   r  r  r  r	  r  rH  r   rP  s    r   r  z:InliningInstructionTranslator.should_compile_partial_graph  sC    %%<<@@B;;;;=7799r   c                d    t         j                  rt        |   ||      S t	        dddg        y )NzGraph break in inlined functionr   z2Graph breaks in an inlined call are not supported.r  )r   r  rH  r  r:   )r   r   r  rP  s      r   r  z3InliningInstructionTranslator.create_call_resume_at  s5    
 %%707PQQ5L		
r   c                F    | j                         | _        d | _        t        r   )r  r  r   r3  r  s     r   r  z*InliningInstructionTranslator.RETURN_VALUE  s    #xxz#' r   c                H    | j                  |      | _        d | _        t        r   )r>  r  r   r3  r  s     r   r  z*InliningInstructionTranslator.RETURN_CONST  s#    #//5#' r   c                2   d| j                   v r| j                   d   j                  d      sv| j                   d   }| j                  |      }d|v r(t        j                  j
                  j                  |   }nt        |      } t        | |      |      }t        ||      }n[| j                  j                  d| j                         }t        |      }| j                   } t        | |      |      }t        ||      }t        |      rt        |      }|||fS )Nr   namedtuple_rZ  ___unnamed_scope)rA  rX  rK  r  r  r_  r`  r   rd   rM   r  ru  rO   rN   rO  rS   )	r   r   rL  rM  rN  fglobals_vtglobal_sourceglobals_nameglobals_sources	            r   get_globals_source_and_valuez:InliningInstructionTranslator.get_globals_source_and_value  s    'z0J0U0U1
 ..4K ..{;M+-MM22LL#  "0!< ?/$>~NK&}d;M;;;;"DNNL *,7N!^^N @/$?OK-ndCM^$ ,M:M{M99r   c                   |j                   }|| j                  vr| j                  |      S | j                  j                  | j                  u rt
        |   |       y | j                  |      \  }}}| j                  j                  j                  ||      r6| j                  | j                  j                  j                  ||             y | j                  |   }| j                  t        j                  | ||             y r   )r  rA  rE  r  rc  rH  rI  r  r.  has_pending_mutation_of_attrr8  	load_attrrb   rG  )r   r   r   r   r  r  r  rP  s          r   rI  z*InliningInstructionTranslator._load_global  s    {{t~~%$$T**;;##t~~5 G &,0,M,Md,S)A{M{{''DD[RVW		$++22<<[$OPt,		///e]KLr   c                l   | j                   j                  | j                  u rt        |   |       y | j                         }t        |t              rt        d|j                  dg        |j                  }| j                  |      \  }}}| j                   j                  j                  |||       y )Nz3Storing Tensor hook handle in globals (inline call)rT  r  )r  rc  rA  rH  rX  r  rH  r   r:   r  r  r.  
store_attr)r   r   r  r   _fglobals_valuer  r   rP  s          r   rX  z*InliningInstructionTranslator.STORE_GLOBAL  s    ;;##t~~5 G &HHJE%!89Q KK 8	 ;;D.2.O.OPT.U+O[!KK$$//T5Ir   )
r	  r   r  ro   r   r  r  r{  r   rb   )r  ro   r   ztrace_rules.SkipResult)
r	  r   r  ro   r   r  r  r{  r   r  r  )r	  r   rd  r   r|  r{  r}  r{  r~  r   r  r   r  z7BaseUserFunctionVariable | LocalGeneratorObjectVariabler   r   r  r  r  r  r  )r   r   r   z#tuple[Any, VariableTracker, Source])r   r   r   r   r   r  r  r  r  r  r  rI  r  r{  r  rv  r  r  r  r  r  rI  rX  rQ  rR  s   @r   r  r    s   *..%%)) ') (	)
 +) 
) ) ?&?	? ?B CC&C (C +	C
 
'C CJK,Z=*)=* =* 4	=*
 5=* (B=*  3=* I=* 
=*~ % %I

 $=
 
	


(:(:	,(:TM"J Jr   r  c                  x     e Zd ZU ded<   d fdZd fdZddZddZddZd fdZ	d fd	Z
dd
ZddZ xZS )r  r  r  c                N    t        |   |i | g | _        d| _        d| _        y r  )rH  rI  r  r  r  )r   r   r  rP  s      r   rI  z/InliningGeneratorInstructionTranslator.__init__  s-    $)&)!#( -2*r   c                     t         j                   j                   fd      5  t                  cd d d        S # 1 sw Y   y xY w)Nc                      j                   S r   r  r   s   r   r   zEInliningGeneratorInstructionTranslator.inline_call_.<locals>.<lambda>  s    4CTCT r   )r  r  r  rH  r  r  s   `r   r  z3InliningGeneratorInstructionTranslator.inline_call_  s8     dkk;TU 	*7')	* 	* 	*s	   ?Ac                     yr  r   r   s    r   r  zCInliningGeneratorInstructionTranslator.should_compile_partial_graph  s    r   c                .   | j                         }| j                  j                  |       t        | j                        t        kD  rt
        j                  | j                  t               t        j                  s| j                  r|| _        t        y r   )r  r  r   r   rv   r   InfiniteGeneratorErrorr8  rg   r   r  r  r  r5  )r   r   tops      r   YIELD_VALUEz2InliningGeneratorInstructionTranslator.YIELD_VALUE  ss    hhj##C(t##$'99,,,		()5511#&D 	 2r   c                    | j                   d   }t        |t              sC| j                          t	        t
              j                  | |gi       }| j                  |       y y r  )r  rH  rz   r  rf   r  r9  r8  )r   r   r  ress       r   GET_YIELD_FROM_ITERz:InliningGeneratorInstructionTranslator.GET_YIELD_FROM_ITER  sN    jjn#34HHJ!$'55dSE2FCIIcN 5r   c                0    d| _         t        | 	  |      S rc  )r  rH  r  r   r   rP  s     r   r  z3InliningGeneratorInstructionTranslator.RETURN_VALUE$      #' w#D))r   c                0    d| _         t        | 	  |      S rc  )r  rH  r  r  s     r   r  z3InliningGeneratorInstructionTranslator.RETURN_CONST(  r  r   c                   t        | j                        dk\  sJ | j                         }| j                  d   }|j                         st	        dddg        	 |j                  |       }t        | j                  t              r| j                  dkD  sJ | xj                  dz  c_        | j                  |       | j                  |       y # t        t        j                  f$ rw}t        |t        j                        rt        j                  |        | j                          | j                  t        j                   |j"                               Y d }~y d }~ww xY w)	Nr  rn  Unreachable sub-generator coder   @Should only be encountered while implementing generator support.r  r   r   )r   r  r  r  r:   r  rH  r   r   r8  r  r  r   r  r  rh   r  r  r   r   r^  r  exs        r   
YIELD_FROMz1InliningGeneratorInstructionTranslator.YIELD_FROM,  s"   4::!###hhjjjn##% 8^		###D)C 433S9,,q01 $$)$IIcNT"# s<<= 	9"c;;<--d3 HHJII&--bhh788	9s   C E'A-EEc                   t        | j                        dk\  sJ | j                         }| j                  d   }t        |t        t
        f      s>t        |t              rrt        |j                  t        j                  j                        rD|j                         r$	 |j                  |       }| j                  |       y t-        dddg        y t-        dd	t/        |       d
t/        |       dg        y # t        t        j                   f$ rl}t"        j$                  dk  r| j                          | j                  t'        j(                  |j                               | j+                  |       Y d }~y d }~ww xY w)Nr  rn  rd  r  r   r  r  zSEND with bad typez
TOS type: z(Attempted to SEND with unsupported type rG  )r   r  r  rH  ry   rq   r   r  collectionsabcIteratorr  r  r8  r  r   r  rL  rr  rh   r  r  r:   r`   r  s        r   SENDz+InliningGeneratorInstructionTranslator.SENDR  s6   4::!###hhjjjnc,.JKLs56399koo&>&>?##%#++D1C IIcN < b	 ,$WS\N3Fws|nTUV	5 &s'D'DE 
$ '''1
II.55bhh?@IIdOO
$s   C; ;F A"E;;F )r   r   r  r   r   r   r  r  r  )r   r   r   r   rI  r  r  r  r  r  r  r  r  rQ  rR  s   @r   r  r    s7    **3***$#L*r   r  )r   r   r   ztypes.ModuleType)r   r=  )r   r   r   Generator[None, None, None])rD  zCallable[..., object]r   r  )rN  rU  r   r   )r^  r   r   r  r  )r   zdict[str, dict[str, Any]])r   r   r  Callable[[object], bool]r8  r   r   r   )r  r  r8  r   r   r>  )r   r   r  r2   r  r  r   r   )r8  r   r)  r   r   zYCallable[[Callable[..., None]], Callable[[InstructionTranslatorBase, Instruction], None]])r  r@   rd  r   r  zCallable[[], int]r   r  (  r   
__future__r   r  collections.abcrP  r8  r   r[  rB  r   r?  r  r  r   r  ro  rL  	threadingr  rf  rI  rC  r   typingr   r   r   r   r	   r
   r   typing_extensionsr   r  torch._loggingtorch._dynamo.dynamo_profilerr   r   torch._dynamo.excr   r   torch._guardsr   r   r   torch._logging.structuredr   %torch.fx.experimental.symbolic_shapesr   torch.utils._functoolsr   r   r   r   r   r  r   r   bytecode_analysisr   r   r    r!   r  r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   codegenr2   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   rL   r  rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   utilsrW   rX   rY   rZ   r[   r\   r]   r^   r_   variables.baser`   ra   rb   variables.builderrc   rd   re   variables.builtinrf   variables.constantrg   rh   variables.ctx_managerri   rj   rk   rl   variables.dictsrm   rn   variables.functionsro   rp   rq   rr   rs   rt   ru   variables.iterrv   variables.lazyrw   variables.listsrx   ry   rz   r{   r|   r}   variables.miscr~   r   r   r   r   r   r   variables.nn_moduler   r   variables.streamsr   variables.tensorr   r   variables.torch_functionr   r   variables.user_definedr   r   r   r   r   r   r   r   torch._subclasses.fake_tensorr   r  r   	getLoggerr   r  r  getArtifactLoggerr  r  r  r  r  rU  r   r9  r   r   containsr   r  r   r   cacher   	dataclassr   r   r   r   r  r  rQ  r  r  r   r  r   r  r3  r5  rE  rO  rb  rt  r  r  r  r  r  r  r?  r  rA  rT  r   r>  rr  _nb_opsr  r  r  r  r  )r   r   r   r   s   0000r   <module>rH     s,  0 #      
        	 
       Q Q Q $   R O C C / < /      " ' 
 
 
 ) / N N  : 	 	 	 ;
 
 
 G F R R . H  <   / /    Q 2 G  ==<'g!..228^L11(LI>>33HnM ^^55h@PQ ioo4R4L4R4R4T',0AqAq'''' ^  "("3"34BBX]]+99
 D ! H  !%&(y  ) )   < C C CL 
 
 
 2 2 23 3. 4 4 )!) ) )& $!$ $ $ ! ! !H	~ 		I 	9 A . .& $ $  > >B   ('
#'&' ' 
	'T BA&A.2A=AHR!R'0R;LR	RB}}"}}@J J4 _ _ _DO?;'O?;d~_5 _D	 w 
 FA	 	!#v-F12JWVABZL3I	
 :=:=
:= (:= !	:= :=zjJ$= jJZ-J Uy'lgs   $W $W