
    9j                   @   U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlmZmZmZmZmZmZ ddlm Z  ddl!Z!ddl"Z!ddl#m$Z$m%Z% ddl&m'Z'm(Z( dd	l)m*Z*m+Z+m,Z, dd
l-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6mZ7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN ddlOmOZO ddlPmQZQ ddlRmSZS ddl5mTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z] ddl^m_Z_ ddl`maZambZb ddlcmdZdmeZemfZf ddlgmhZhmiZimjZjmkZkmlZl ddlmmnZnmoZo ddlpmqZqmrZrmsZs ddltmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z| ddl8m}Z}m~Z~ ddlmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZmZ dd lmZmZ dd!lmZ dd"lmZmZmZmZ dd#lmZ dd$lmZmZmZmZmZmZmZ dd%lmZ dd&lmZ dd'lmZmZmZmZmZmZ dd(lmZmZmZmZmZmZmZ dd)lmZmZ dd*lmZ dd+lmZ dd,lmZmZmZ dd-lmZmZ dd.lmZmZmZmZmZ erdd/lmZmZmZ dd0lmZ dd1lmZ  ej                  eԫ      Ze!j                  j                  ed2      Ze!j                  j                  ed3      Ze!j                  j                  ed4      Ze!j                  j                  ed5      Z ej                         Z ej                         D  ci c]  \  } }|  e|      j                   c}} Zd6ed7<    eej                        j                  Z eej                        j                  Zd8 ed9<   d: ed;<   e9jd                  ez  ez  Zd<ed=<   e	j                  dpd>       Zej                   G d? d@             Zej                   G dA dB             Zej                   G dC dD             Zej                   G dE dF             Z G dG dH      Ze	j                  dqdI       Zej                  	 	 	 	 drdK       Zej                  	 	 	 	 drdL       Zej                   G dM dN             Z G dO dPe      Z G dQ dRe      Z G dS dTe      ZdsdUZdtdVZe	j                  dudW       Z	 	 	 	 	 	 	 	 dvdXZdYZdwdZZdxdyd[Z	 	 	 	 	 	 dzd\Z 	 	 	 	 	 	 	 	 d{d]Z	 	 	 	 	 	 d|d^Z G d_ d`e      Zej                   G da db             Z G dc dJ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TYPE_CHECKING	TypeAliasTypeVar)TypeIs)DynamoProfilerStateFunctionTraceTiming)ObservedExceptionTensorifyScalarRestartAnalysis)InlinedCodeCachetracingTracingContext)	dump_file)
guard_bool)cache_method   )configexcgraph_break_hintsloggingtrace_rules	variables)get_indexofJUMP_OPNAMESlivevars_analysispropagate_line_nums)cleaned_instructionscreate_binary_slicecreate_call_functioncreate_call_function_excreate_copycreate_dup_topcreate_instructioncreate_jump_absolutecreate_rot_ncreate_swapget_code_keysInstructionis_generatoris_jump_absolute	unique_id)code_context)	PyCodegen)%maybe_setup_comprehension_speculation)
!augment_exc_message_with_hop_nameBackendCompilerFailedcollapse_resume_framesformat_frame_infoget_stack_above_dynamoResumePrologueTracingErrorStepUnsupportedunimplementedUnsupported	UserError)get_funcname)GuardBuilderinstall_guard)GraphCompileReasonOutputGraphStackLocalsMetadata)impl_CONTAINS_OP_fallbackimpl_IS_MAPPINGimpl_MATCH_CLASSimpl_MATCH_KEYSimpl_MATCH_SEQUENCE)DummyModuleExecutionRecorder)ContinueExecutionCache"IS_TRACING_RESUME_PROLOGUE_VARNAMEReenterWith)
AttrSourceDictGetItemSourceGlobalSourceGlobalWeakRefSourceLocalCellSourceLocalSourceSkipGuardSourceSource)is_builtin_constantis_forbidden)	_get_error_on_graph_breakcountersget_fake_valueget_instruction_source_311get_metrics_contextgraph_break_dup_warning_checkeristype
LazyStringproxy_args_kwargs)typestrValueMutationNewVariableTracker)FrameStateSizeEntryVariableBuilderwrap_fx_proxy)BuiltinVariableDictBuiltinVariable)ConstantVariable)ContextWrappingVariableGenericContextWrappingVariableWithEnterFunctionVariableWithExitFunctionVariableConstDictVariable)BaseUserFunctionVariableLocalGeneratorFunctionVariableLocalGeneratorObjectVariableNestedUserFunctionVariableSkipFunctionVariableUserFunctionVariableUserMethodVariable)MAX_ITERATOR_LIMIT)LazyVariableTracker)BaseListVariableIteratorVariableListIteratorVariableListVariableSliceVariableTupleVariable)CellVariableExceptionVariableGetAttrVariableNullVariablePythonModuleVariableTracebackVariableUnknownVariable)NNModuleVariableUnspecializedNNModuleVariable)SetVariable)SymbolicStreamState)supported_comparison_opsSymNodeVariableTensorVariable)SymbolicTorchFunctionStateTorchFunctionModeVariable)RemovableHandleVariableUserDefinedClassVariable!UserDefinedExceptionClassVariable"UserDefinedExceptionObjectVariableUserDefinedObjectVariable)Callable	GeneratorSequence)FakeTensorMode)CompilePackagegraph_breaks
trace_calltrace_sourcetrace_bytecodedict[str, Any]compare_op_handlersc                2    t        | g t        |      i       S N)handle_containsreversedtxargs_s      ^/media/conek/DATA/Code/OCR/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bool | Noneerror_on_graph_breakzGraphCompileReason | None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
<    ej
                  e      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_grad	list[str]autograd_grad_leaked_tensorsgraph_break_on_requires_grad_c                    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   r   r     s     '8k&7&7&MG#ME3N */ $..?k.?.?PT.U )U +0!4/--%(-?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>e  s*      
%)QqcAHHJ< 
s   "$)joinr   itemsr   s    r   r   zLocalState.renderd  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   ^  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list[LocalState] | None
all_states)r   r   r   r   r  r   r   r   r  r  k  s    O*.J'.r   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.specializex  s    !!%%e,r   c                    || j                   v S r   )r  r
  s     r   should_specializez TensorifyState.should_specialize|  s    1111r   c                8    | j                   j                          y r   )r  r   r  s    r   r   zTensorifyState.clear  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  r  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_indexNz?ContextWrappingVariable | GenericContextWrappingVariable | None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,  rL   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   r2  zBlockStackEntry.exit  sG       ,,,t00DDF$$))"--r   r  )r   rL   )r   r   r3  r   r   VariableTracker | None)r   r   r   r   r(  r*  r/  r2  r   r   r   r%  r%    sH     TXLQX-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)ReturnValueOpNr6  r   r   r   r9  r9    r7  r   r9  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   r;  r;    s    r   r;  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)fnrC  rA  rB  s     @@r   stack_oprK    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_stdlibrU    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   rJ  z(get_assert_bytecode_sequence.<locals>.fn  s    OeO1r   c                    | sJ y r   r   rY  s    r   rJ  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   )rZ  r   r   r   )disget_instructionsr   r   	enumerater   )with_msgrJ  r   insts	begin_idxend_idxs         r   get_assert_bytecode_sequencerh    sr    		 &)%9%9"%=>TT[[>E> Vi&6VVIkk/*GQ1-- ?s   A/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truthrN  r   r   rh  instructionsr   r   r   argvalr>  rb   build)
r   truth_fnr>  current_instruction_pointerrd  assert_insts	cur_instsr   load_const_idx	error_msgs
             r   &_detect_and_normalize_assert_statementrv    s     	&4d..444"&":":! 3H=%%'*E,+ 
	 .77TT[[7	7$!-!3!3L!A --/.@&  .	IIo++D)<=!$  8s   -C#Fc                   | j                   j                  dd      xs t        | dd      }|sy|j                         j	                  d      }d}t        |      D ]'  \  }}|j                         j                  d      s&|}) |dk  ry||   j                         }d}|dz   t        |      k  r||dz      j                         }| |rd| z   S dz   S )	zIExtract the innermost user source location from an FX node's stack trace.stack_tracer   r   zFile r   r   z, code: )metagetgetattrstriprQ  rc  r^  r   )nsttrace_lineslast_file_idxr_  line	file_linecodes           r   get_node_source_infor  P  s    	
M2	&	G'!]B*GB((*""4(KM[) 4::<""7+M qM*002IDq3{++=1,-335[$xv.??B??r   c                  	 t        | t              sy	 | j                  j                  }g g t	               d
dd	fd	 	|       ssyg }t        t                    z   D ]$  }|j                  |       |j                  d       & ddj                  d |D              z   S # t        $ r t        j                  dd	       Y yw xY w)zWalk the FX graph backwards from a TensorVariable to show how it was
    computed, with user source locations. Graph inputs (placeholders) are always
    shown first, followed by operations in dataflow order ending at the branch
    condition.r   c                x    t        | t        j                  j                        r| j                  S t        |       S r   )rN  torchfxNoder   repr)as    r   fmt_argz0format_tensor_computation_trace.<locals>.fmt_args  s&    '588==9166FtAwFr   c                (   | j                   
v ry 
j                  | j                          t        |       }| j                  dk(  rUg }|r|j	                  d|        |j	                  | j                    d| j
                   d       	j	                  |       y | j                  dk(  rt              k  rt        | j
                  dt        | j
                              }dj                  fd| j                  D              }g }|r|j	                  d|        |j	                  | j                    d	| d
| d       j	                  |       | j                  D ]/  }t        |t        j                  j                        s( |       1 y y y )Nplaceholderz# z: graph input ()r?  r   z, c              3  .   K   | ]  } |        y wr   r   )r   r  r  s     r   r   z@format_tensor_computation_trace.<locals>.walk.<locals>.<genexpr>  s     $@AWQZ$@s   z = r   )r   r	  r  opr   r&  r   r|  r   r   r   rN  r  r  r  )r~  sourceblocktarget_nameargs_strr  r  	max_lines	op_blocksplaceholder_blocksvisitedwalks         r   r  z-format_tensor_computation_trace.<locals>.walkv  sM   vv KK)!,Ftt}$LL2fX/xqxxjBC"))%0tt&3y>I+E%ahh
CMJ99$@$@@LL2fX/xs;-q
!DE  '  A!!UXX]]3Q  ,F&r   z@

  The branch condition involves a tensor computed as follows:
r   c              3  &   K   | ]	  }d |   yw)    Nr   )r   r  s     r   r   z2format_tensor_computation_trace.<locals>.<genexpr>  s     <$$tf<s   z&format_tensor_computation_trace failedT)exc_info)r  objectr   r   )r~  torch.fx.Noder   r   )rN  r   proxynoder  r   r   extendr   r   	Exceptionr  debug)
valuer  r  	all_linesr  r  r  r  r  r  s
    `   @@@@@r   format_tensor_computation_tracer  c  s    
 e^,9{{ &(	.0E	G	  	 6 	T
!3  "	'$x	/B*CC 	!EU#R 	!
 Rii<)<<=	
  		:T	Js   ?B4 AB4 4 CCc                L     dd	 d	 	 	 	 	 	 	 	 	 dfdd fd}|S )Nc                   t        |       }g }t        | t              r	 | j                  j                  j
                  j                  d      }|_|j                         dk(  rL|j                  t        j                  t        j                  t        j                  fv r|j                  d       |j                  t         j"                         |j                  d       t%        dd|  d|z   |       y # t        $ r Y Qw xY w)	Nexample_valuer   zThe branch condition uses a scalar integer tensor. Consider rewriting the computation to use plain Python ints (e.g. use int attributes instead of tensor buffers) so the condition becomes a shape guard instead of data-dependent branching.z1Use `torch.cond` to express dynamic control flow.zData-dependent branchingzattempted to jump with zyDetected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.gb_typecontextexplanationhints)r  rN  r   r  r  rz  r{  dimdtyper  r   int32int64r   r  r  r   FUNDAMENTALr:   )r  
trace_infor  examples       r   raise_jump_graph_breakz,generic_jump.<locals>.raise_jump_graph_break  s    4U;
e^,++**//33OD'*

 LL4 	&223HI.-eW5DFPQ	
	  s   BC5 5	D D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/                  t1        d      g       t1        |j2                  |d   	      }	|	j5                  |       | j                  j/                  |	g|z   |z          y # t        t        f$ r}|}Y d }~d }~ww xY w)
Nr   r   zgeneric_jump triggered compilezgeneric_jump r   r   
stack_pops      TO_BOOLr   )r&  )should_compile_partial_graphr;   r<   maybe_has_backedgeraise_loop_graph_breakf_codelog_graph_breakcode_optionsr   r>  r  r  r   compile_subgraphr@   r`   frame_summarypopcreate_call_resume_atnext_instructionr&  rR  version_infoadd_output_instructionsr'   r   copy_positions)r   r   r  	extra_msgr   eall_stack_locals_metadataif_nextif_jump	jump_instr>  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 Y' 	C	s   G G,G''G,c                T   | j                         }t        j                  r`t        j                  j
                  dk(  rBt        |       r4| j                         }|j                         rmt        |j                               r| j                  |      S | j                         r | ||       y 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$        j0                        s|dk7  }t$        j2                  j4                  j6                  j9                  |      }|s(t        d
t;        |      dg t        j<                         | j                  |       y  | j                   j"                  d	t$        j>                  gt)        |fi        }tA        | |tC        |jD                  |             } | j                   j"                  d	t$        j&                  gt)        ||fi         | j                  |       y |j                         rt+        |tF              r>|jH                  r2tK        |jH                  jM                  tN        jP                                |j                               r%r| jS                  |       | j                  |       y y |j                         r| j                         r | ||       y t+        |tT              rS| j                   jW                  |jX                        } |      r%r| jS                  |       | j                  |       y y t+        |tZ              r	 |j]                  | d      }	t+        |	td        tf        f      r1|	ji                  | g i       }tk        tk        |	dd       dd       }
|j                         r|j                         }|
dk(  rCt+        |t              s3t_        jl                  tn        | dtq        |      jr                   g       t+        |t        tt        f      r |      rr| jS                  |       | j                  |       y t+        |t,              r5|jw                         rir| jS                  |       | j                  |       y t        dd|	 d| dg        y  d      r%r| jS                  |       | j                  |       y y y y y |j                         sW|jy                  |       rF t{        |j}                  |                   r%r| jS                  |       | j                  |       y y t+        |t,              r	 t+        |j.                  t$        j0                        r|jw                  | j                         }nt        |j.                  dk7        } |      r%r| jS                  |       | j                  |       y y t+        |t        j                        r. d      r%r| jS                  |       | j                  |       y y ddl$mC} |jH                  N ||jH                        r< |j                               r%r| jS                  |       | j                  |       y y  |       y # t^        j`                  $ r] t_        jb                  |        	 |j]                  | d      }	n0# t^        j`                  $ r t_        jb                  |        d }	Y nw xY wY w xY w# t^        j                  $ r*}| j                         r | ||d|       cY d }~S  d }~ww xY w)Nr   z>Data-dependent assertion failed (cannot compile partial graph)zvalue: zuDynamo has determined when encountering a data-dependent assert failure that it should not compile the partial graph.zUse `torch._assert()` to raise a hard AssertionError when the check fails. This error will propagate back the user code that called the compiled function (i.e. Dynamo will not trace any exception handling).zRemove the assert statement.zMove the assert statement outside of any context managers in order to graph break with partial graph compilation (if fullgraph=False).r  r?  z#Assertion failed on symbolic shapesr   )r  __bool____len__rJ  r   z&__bool__ should return bool, returned r   z3Data-dependent branching with non-constant __bool__zmethod: z
, result: z}Attempted to perform data-dependent branching on a user-defined object with a __bool__ method that did not return a constant.Tr   )r  r   )is_constant_source)Er  r    rewrite_assert_with_torch_assertrR  flagsoptimizerv  is_python_constantr   as_python_constantjumpr  r:   r   r  	is_tensorr   create_proxyr  _assert_asyncr_   rN  r   sym_numSymBoolr  experimentalsymbolic_shapesexpect_truer   
USER_ERRORscalar_tensorre   rY   r  rn   r  r?   
make_guardr>   SEQUENCE_LENGTHr>  r   get_submodule
module_keyr   var_getattrr   ObservedAttributeErrorhandle_observed_exceptionr   ru   r?  r|  raise_observed_exception	TypeErrortyper   r   evaluate_exprhas_unpack_var_sequencer   unpack_var_sequencer   r<   r   BackwardHookVariabler  get_real_value)r   r   r  ru  sym_exprresultscalar_to_tensor_proxyscalar_to_tensorrT  rZ  method_nameresult_valueeval_resultr  r  r  r>  r  rp  s                  r   innerzgeneric_jump.<locals>.inner  s   !%33		""a'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 !o/ABCr26%gat&<j$O,,.#)#<#<#>L"j0LRV9W44% "HlI[IdIdHe f" ",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-i -- --d3))$	:A11 11$7A| == 446+D$2aSRRs[   =[7  A]* 7(]' \32]'3*] ]']  ]'&]'*^'=^"^'!^""^')r  rb   r   r   )r   )
r   r   r   r,   r  rb   r  r   r   r   r   r   r   r,   r   r   r   )rp  r>  r  r  r  s   `` @@r   generic_jumpr    s\    !
N 	7M'7M7M 7M 	7M
 
7M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_stackrN  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     13H/1F

 
 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        t
        f$ rd}| j                  rg| j                  s| j                  r t        |t              r|j                          t        dd| j                   ddgt        j                  |       t        |dd      r | j                         s | j!                         r| j#                  | j$                  |       | j'                  | j(                   dt+        |       |	       t        |t              r!|j                          |j-                  d
       t/        t        |dt+        |            t        |d| j1                         g            |_        Y d }~nd }~ww xY w	 || _         n# || _         w xY w|j3                  | 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_exc
skip_frameFz:

r  graph_breakrX  
real_stack)current_instruction_push	speculater   r   r;   r<   active_generic_context_managers	one_graphr   rN  remove_from_statsr:   r   CAUSED_BY_EARLIER_GRAPH_BREAKr|  r  r  r  r  r  r  r   add_to_statsr@   r  r   )	r   r   	prev_pushspeculationexcphandle_graph_breakinner_fn
msg_prefixr>  s	        r   wrapperz>break_graph_if_unsupported.<locals>.decorator.<locals>.wrapper  s   55I,0D)..*K!!$'"))555)$k6H6HII.:d+Z 1:-Y  + *77~~)B)B "$4..0! R"CDDhDhCi j %Dc.LL "&	 4u588:**,//TB$$%%(\s4yk: %  dK0**,%%m4%7D%T3D,1C1C1E0FG&""O*N #
 1:-	-11$2K2KLs+   A) )G9EGG) GG) )	G2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r     r     CALLPRECALLz%s triggered compiler  r   r   r  KW_NAMESrn  Fry  ) rR  r  r   ra  stack_effectopmapargopcoder  r  r   r  r   r1   root_txr  r  rb  kw_namesr  r   r'   r#   r  r&  copyexn_tab_entryr@  r>  r   r  r  )r   r   r   r0  r  r  r  r5  
call_insts	inst_copyr>  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   )rH  rI  )r$  r&  r#  r%  r>  s   ` @r   	decoratorz-break_graph_if_unsupported.<locals>.decorator  sT     
	"7	M 
#7	Mr<	+<	<	 '<	 	<	| r   )r$  Callable[..., None]r   8Callable[[InstructionTranslatorBase, Instruction], None]r   )r>  r%  r:  s   `` r   break_graph_if_unsupportedr=    s$    
{%{	A{z 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>._missingr  sS    2!(+dV4[\b[ccef;F8 D_ _ '22		r      )r   r   r   r   r   r   )super__init__ra  r1  r   r|  rH  partialranger{  dispatch_table)
r  r   basesdctrD  r   r  rJ  r_  	__class__s
            r   rG  z"BytecodeDispatchTableMeta.__init__o  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   rK  r   rL  r   r   r   )r   r   r   r   rG  __classcell__rM  s   @r   r?  r?  l  s    ^J Jr   r?  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ExceptionVals | None_current_exceptionc                    d | _         y r   rT  r   s    r   clear_current_exceptionz&ExceptionStack.clear_current_exception  s
    "&r   c                4    | j                  |       || _        y r   )._set_context_and_break_context_reference_cyclerT  r   vals     r   set_current_exceptionz$ExceptionStack.set_current_exception  s    ;;C@"%r   c                v    | j                   J | j                  | j                          | j                          y r   )rT  r   rW  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   rV  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  r9| j                  |   }| j                  ||dz
         ||ur|j                  |       |S Nr   r   )__context__r  rh   r   rR  _set_context_recursiveset_context)r   r[  prev_idxctxprevs        r   rd  z%ExceptionStack._set_context_recursive  st     ??"C"S	9I(IJt(*Q.??8,D''hl;3%
r   c                    |x}}d}	 |j                   }t        |      t        u ry ||u r%|j                  t        j                  d              y |}||u ry |r|j                   }| }`r  )rc  r  rh   re  create)r   r[  oslow_oslow_update_toggler  s         r   _break_context_reference_cyclez-ExceptionStack._break_context_reference_cycle  s    
 F"mmGG} 00#~.55d;<AF{ !++%7!7% r   c                v    | j                  |t        | j                        dz
         | j                  |       y Nr   )rd  r   rR  rn  rZ  s     r   rY  z=ExceptionStack._set_context_and_break_context_reference_cycle  s0     	##CT__)=)AB++C0r   c                6    | j                   j                         S r   )rR  r  r   s    r   r  zExceptionStack.pop  s    ""$$r   c                :    | j                   j                  |       y r   )rR  r   rZ  s     r   r   zExceptionStack.append  s    s#r   c                ,    t        | j                        S r   )r   rR  r   s    r   r  zExceptionStack.__len__  s    4??##r   c                     | j                   |   S r   )rR  )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=)rR  rT  r   s    r   __str__zExceptionStack.__str__  s"    "$//##?t'>'>&@AAr   r   )r[  r   r   r   )r   r   )r[  r   rf  r   r   r   )r   r   )r   r   r   r   r   )r   r   r   r   r   r   r   rR  r   rT  rW  r\  r^  r`  rd  rn  rY  r  r   r  ru  rw  __repr__r   r   r   rQ  rQ    s     '8k&7&7&MJ#M/@{/@/@/N,N'&'
'
 
,/
	
861 1	1%$$&B Hr   rQ  c                  n    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dd>Zdd?Zdd@Zej$                  dAk\  rddBZnddCZeddD       ZddEZddFZddGZd dHZddIZddJZddKZddLZddMZddNZddOZ ddPZ!ddQZ"eZ#ddRZ$ddSZ%ddTZ&e'jP                  ddU       Z)ddVZ*ddWZ+e,ddX       Z-ddYZ.ddZZ/dd[Z0e0Z1dd\Z2e,dd]       Z3dd^Z4d	d_Z5e5Z6e5Z7 e8e9jt                  d`      Z; e8e9jx                  d`      Z= e8e9jt                  da      Z> e8e9jx                  da      Z?ddbZ@ddcZAdddZBddeZCddfZDddgZEd
dhZFddiZGddjZHddkZIddlZJddmZKddnZLddoZMddpZNddqZOddrZPddsZQddtZRdduZSddvZTddwZU eVdadxy      ddz       ZW eVdad{y      dd|       ZX eVdad}y      dd~       ZYddZZddZ[ddZ\ddZ]ddZ^ddZ_ eVd`dy      dd       Z`ddZaddZbec	 	 	 	 	 	 dd       Zd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZe	 	 	 	 	 	 ddZfec	 	 	 	 	 	 	 	 dd       ZgddZh eVd`dy      dd       ZiddZj	 	 	 	 	 	 ddZkddZlddZmddZnddZoddZpeqfddZrddZsesZtddZuddZvevZwddZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZ eVd`dy      dd       ZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZeZddZddZddZddZddZddZddZddZ ee9j8                        Z ee9j<                        Z ee9jt                        Z ee9jB                        Z ee9jF                        Z ee9jJ                        Z ee9jN                        Z ee9jR                        Z ee9jV                        Z ee9jZ                        Z ee9jZ                        Z ee9j`                        Z ee9jd                        Z  eVdady       ee9jh                              Z ee9jl                        Z ee9jp                        Z ee9jt                        Z ee9jx                        Z ee9j|                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        Z ee9j                        ZddZej$                  dAk\  rddZddZddZddÄZߐdddĄZ eVdadŬy      ddƄ       ZddǄZddȄZe5Ze5Z e8e9jx                  d`      Z e8e9jx                  d`      Z e8e9jt                  d`      Z e8e9jt                  d`      ZddɄZddʄZ	 	 	 	 	 	 dd˄Zecdd̄       Zdd̈́Zdd΄ZddτZddЄZddфZdd҄ZddӄZddԄZddՄZddքZddׄZdd؄Z eVdad٬y      ddڄ       ZddۄZdd܄Zdd݄ZddބZdd߄ZeZ eZeZdZddZddZdZdd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	 	 	 	 	 	 	 	 d#dZ	 	 	 	 d$dZ	 	 	 	 	 	 	 	 d%dZec	 	 	 	 	 	 d&d       Z	 	 	 d'	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d( fdZ xZS ()  r   rA   r   dict[str, VariableTracker]symbolic_localssymbolic_globalsr   symbolic_torch_function_stater   symbolic_stream_statez!dict[str, VariableTracker] | Nonepost_prune_cell_and_freevarslist[VariableTracker]stack
int | Noner   r,   current_instructionr   r  zlist[BlockStackEntry]r  r   r   zConstantVariable | Noner5  accept_prefix_instlist[Instruction]prefix_instsinline_depthinconsistent_side_effectszSpeculationEntry | Nonecurrent_speculationz	list[Any]rJ  rQ  exn_vt_stackzExecutionRecorder | Noneexec_recorderz(Callable[[VariableTracker], bool] | Nonestrict_checks_fnstart_pointhas_no_inlined_callsz InstructionTranslatorBase | Noner  is_child_tracer_activez3list[tuple[VariableTracker, list[VariableTracker]]]debug_localsCompilePackage | Nonepackagez
deque[str]latest_bytecode_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   rm  r   r   rn  r  )r   r  
cur_offsetr   jump_offsets        r   r  z,InstructionTranslatorBase.maybe_has_backedge  s    * 48 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.cellvars9        //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   rm  r  )r   r   r   readss       r   prune_dead_localsz+InstructionTranslatorBase.prune_dead_localsD  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   )rN  rb   )r   rZ  s     r   r   z:InstructionTranslatorBase.call_function.<locals>.<genexpr>Z  s      
 q/*
   r  rJ  z$Attempt to trace forbidden callable )rN  rb   r   r   all	itertoolschainvaluesr-  r  rJ  callablerV   AssertionErrorr>  r?  )r   rJ  r   kwargsr$  s        r   r?  z'InstructionTranslatorBase.call_functionQ  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"
        )rN  rp   r?  r   rJ  r   r  s       r   inline_generator_functionz3InstructionTranslatorBase.inline_generator_functiong  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_returnt  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   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_header  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   r  )r  	linecachegetliner  r  r   rstrip)r   log_strr  s      r   get_log_starts_line_log_strz5InstructionTranslatorBase.get_log_starts_line_log_str  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   starts_linez%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        tJ        f$ r}| jL                  s%| j                  s| jN                  stQ        |d	d      r2tS        |tJ              r!tU        d
ddddgtV        jX                          | j                  OtZ        j                  d       tS        |tJ              r"tU        dddddgtV        jX                  d       d|_.         dt_        |       }| ja                  | jb                  ||       Y d}~nd}~ww xY w| j                  je                  | 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  Tr  z3cannot resume from torch._dynamo.step_unsupported()r   ztraced torch._dynamo.step_unsupported(), but Dynamo is instructed to error on graph break. This graph break is used for debugging only.z1Remove the torch._dynamo.step_unsupported() call.z9Make sure fullgraph=False and error_on_graph_break=False.r  z1empty checkpoint - cannot resume from graph breakz6torch._dynamo.step_unsupported() with empty checkpointztraced torch._dynamo.step_unsupported(), but there is no checkpoint to step_graph_break from. This graph break is used for debugging only.zInclude at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some line of code that is not in a try/with block, and has an empty Python stack.)r  r  r  r  r  zEncountered graph break that we cannot resume from. Compiling up to the previous resumable state, then skipping the rest of the function. Graph break encountered:

r  )3rW   r   r   rm  r  r  r  r  is_non_empty_graphr  r  r   step_graph_breakis_trace_bytecode_log_enabledtrace_bytecode_logr  r   rn  r  r   verbose
ValueErrorr  r   update_block_stackrJ  r3  r   r!  r   r   r   exception_handlerr9  r;  r;   r<   r9   r  is_tracing_resume_prologuer|  rN  r:   r   
DYNAMO_BUGr  r  r   r  r  r   )r   ipr   
stack_reprr  r   s         r   stepzInstructionTranslatorBase.step  s"   $=$?!%%:*.*;*;B*?? 4#%6 T--. 

113'')'+~~'7D$''..t4%%d+--$$ $++t{{D<L >>P!$**-
 &&--QtDKK'8&9:,G 	%A	,D,T48{{....  PO
P . 	$$ 	""1%|, 	Y8 7	 ,,221lE2a1! U "%` PW /99
 ''/		MNa1! X "%a Pk /99	 $(  $/ 031vh8    !! !  g7	r 	  ::4;T;TUs=   0G 6G  GG L-<HL-&L-9C*L((L-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   ry  )NOPJUMP_BACKWARD	NOT_TAKENr   )r7  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   rm  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                  rJd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  rp|j!                  g t#        d      |j%                  d      |j'                         t3        |d       t#        d      |j%                  d      t)        d             |j!                  t)        d|dz   	      t)        d|dz   	      t)        d|dz   	      g       | j                   j;                  |j=                         | j                  j?                  | j                  j@                  |dd        z          y | j                   j;                  g t5        d      t)        d             t        | j                   j                        }| j                   j;                  |j%                  d      |j'                         g       |d   jB                  jE                         D ]X  \  }	}
| j                   j;                  tG               |j%                  |
      |j'                         |jI                  |	      g       Z | j                   j;                  t)        d      tK        |      g| jL                         y )Nzstep triggered compilestep_unsupported)r   r   )	skip_coder  r   
BUILD_LISTr2  TFDELETE_SUBSCRr  LIST_APPENDSTORE_SUBSCRUNPACK_SEQUENCEPOP_TOPry  )'r   output_instructionsr  r  r  r  r  r@   r  r  
eval_framer  r   nested_graph_breaksr1   r4  r  r%   create_load_constcreate_binary_subscrr'   create_resumer  codegen_call_resume	num_stackr"   r*   r>  r   r  rb  r  r  locals_namesr   r&   create_storer(   rm  )r   continue_instr  r  r  leaf_resume_codeleaf_resume_namer  r  localidxs              r   r  z*InstructionTranslatorBase.step_graph_breakE  s9   ;;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                  jY                          t)        | t.              r5| j                  j[                          | j                  j]                          	 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*        t,        f      rTt)        | t.              rD| j0                  s8| j2                  s,dt        |       }| j5                  | j6                  ||       t)        |t8        j:                        s$| j                  j<                  j?                          tA        |d      rpd|jB                  v rbtD        jF                  jI                  | j                  jJ                  | j                  jL                        jO                  ddd	      }||_(          d }~wt        $ ro}| jR                  r| jR                  jU                         |_+        t)        |t8        j:                        s$| j                  j<                  j?                           d }~ww xY w# | j                  jY                          t)        | t.              r5| j                  j[                          | j                  j]                          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  rX  zData-dependentFT)print_outputinclude_strideinclude_device)/r  r   r  r  r   push_txr   r  r  r  r  r8   r  r   r   with_traceback__traceback__r   r4   RuntimeErrorrN  r;   r<   rD  r   r  r  r  r   RestartAnalysisside_effectslog_side_effects_summaryr-  rX  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    L	=dkk--.J=##D)#'#;#; 
))+ ))+t ""$ d$9:KK'')
 KK::<YL	= L	= ! 668_#Aw334Bs1vh@ ).9t	D
  2 (  # q;	":;"4)>? 55 NN77:1vh@ 
 (())% )  "!S%8%89KK,,EEG1e$)9QUU)B%*XX%9%9..0A0A&$n%*4PT %  #
 *8A& %%$($6$6$A$A$CAM!!S%8%89KK,,EEG ""$ d$9:KK'')
 KK::< ;ML	= L	=si    M1,E!C)AM1)	E2AEEEL
*D%JL
A*LL

LA!M..M11M:c                    t        |t              sJ dt        |              | j                  j	                  |       y )Nz"push expects VariableTracker, got )rN  rb   r`   r  r   rZ  s     r   r>  zInstructionTranslatorBase.push]  s;    #/ 	
0?	
/ 	

#r   c                4    |D ]  }| j                  |        y r   )r>  )r   valsr[  s      r   	push_manyz#InstructionTranslatorBase.push_manyc  s     	CIIcN	r   c                6    | j                   j                         S r   )r  r  r   s    r   r  zInstructionTranslatorBase.popg  s    zz~~r   c                p    g t        t        |      D cg c]  }| j                          c}      S c c}w r   )r   rI  r  )r   r~  r   s      r   r@  zInstructionTranslatorBase.popnj  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)NrM  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)rn  r  f_localsadd_local_varr>  r{  unwrapKeyErrorr^  replacer:   r   r  r  )r   r   r   new_names       r   	LOAD_FASTz#InstructionTranslatorBase.LOAD_FASTm  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   )
rn  r  r{  r   r  	load_cellr>  r  r$  r%  )r   r   cellcontents_vars       r   
LOAD_DEREFz$InstructionTranslatorBase.LOAD_DEREF  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   )	rn  r  set_name_hintr{  rK   r  r  r   r  )r   r   r   	loaded_vtr[  s        r   
STORE_FASTz$InstructionTranslatorBase.STORE_FAST  sj    {{HHJ	%%.T"55..0C9$$$.1D+ 6r   c                    | j                   j                  |j                        }t        |t              r| j                  |       | j                   |j                  = y r   )r{  r{  rn  rN  r   _maybe_emit_sync_dealloc)r   r   vars      r   DELETE_FASTz%InstructionTranslatorBase.DELETE_FAST  sF    ""&&t{{3c>*))#.  -r   c                ^   ddl m}m} |j                  }||j                  dvry |j
                  j                  }|j                  j                  di       j                  dd       }t        |j                  j                               }|sy d }| j                  j                  j                  D ]	  }	|	|v s|	} ||j                  dk(  ry |j                  j                  di       j                  dd       }
||
k(  ry | ||      }|
 ||      }
 |       }| j                  j!                  dt"        j$                  j&                  j(                  ||
fi        | j                  j!                  dt"        j$                  j&                  j*                  |||j-                         fi        y )Nr   )get_current_stream	new_event)cudaxpucustomstreamr   r?  )variables.streamsr9  r:  devicer  r  r  rz  r{  r  userskeysr   r  nodesr  r  r  opsstreamsrecord_eventsync_deallocas_proxy)r   r6  r9  r:  r@  r  alloc_streamrA  	last_userr~  last_use_stream	event_idxs               r   r5  z2InstructionTranslatorBase._maybe_emit_sync_dealloc  su   D>V[[?yy~~yy}}Xr266xFDJJOO%&	""(( 	AEz		 	 8#..,,Xr:>>xN?*-f5L"08OK	  II**(		
 	  II**clln5		
r   c                R   |j                   | j                         v sJ | j                  |j                      }| j                         }| j                  j
                  j                  ||       t        |t              sJ |j                  |j                  |j                         y y r   )rn  r  r{  r  r   r  
store_cellrN  r~   
local_namer1  )r   r   r-  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 )Nr  )r2  rh   rj  rn  _constants_cache)r   r   r_  r[  s       r   _load_constz%InstructionTranslatorBase._load_const  sv    HH9#**==##A&'7'>'>T[['QD!!!$''*C
r   c                D    | j                  | j                  |             y r   )r>  rT  r  s     r   rj  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   )rn  r  	f_globalsadd_global_var
f_builtinsbuiltinsload_builtinr|  r   r  r>  load_globalrb   ro  rO   )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   ro  )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  )r2  rR  r  	PUSH_NULLr^  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  rn  rO   r|  r  r   r  track_global_existingrN  r   r:   store_global)r   r   r  r   r  r]  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   <rM  _dot_	__import_)r  r  package_importer_package_imported_modulesr(  r   add_import_sourcer   import_sourcesglobal_scopeupdate_co_namesrO   )r   ra  r  aliasrW  s        r   r`  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
        rM  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)r  )
stacklevelzYcan't resolve package from __spec__ or __package__, falling back on __name__ and __path__r   __path__rM  r   )rW  r{  r  r  warning
rpartition)r   r  specs      r   calc_packagez&InstructionTranslatorBase.calc_packageI  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   )fromlistr}  globalszImport failurezmodule_name: z, fromlist: z, level=z"Failure when attempting to import.r  r   rM  r  zBad import resultz%Import result is not a Python module.)r@  r  rn  rI   LOCAL_MOD_PREFIXrW  rO   
__import__r|  r:   r   r  r  r  	partitionr`  r  add_local_modrN  rO  rP  rH   r>  r   r`   )
r   r   r}  r  ra  recorded_namer  r  pkgtop_level_module_names
             r   IMPORT_NAMEz%InstructionTranslatorBase.IMPORT_NAMEf  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 ee..<=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_attrrn  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  )rY  r:   r   r  r  rO   r   %name_of_builtins_dict_key_in_fglobalsrN   rb   ro  rU   )r   rn  r[  builtins_source
var_sources        r   load_builtin_from_argvalz2InstructionTranslatorBase.load_builtin_from_argval  s    (?3F8;QR&11	 oof%C=*AAO +?FCJ"((sJ??&s+++"((s33r   c                X    | j                  | j                  |j                               y r   )r>  r  rn  r  s     r   r[  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                         j                         }| j                  |       	 |j                  |       }| j                  |       y # t        t
        j                  f$ r}t        |t
        j                        rt        j                  |        t        j                  dk\  r%| j                  t        j                  d              n| j                          | j                  |       Y d }~y d }~ww xY wNr*  )r  realizer>  next_variableStopIterationr   ObservedUserStopIterationrN  r  rR  r  rh   rj  r  )r   r   itr[  r  s        r   FOR_ITERz"InstructionTranslatorBase.FOR_ITER  s    XXZ!		"	""4(CIIcNs<<= 	!S::;--d37*
 		*11$78 
IIdOO	s   "A C?-BC::C?c                l    t        |t        j                  t        f      r|j	                  | g i       }|S r   )rN  r   rf   r   r?  rZ  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        j                  | d      |gi        y )Nr
  __setattr__)	r  r  rN  rh   r   from_frame_summarycall_methodrb   ro  )r   r   r  tbnew_tbs        r   _attach_traceback_to_exceptionz8InstructionTranslatorBase._attach_traceback_to_exception
	  s    **,S__

 !#45
 	
 
 #55mRH""496B	
r   c                   | j                  |      }t        | j                        rWt        |t        j
                        r=|j                  t        u r+t        j                  | t              j                  | g i       }| j                  |      r:t        |dd       -t        j                  j                   j#                         |_        | j                  |      rb| j&                  j)                  |       t+        j,                  |j                        }t        |dd       } |d|j/                          |      t+        j0                  t2        | d|j5                          g       y )Npython_stackraised exception )r  z/exceptions must derive from BaseException, not r  )r  r-   r  rN  r   r   exc_typer  rb   ro  r  r?  _isinstance_exceptionr|  r  _guardsr   extract_stackr  r  r\  r   get_dynamo_observed_exception
debug_reprr  r  python_type_name)r   r[  observed_exception_typer  s       r   _raise_exception_variablez3InstructionTranslatorBase._raise_exception_variable	  s2    ))#.
 %3	 ; ;<-!''l;II$PRTVWC &&s+^T2:$}};;IIKC %%c*33C8&)&G&G&U#"3=L)#CNN$4#56<  	$$A#BVBVBXAYZ	
r   c           
     D   |j                   dk(  rt        | j                        st        j                  t
        | d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                  | dt        j                  | d      |gi        y # | j                  j                         }| j                  |       w xY w# | j                  j                         }| j                  |       | j                  |      }|j                  | dt        j                  | d      |gi        w xY w)Nr   zNo active exception to reraiser  ry  r   r  	__cause__)r2  r   r  r   r  r  r  r  r  r`  r  r  r  r  rb   ro  )r   r   r[  curr_excfrom_vtcauses         r   r`  z'InstructionTranslatorBase.RAISE_VARARGSN	  s   88q=t((),, $.N-O t(()))##B'C--c27C72**3/XX]**R.C>..s3  ,,BBD33H= hhjG((*C..s3  ,,BBD33H=33G<$$!$**4=uE	  ,,BBD33H=  ,,BBD33H=33G<$$!$**4=uE	s   1F F7 -F47A(Hc                    | j                   d   }t        |t              sJ |j                  t        u rt        dddg        y | j                  |       y )Nry  z CLEANUP_THROW with StopIterationr   zRReceived StopIteration when handling generator.throw/close. This is not supported.r  )r  rN  r   r  r  r:   RERAISEr   r   toss      r   CLEANUP_THROWz'InstructionTranslatorBase.CLEANUP_THROWv	  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(  )rR  r  r  rn  r  r>  )r   r   r[  r   _exc_tbs         r   r  z!InstructionTranslatorBase.RERAISE	  s     w&((*C{{HHJ..s3 		#..s388:D((*C((*C**3/r   c                "    t        |t              S r   )rN  r   rZ  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(  r           ry  r
     ir  )rR  r  r   r  r  rf   r  r  rN  r   r   r?  )r   r   r   fn_locrJ  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\  rL j                  j                  }|rt	         j
                        |j                  kD  r3 j                          t	         j
                        |j                  kD  r3|j                  r9 j                  t        j                    j                  j                                j                   j                  j                                 j                  |       y  j
                  j!                           j                  j                         } j#                  |       t%               t&        u r |        t	         j(                        rF 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                  tE        jF                                 j                  |        j                  tE        jH                  |jJ                               nl j                  tM        jN                  d               j                  tM        jN                  d               j                  tM        jN                  d               j                  tE        jF                                 j                  |        j                  tE        jH                  |jJ                                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                          g t        j                  t        j                         y )NzObserved exceptionr  r  )r  r`  r   r  python_typerN  r:   r  r   r  rC  )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,?,?,A+BC7&11&22 *	r   r(  EXCEPT_HANDLERr  r   z#Observed exception (EXCEPT_HANDLER)z  This graph break is unexpected.r  g    .Ar  r  r   )(rR  r  r  r7  r   r  depthr  lastir>  rb   ro  r  r  r`  r  r   r  r  rD  r  r   r   r@  r:   r   r   r  r^  r'  r,   r   r   r%  r   r   rf   r  rh   rj  )
r   r  r  r7  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'--dD4L4L4S4ST
 		$++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 II.55d;<II.55d;<II.55d;< 		)3356		-(		)33M4J4JKL 		+, 

  ":!6635&&r   c                   | j                         }t        | j                        dk(  rt        j                  d       }n| j                  d   }| j                  |       | j                  |       | j                  j                          y )Nr   ry  )r  r   r  rh   rj  r>  r^  )r   r   r[  prev_excs       r   PUSH_EXC_INFOz'InstructionTranslatorBase.PUSH_EXC_INFOG
  sk    ( hhjt  !Q&(8(?(?(EH((,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   ry  r  zYBug in Dynamo tracing of exception handling.Top of the block stack is not EXCEPT_HANDLER.r  )
rR  r  r  r   r  r  r   r   r  r@  )r   r   r   s      r   
POP_EXCEPTz$InstructionTranslatorBase.POP_EXCEPTd
  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(  ry  z Exception with bad expected typez"`except ...` has unsupported type rM  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  rR  r  rN  rf   r}   r   r   r:   r   r   r  r  r   
issubclassr  rJ  r   )r   expected_exc_typesexc_instanceexpected_typesexpected_types        r   check_if_exc_matchesz.InstructionTranslatorBase.check_if_exc_matchesy
  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                j    | j                  t        j                  | | j                                      y r   )r>  rb   ro  r  r  s     r   CHECK_EXC_MATCHz)InstructionTranslatorBase.CHECK_EXC_MATCH
  s$    		/''d.G.G.IJKr   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  )rn  r  r>  r   r@  r  s     r   
COMPARE_OPz$InstructionTranslatorBase.COMPARE_OP
  sD    ;;++  &II)$++6tTYYq\2NOr   c                x    | j                  t        j                  | t              | j	                         gi        y r   )r?  rb   ro  iterr  r  s     r   GET_ITERz"InstructionTranslatorBase.GET_ITER
  s)    ?00t<txxzlBOr   zjEncountered graph break when attempting to trace CALL_FUNCTION: a call to a regular function, e.g. f(x, y))r>  r%  c                    | j                  |j                        }| j                         }| j                  ||i        y r   )r@  rn  r  r?  )r   r   r   rJ  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)rn  rn   r  rR  r  rN  r   r:   r   r  rx   has_force_unpack_var_sequencer}   force_unpack_var_sequencer   rg   call_custom_dictr   r`   r  keys_as_python_constantr?  r   )r   r   
kwargsvarsargsvarsnullrJ  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";<,==dD*UJ ($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@  rn  rN  r}   r  r  r   r   zipr?  )r   r   argnamesr   rJ  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  r/  r   co_namesr(  )	r  r   r(  rn  r  rR  r  r  LOAD_METHODr   r   r2  rn  s       r   LOAD_METHOD_SUPERz+InstructionTranslatorBase.LOAD_METHOD_SUPER5  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  r/  r   r  )r  r   r(  rn  r  r  r  s       r   LOAD_ATTR_SUPERz)InstructionTranslatorBase.LOAD_ATTR_SUPER>  sK    ;..tA>?kk!n"":.s3r   c                F   | j                  |j                         | j                         }t        j                  dk\  r#| j                  |       | j                  |       y t        j                  dk\  r#| j                  |       | j                  |       y t        d      )Nr  r(  zPLOAD_METHOD should have been rewritten to LOAD_ATTR. We should never reach here.)r  rn  r  rR  r  r>  rf  r  r   r   objs      r   r  z%InstructionTranslatorBase.LOAD_METHODD  sy    $hhjw&IIcNNN4 ( NN4 IIcN b r   c                    t        d      )Nz^CALL_METHOD should have been rewritten to CALL_FUNCTION. This function should never be called.)r  r  s     r   CALL_METHODz%InstructionTranslatorBase.CALL_METHODU  s    l
 	
r   c                    | j                         }t        j                  | t              j	                  | |t        j                  | |      gi       }| j                  |       y r   )r  rb   ro  r|  r?  r>  )r   attrr$  r  s       r   r  z$InstructionTranslatorBase._load_attrZ  sS    hhj &&tW5CC/''d34

 			&r   c                    t         j                  dk\  r!|j                  dz  r| j                  |       y | j	                  |j
                         y )Nr*  r  )rR  r  r2  r  r  rn  r  s     r   	LOAD_ATTRz#InstructionTranslatorBase.LOAD_ATTRc  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        j                  | t              j	                  | |t        j                  | |j
                        |gi        y )Nr  )r@  rb   ro  setattrr?  rn  )r   r   r[  r$  s       r   
STORE_ATTRz$InstructionTranslatorBase.STORE_ATTRk  sQ    
 99Q<SdG,::/''dkk:C@	
r   c                    | j                         }| j                  ||j                         t        j                  | t
              j                  | |t        j                  | |j                        gi        y r   )r  _maybe_sync_dealloc_attrrn  rb   ro  delattrr?  r#  s      r   DELETE_ATTRz%InstructionTranslatorBase.DELETE_ATTRw  s[    hhj%%c4;;7dG,::/''dkk:;	
r   c                    | j                   j                  j                  ||      rI| j                   j                  j                  ||      }t	        |t
              r| j                  |       y y y r   )r   r  has_pending_mutation_of_attr	load_attrrN  r   r5  )r   r$  r   attr_vars       r   r/  z2InstructionTranslatorBase._maybe_sync_dealloc_attr  s]     ;;##@@dK{{//99#tDH(N3--h7 4 L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   r  r  r  r/  r  )r  r*   r   r'   rn  )r   r  re  return_insts       r   codegen_return_with_popsz2InstructionTranslatorBase.codegen_return_with_pops  s      A~~>LLQ( {{n, ~.#N4;;G 	
 		*,>y,I;W	
 r   c                L    |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                  j]                  || j^                          j`                  * j`                  jc                  | j^                  d   |       td        d   |jf                  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!!Tr?  r  r  r  NTr*  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/  rB  s     r   r   z:InstructionTranslatorBase.create_resume.<locals>.<genexpr>C  s     :A!++-:r  orig_graphmodulec                      y r   r   r   r   r   r   z9InstructionTranslatorBase.create_resume.<locals>.<lambda>O      r   r   resumesr   )4r  stack_ctx_argsstack_ctx_idxes_origr   ri   r  append_outputr&   r	  r  r*   r  r  r'   locals_ctx_argsr{  r  r  r.   r&  r/   r  r   rm  r.  r  locals_null_keysr   r"   rB  rR  r  stack_null_idxesr  rJ   lookupr  r   r  r  r0   get_contextr{  weakrefrefr   install_resume_function_globalrW  r  add_resume_functionrX   r  )r   r   resume_instrz  resume_codesr  is_leafhandle_inactive_ctxjr   j_origrg  r   resume_nameall_argnamesr  argnames_nullr2  	stack_lennew_codeorig_graphmodule_mayber>  r  s   `                    @@r   r  z'InstructionTranslatorBase.create_resume  s5   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
 	224>>	
 <<#LL,,$..4k 	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  r  r  T)r   r1   r   r4  r  r   r   r  r   r  rM  r  r*   rI  rJ  r'   rb  r  r>  r   r%   r  r  r"   r  r&   r6  deepcopyrc  r  r  )r   r   r  r  txesidxesresume_instsr  r   rT  current_num_stackr   stack_insert_idxfilter_instsrU  resume_namesr_  resume_coderZ  s                      r   r  z/InstructionTranslatorBase.create_call_resume_atc  s   6 $( t{{**+ 13*,37 ~"$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           	        |j                  t        d             t        t        ||             D ]  \  }\  }}|t	        |      dz
  k(  r n|j
                  ru|j                  t               |j                  |      |j                         g       |j                  |j                  |d      gt        d      t        dd             n"|j                  |j                  |dd             |j                  t        d              |j                  t        d      t        d	t	        |       dz
  
      g       |j                  t        d             | d   j
                  r|j                  |j                  d      |j                         g       |j                  |j                  |d   d      gt        d      t        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   T)r	  )	push_nullFr   r  r  r  r  ry  r  LIST_EXTENDN)r  r%   rc  r  r   r  r&   r  r  create_load_globalr*   r#   load_function_namer'   r)   r$   )rU  rh  r  r_  r   r  s         r   r  z-InstructionTranslatorBase.codegen_call_resume  s   4 	Q((\<)HI 	-OA|dC%))  &(,,Q///1   --d-=$Q .a4@   !6!6tUA!FG[^,/	-0 	"9-"<S5F5JK	
 	Q(''((,++- )),r*:)E ^ *!t< !!_ &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(  ry  Fc              3  <   K   | ]  }|j                           y wr   )r*  rB  s     r   r   zIInstructionTranslatorBase.should_compile_partial_graph.<locals>.<genexpr>  s     :A:r  )rR  r  r  r7  r  r&  r  r  r  r   r  r  r   current_tracerr  )r   r   s     r   r  z6InstructionTranslatorBase.should_compile_partial_graph  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 )Nr  __setitem__)r@  r  )r   r   r[  r$  keys        r   r  z&InstructionTranslatorBase.STORE_SUBSCR  s-    
 		!S#mc3Z<r   c                z    | j                  d      \  }}| j                  ||       |j                  | d|gi        y )Nr  __delitem__)r@  _maybe_sync_dealloc_subscrr  )r   r   r$  rt  s       r   r  z'InstructionTranslatorBase.DELETE_SUBSCR  s9    99Q<S 	''S1mcUB7r   c                    ddl m} ddlm} d }	 t	        ||      r|j                  | |      }nt	        ||      r|j                  |      }t	        |t              r| j                  |       y y # t        $ r Y .w xY w)Nr   rm   )rx   )
variables.dictsrn   variables.listsrx   rN  getitem_constmaybe_getitem_constr  r   r5  )r   r$  rt  rn   rx   item_vars         r   rw  z4InstructionTranslatorBase._maybe_sync_dealloc_subscr  s     	75		#/0,, C!232237 h/))(3 0  		s   <A/ /	A;:A;c                n    | j                  |j                        }| j                  t        |             y r   )r@  rn  r>  r}   r   r   r   s      r   BUILD_TUPLEz%InstructionTranslatorBase.BUILD_TUPLE  s%    		$++&		-&'r   c                r    | j                  |j                        }| j                  t        ||              y )N)r   )r@  rn  r>  r|   r  s      r   BUILD_SLICEz%InstructionTranslatorBase.BUILD_SLICE  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_nested  s    
 r   c                    t        | |      ry | j                  |j                        }| j                  t	        j
                  | |             y r   )r2   r@  rn  r>  rb   ro  r  s      r   r  z$InstructionTranslatorBase.BUILD_LIST  s:    0t<		$++&		/''e45r   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  mutation_type)r   +inject_BUILD_SET_unimplemented_TESTING_ONLYr:   r@  rn  r   ra   r>  )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@  rn  r  r  NotImplementedErrorr:   r   r   r  r>  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           	         t        | |      ry | j                  |j                  dz        }t        t	        |d d d   |dd d               }| j                  t        j                  | |             y )Nr  r   )r2   r@  rn  r   r  r>  rb   ro  )r   r   r   ds       r   	BUILD_MAPz#InstructionTranslatorBase.BUILD_MAP  sa    0t<		$++/*U3Q3Zqt!t-.		/''a01r   c                l   | j                  |j                        }|D cg c].  }t        j                  | t              j                  | |gi       0 }}i }|D ]/  }t        |t              sJ |j                  |j                         1 | j                  t        j                  | |             y c c}w r   )r@  rn  rb   ro  r   r?  rN  rn   updater   r>  )r   r   r   rZ  r  s        r   BUILD_MAP_UNPACKz*InstructionTranslatorBase.BUILD_MAP_UNPACK  s    		$++& 
 !!$-;;D1#rJ
 
 "$ 	#Aa!2333MM!''"	# 			!!	

s   3B1c                f   | j                         }| j                  |j                        }t        |t              sJ |j                         sJ |j                  |       }t        |      t        |      k(  sJ | j                  t        j                  | t        t        ||                         y r   )r  r@  rn  rN  r}   r  r  r   r>  rb   ro  r   r  )r   r   rB  r  s       r   BUILD_CONST_KEY_MAPz-InstructionTranslatorBase.BUILD_CONST_KEY_MAP  s    xxz4;;'$...&&(((--d34yCK'''		!!Sv&'	
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   rs  )r@  rn  r2  r  r  rN  rn   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  rn  r2  r  rN  r   
is_mutabler  r   r   r   r$  s       r   SET_ADDz!InstructionTranslatorBase.SET_ADD2  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  rn  r2  r  r  rN  r{   r  r   r  mutationr   r   r  s       r   r  z%InstructionTranslatorBase.LIST_APPENDD  s    HHJ{{Qxx###jj$((#++-#|,,,~~  ))#.		r   c                R   |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                         }t        || j                  |||      }	|rut        |t              sJ |j                  }
t        t        t!        |
d d d   |
dd d   d	            t#               
      }|	j%                  |       j'                  d|       | j)                  |	       y )Nr(  co_qualnamer     r  r  r   Tstrictr  r   )r2  rR  r  r  r-  r  rb   ro  r  rr   rW  rN  r}   r   rn   r   r  ra   get_dict_vtsetitemr>  )r   r   r  fn_namer  defaultsclosurer   
kwdefaultsrJ  r   anns               r   MAKE_FUNCTIONz'InstructionTranslatorBase.MAKE_FUNCTIONN  s   g%hhjGxxzw& 4::}555%++D$**2H2HIG
g% 4<"hhjG4<"&((*K4<!%J4<#xxzH'NN
 k=999  %%E#SssU14a4[>?.0C NN4 ((!3 			"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)rc  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  rI  rn  rN  r   r$  r|  rH  r   re   r  r  r:   r   r   r  r   r  r   r>  )r   r   r  r[  r  r_  s         r   r  z)InstructionTranslatorBase.UNPACK_SEQUENCE  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  )rn  r  r  r   r  r   r   r>  r}   r:   r   r   r  )
r   r   prefixsuffixr  r  vals_prefix	vals_listvals_suffixitems
             r   	UNPACK_EXz#InstructionTranslatorBase.UNPACK_EX  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_function  s0     $$=6 ^ %r   c                F    |j                   dk(  r| j                  |       y y )NGRAPH_BREAK_IF_LEAF)rn  r  r  s     r   r  zInstructionTranslatorBase.NOP  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  r>  r   r   r  r  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        j                  | t              j                  | |gi       S |dk(  r,t        j                  | t              j                  | |gi       S |dk(  r,t        j                  | t
              j                  | |gi       S |S )Nr   r  r  )rb   ro  r   r?  r  ascii)r   r  flags      r   _convert_valuez(InstructionTranslatorBase._convert_value  s    19"((s3AA$QSTTQY"((t4BB4%RTUUQY"((u5CCD5'SUVV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   r  r  z{:})r  rN  r   torch._dynamo.variables.lazyr  rw   rj  r  r>  r  rb   ro  r  r?  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!''$4466<
 	?3::6%8H"Mr   c                    |j                   }|J |dz  dk(  r| j                         }nt        j                  | d      }| j	                  ||      S )Nr  r   )r2  r  rb   ro  r  )r   r   r  r  s       r   FORMAT_VALUEz&InstructionTranslatorBase.FORMAT_VALUE  sS       DLT!xxzH&,,T26H!!(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   )r2  r@  r  r   rN  r   StringFormatVariableformat_stringr  sym_argsr  rB  
sym_kwargsr:   r   r  r  r   r>  rj  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  r/  )rn  r'   r  )r   r   
new_argvalnew_insts       r   IS_OPzInstructionTranslatorBase.IS_OP9  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__)rn  r@  r>  r  r   ObservedTypeErrorr;   rN  r  r  r  rb   ro  rC   	UNARY_NOT)r   r   leftrightr  r"  s         r   CONTAINS_OPz%InstructionTranslatorBase.CONTAINS_OPB  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  rn  r2  r  rN  r{   r  r  r  s       r   rl  z%InstructionTranslatorBase.LIST_EXTEND_  su    HHJ{{Qxx###jj$((##|,,,~~hR0r   c                    | j                  t        j                  | t              j	                  | | j                         gi              y r   )r>  rb   ro  r.  r?  r  r  s     r   LIST_TO_TUPLEz'InstructionTranslatorBase.LIST_TO_TUPLEh  s6    		!!$.<<TDHHJ<QST	
r   c                   | j                   d   }| j                  |      sJ |j                  t        u rt	        j
                  | t              j                  | t	        j
                  | d      gi       }|j                  | t	        j
                  | d      |       |j                  | t	        j
                  | d      |       || j                   d<   y y )Nry  zgenerator raised StopIterationrc  r  )	r  r  r  r  rb   ro  r  r?  call_setattr)r   r   r[  new_vals       r   STOPITERATION_ERRORz-InstructionTranslatorBase.STOPITERATION_ERRORm  s     jjn))#...<<=(%++D,?MM &&t-MNOG
   '<'<T='QSVW  '<'<T;'OQTU$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  rn  r2  r  r  rN  rn   r  r  r  s       r   
DICT_MERGEz$InstructionTranslatorBase.DICT_MERGE  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 )Nry  r  )r  r  r>  rb   ro  r   r  r  r  s      r   GET_LENz!InstructionTranslatorBase.GET_LEN  s]    jjn!!#IIo++D#c6L6L6N2OPQ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
        ry  N)r  r>  r  rb   ro  rD   r  s      r   MATCH_MAPPINGz'InstructionTranslatorBase.MATCH_MAPPING  sC    
 jjn		,,%%dO<	
r   c                    | j                   d   }| j                  | j                  t        j                  | t
              |gi              y Nry  )r  r>  r  rb   ro  rG   r  s      r   MATCH_SEQUENCEz(InstructionTranslatorBase.MATCH_SEQUENCE  sB    jjn		,,%%d,?@	
r   c           	        | j                  d      \  }}}t        j                  | |j                        }| j	                  | j                  t        j                  | t              ||||gi              t        j                  dk  rD| j                  d   }| j	                  t        j                  | t        |t                            y y )Nr  r(  ry  )r@  rb   ro  r2  r>  r  rE   rR  r  r  r]   rh   )r   r   subjectr  namesr2  r  s          r   MATCH_CLASSz%InstructionTranslatorBase.MATCH_CLASS  s    "iile##D$((3		,,%%d,<=#sE*	
 g%**R.CIIo++DfSBR6S2STU &r   c           	        | j                   d   }| j                   d   }t        |t              sJ | j                  | j	                  t        j                  | t              ||gi              t        j                  dk  rD| j                   d   }| j                  t        j                  | t        |t                            y y )Nry  r  r(  )r  rN  r}   r>  r  rb   ro  rF   rR  r  r]   rh   )r   r   rB  r$  r  s        r   
MATCH_KEYSz$InstructionTranslatorBase.MATCH_KEYS  s    zz"~jjn$...		,,%%dO<sDk2	
 g%**R.CIIo++DfSBR6S2STU &r   c                D    | j                  | j                  d             y )Nr  r>  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)r2  append_prefix_instr  r  s     r   RESUMEz InstructionTranslatorBase.RESUME  s5    88q=##D)&+D#.....r   c                P    |j                   J t        |j                      | |      S r   )r2  _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_constsrR  )r  r2  rN  r.  r   r5  rh   rj  )r   r   r5  r   s       r   r.  z"InstructionTranslatorBase.KW_NAMES  sl    $$[1$((;(E*** 	)DdC(((	)}}$$$(//h?r   c                6    | j                  t                      y r   )r>  r   r  s     r   rf  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   )rR  r  r  rN  r}   r  r  r5  r  r2  r@  r   r   r   r  r?  )	r   r   call_kwr5  contentsrJ  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.CALLF  s    
 	

4r   c                r    |j                   J | j                  | j                  |j                              y r   )r2  r>  r  r  s     r   COPYzInstructionTranslatorBase.COPYM  s-    xx###		$**dhhY'(r   c                    |j                   J | j                  |j                       | j                  d   c| j                  d<   | j                  |j                    <   y r  )r2  r  r  s     r   SWAPzInstructionTranslatorBase.SWAPQ  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(  ry  )rN  rj   supports_graph_breaksr  r   rR  r  r7  r  r&  r  rD  r   r  r%  r   r  enter)r   rg  r   r&  s       r   	enter_ctxz#InstructionTranslatorBase.enter_ctxc  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  )rg  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  rN  ri   rj   r/  r>  rl   r&  r-  )r   r   rg  s      r   r  z.InstructionTranslatorBase.setup_or_before_with  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_inst  s%    &&&&  &r   c                .   t         j                  dk\  rq| j                  set        | j                  |j
                     t              sJ | j                  j                  j                         | j                  |j
                  <   y | j                  |       y r  )rR  r  r  rN  r{  rn  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_VARS      %r   c                &    | j                  |       y r   r6  r  s     r   RETURN_GENERATORz*InstructionTranslatorBase.RETURN_GENERATOR  r8  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  r*  r   )rR  r  r  r@  r  _comprehension_end_for_ipsdiscard_comprehension_depth)r   r   
current_ips      r   END_FORz!InstructionTranslatorBase.END_FOR  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{  r{  rn  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   )rn  r{  r>  r   r*  r  s     r   LOAD_FAST_AND_CLEARz-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  r/  r   )r  r   r(  r2  r  r  rn  r  s     r   LOAD_SUPER_ATTRz)InstructionTranslatorBase.LOAD_SUPER_ATTR  sV    ;..tA>?xx###88a<T"OODKK(r   c                D   |j                   dk(  r| j                  |       y |j                   dk(  r| j                  |       y |j                   dk(  r8| j                  t	        | j                         j                  |                    y |j                   dk(  rN| j                         j                         }t        j                  t        |            }| j                  |       y t        dd|j                    d|j                    dg t        j                  	       y )
Nr  r     r  z Missing CALL_INTRINSIC_1 handlerzCALL_INTRINSIC_1 operand: z,No handler implemented for CALL_INTRINSIC_1  instruction.r  )rn  r  UNARY_POSITIVEr>  r}   r  r  r  r   TypingVariabler
   r:   r   rC  )r   r   r   tvs       r   CALL_INTRINSIC_1z*InstructionTranslatorBase.CALL_INTRINSIC_1  s    ;;!$$T*[[A%[[AIImDHHJ$H$H$NOP[[A
--/A))'!*5BIIbM:4T[[MBJ4;;-Wde6)556	r   c                p   | j                         }| j                         }|j                  dk(  rMt        |t              sJ |j	                  | dt        j                  d      |gi        | j                  |       y t        dd|j                   d|j                   dg t        j                         y )	Nr  r  __type_params__z Missing CALL_INTRINSIC_2 handlerzCALL_INTRINSIC_2 operand: z,No handler implemented for CALL_INTRINSIC_2 rI  r  )r  rn  rN  ro   r  rh   rj  r>  r:   r   rC  )r   r   arg2arg1s       r   CALL_INTRINSIC_2z*InstructionTranslatorBase.CALL_INTRINSIC_2  s    xxzxxz;;! d$<===!(():;TB	 IIdO: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                         }t        |t              sJ | j                         }|dz  rgt        j
                  dk\  sJ |j                  | t        j                  | d      gi       }|j                  | dt        j                  d      |gi        n|dz  r||_        n|dz  rvt        |t              sJ |j                  }t        t!        t#        |d d d   |dd d   d	
            t%                     }|j'                  |       j)                  d|       n|dz  r||_        n|dz  r||_        | j/                  |       y )N   r  r   r  r   r  r  r  Tr  r  )r2  r  rN  rr   rR  r  r?  rb   ro  r  rh   rj  r  r}   r   rn   r   r  ra   r  r  r  r  r>  )r   r   r  rJ  r(  r   r  s          r   SET_FUNCTION_ATTRIBUTEz0InstructionTranslatorBase.SET_FUNCTION_ATTRIBUTE.  sT      XXZ"8999xxz4<##w... %%d_-B-B4-K,LbQDNN!(():;TB	 T\BJT\dM222 JJE#SssU14a4[>?.0C NN4 ((!3 T\ BMT\BK		"r   c                    |j                   J | j                  | j                  | j                         |j                                y r   )r2  r>  r  r  r  s     r   CONVERT_VALUEz'InstructionTranslatorBase.CONVERT_VALUEV  s5    xx###		$%%dhhj$((;<r   c                P    | j                  t        j                  | d      d       y )Nr   r   )r  rb   ro  r  s     r   FORMAT_SIMPLEz'InstructionTranslatorBase.FORMAT_SIMPLEZ  s    ?00r:A>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)rc  rd  rc  )rN  r2  r   _load_special_namesr  ri   rj   r/  r>  rk   rf  rl   r  )r   r   r(  rg  r$  s        r   LOAD_SPECIALz&InstructionTranslatorBase.LOAD_SPECIALo  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                b    | j                  t        j                  | |j                               y r   )r>  rb   ro  rn  r  s     r   LOAD_SMALL_INTz(InstructionTranslatorBase.LOAD_SMALL_INT  s    		/''dkk:;r   )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)rN  r2  r   r>  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>  rF  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_summary  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)ru  FrameSummaryr|  r  r   r   s    r   r  z'InstructionTranslatorBase.frame_summary  s?    %%DKK<KKDKKK8	
 	
r   c                    t        | j                  dd      }t        j                  d      }|j	                  |      d uS )Nr  rz  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_modules  s:    4;;{CZZ(?@!''1==r   c                    | j                   j                  |t        j                  |            }t	        t        |      j                  t        j                               |S r   )	r   install_global_by_idrP  rQ  r?   rP   r  r>   WEAKREF_ALIVE)r   r  r  global_names       r   store_global_weakref_by_idz4InstructionTranslatorBase.store_global_weakref_by_id  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_mode  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_mode  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 rb  )r   r  r   r  r  r   rm  r   s    r   r  z#InstructionTranslatorBase.speculate  s|    ''333''!+++##((KK##KK$$q(d66:;	
 	
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   co_firstlinenor   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%%;?;;J(#'#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  ry  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>C  s    3$! r   c                 6      dt        j                          S )Nr   )ru  
format_exc)user_stack_traces   r   r   z;InstructionTranslatorBase.log_graph_break.<locals>.<lambda>G  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   ru  rv  r5   r3   r   _loggingtrace_structuredrN  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  )r  r   s     r   r  z0InstructionTranslatorBase.raise_loop_graph_breakk  s;     	)%&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  Try     )maxlen)r  r  r  Fr   )CO_ASYNC_GENERATORCO_COROUTINECO_GENERATORCO_ITERABLE_COROUTINE)MrF  rG  r  distributed_stater   r{  r|  r}  r~  r  r  r   r  r'   r  r  r  r  r   r5  r  r  r  r   r  r>  r  r<  rm  r   r  r$  rW  rY  r  r  r  r   replay_record_enabledrI   r  nn_module_stack	num_callsexportr  r   r  r  r  r  r  r  r  r  resume_executionr  r  r  r  co_flagsr>  rf   r  r  r   r  rS  r  r  r   r  r  r  r  r  	lazycacher  )r   r   rm  r$  rW  rY  r  r{  r|  r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  rM  s                           r   rG  z"InstructionTranslatorBase.__init__y  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+,().&P
  !P"
 ++GMM: 	* 9I8U8UMM9
( 	F..	:r   r   r  )r   r   )rJ  rb   r   r  r  rz  r   r   )rJ  ro   r   Sequence[VariableTracker]r  rz  r   rb   )rJ  ro   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   )r[  rb   r   r   )r  r  r   r   r   rb   )r~  r   r   r  )r6  r   r   r   )r   r,   r   rb   )ra  r   r   rO   )r   r   r  r   r}  r   r   r   )rn  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$  rb   r   r   r   r   )r   r,   r  r   r   r  )r   r   rT  r,   rz  rB   rU  list[types.CodeType]r  r1   rV  r   rW  r   r   ztuple[types.CodeType, str]r   r,   r  zlist[StackLocalsMetadata]r   r  )rU  r  rh  r   r  r1   r   r   )r$  rb   rt  rb   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   )rg  z8ContextWrappingVariable | GenericContextWrappingVariabler   r,   r   rb   )rg  rb   r   r   )rw  zlist[Any] | Noner   r   )r   ztraceback.FrameSummary)r  r   r  r   r   r   r   zFakeTensorMode | None)r  z!Callable[[VariableTracker], bool]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 | UserError | StepUnsupportedr   r   )r  types.CodeTyper   zUnsupported | UserErrorr   r   )NNN)(r   rA   rm  r  r$  r   rW  r   rY  r   r  r   r{  rz  r|  rz  r}  r   r~  r   r  r  r  r   r  r   r  r   r  rQ  r  DistributedState | Noner  ztuple[types.CellType] | Noner  r  r  zdict[Instruction, int] | Noner   r   (  r   r   r   r   r  r  r  r  r  r  r?  r  r  r  r  r  r  rR  r  r  propertyr  r  r  r  r>  r  r  r@  r*  r/  r3  r7  r5  rP  LOAD_CLOSURErT  rj  r^  rH  cached_propertyrd  rg  rl  r   r`  r  r  r  EAGER_IMPORT_NAMEr  r  r[  r  JUMP_FORWARDJUMP_ABSOLUTEr  rk  not_rY  rl  rX  JUMP_IF_FALSE_OR_POPJUMP_IF_TRUE_OR_POPr  r  r  r  r  r  r  r  r  r`  r  r  r  r  r  r  r  r  r  r  r  r
  r=  r  r  r  r  r!  r  r&  r  r*  r-  r1  r/  staticmethodr8  r  r  r  r  r  r  rw  r  r  r  r  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  rl  r  r  r  DICT_UPDATEr  r  r  r  r  r
  r  r  rK  posrJ  negUNARY_NEGATIVEr  invertUNARY_INVERTpowBINARY_POWERmulBINARY_MULTIPLYmatmulBINARY_MATRIX_MULTIPLYfloordivBINARY_FLOOR_DIVIDEtruedivBINARY_TRUE_DIVIDErT  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-  r.  rf  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  r4  r7  r:  r@  rB  rD  rF  rM  rR  rT  rV  r  r\  r^  r`  rb  LOAD_FAST_BORROWr  POP_ITERrh  ri  rk  rn  ro  r  rx  r  r  r  r  
contextlibcontextmanagerr  r  r  r  r  r  rG  rN  rO  s   @r   r   r     s    //00#==.."CC  ##$$""&&K%%####00  ++>>,, ! EE""%%.!F00'

88 $8 +	8
 
8,4$4 (4 +	4
 
4U$U (U +	U
 
Un	Wn` 7"*	+\	 ; ;AF2M=^ ;!+FV2.)
V/ L	*J* J J!E( # #,
2:;| $% 4 4,>4 LM$X]]E:#HNNE:'t<&x~~t<U
U
(U*
(.
`&P0..$)LA'F<:$*QfLPP  )	)
  :;	:;x  A
	-
	-G "

%   A
	

8 &)	 >x%x% !x% "	x%
 +x% x% x% "x% 
$x%tg%g% $=g% 
	g%R A?*A?:CA?IRA?	A? A?F
&  ~=	=84"4)84	4((16
 @L @ 8 $6 2
$ "2
 9.1/b:0  N

4

N,3
B"!:1

%$1 K@

V V"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(#E# # 
	#J 
 
 -'	*&&/;).,  A
'
'
&P=?* !IH
!8<S ;?	
'7	
		

>
 5 5 *9*	* *
""%/"BE"	"+(+	$+(l$l l 7	l
 
l\ 

#:
	
 
@ 15)-15-@;@; (@; !	@;
 "@; #@; %@; 4@; 5@; (B@;  3@; @; @; @; (@;  %!@;" 3#@;& .'@;( ')@;, /-@;. 
/@; @;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 )rD  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|  r!  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_scoperw  r  torch_function_mode_stackr  r  r   )r   rm  r$  rW  rY  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  rF  rG  rA   _throw_if_in_functorchr   r   r  r#  r  r  r{  r  r  r0   rO  r{  r   	frozensetrw   rj  rR   r  r  r3  rN  rO  r  r  rQ   cell_contentsr  r   DeletedVariabletrack_cell_existingr   r}  r   r~  realize_all)r   rm  r  r$  rW  rY  r  r&  r  compiler_fnr  r  export_constraintsframe_stater  r  r  r  r  r'  r   r  local_dynamismr6  r  contents_sourcer.  cell_varr-  cell_sourcerM  s                                 r   rG  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eagerr1  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_backendrE  getattr_staticr   r1  _C
_functorchpeek_interpreter_stackTransformTypeVmapGradJvprt  r   lowerr:   )r   r9  r1  ciforbidden_keysr   rX  s          r   r+  z,InstructionTranslator._throw_if_in_functorch  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   )rN  rR   r$  rO  rO   rW  r  r'  )r   r  s     r   get_example_valuez'InstructionTranslator.get_example_value  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  rN  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 )Nry  r  )r   r  rN  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  )#rN  r   r  r[   r  r   allow_empty_graphsr   rs  r  rL  r  r  r   r  r   	SkipFramer6   r  r  r   r*  r  r   r  r  r  r@   r  r   rM  r  r8  r  r9  )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   rS  r  s     r   r  z"InstructionTranslator.RETURN_VALUE      Tr   c                &    | j                  |       y r   rU  r  s     r   r  z"InstructionTranslator.RETURN_CONST  rV  r   )r   rD  r  )$rm  r  r  r  r$  r   rW  r   rY  r   r  ztuple[Any, ...] | Noner&  r   r  r   r1  r   r  r   r  r   r2  r   r3  r   r  r   r  rQ  r  r  r  r  r   r   r   )r  rT   r   r   r  r  )r   r   r   r  r  r  r  r#  rG  r+  rH  rL  rN  rS  r  r  rN  rO  s   @r   rD  rD    s     # #c'c c !	c
 "c #c (c $'c %c c c c  c c (c  %!c" 3#c$ '%c& 
'cJ>	,\r   rD  r(  INPLACEr  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_stackr>  r  r  r  timetime_nsr  start_time_nschild_time_nsr   r[  r   r\  r   co_coderc  record_timingadd_child_time)r   r  get_inline_depthcaller_inford  trace_successstack_entrytrace_end_nsr  r]  r^  timings               r   profile_inline_callrv  '  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 methodr4  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 rp  r  )r  s   r   r   z;InliningInstructionTranslator.inline_call.<locals>.<lambda>v  s    F4G4G!4K r   )rv  r   r  build_inline_tracerinline_call_)r  r  funcr   r  tracers    `    r   r  z)InliningInstructionTranslator.inline_calll  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_applyrJ  _originz"allowlist in dynamo known functionr   zAvoid calling the function `rB  r:  z:Apply `@torch._dynamo.dont_skip_tracing` to the function `zw` to force tracing into the function. More graph breaks may occur as a result of attempting to trace into the function.z Please file an issue to PyTorch.z.Attempted to inline function marked as skippedz
qualname: z, name: z, filename: `z`, skip reason: z?Dynamo developers have intentionally marked that the function `z` should not be traced.)has_selfr:   r   rN  rt   rE  r<  get_functionr   check_verboseskippedtorch._dynamo.variables.miscr  r-  rJ  r  
SkipResultr   get_filenameget_namer   )r~  rX  r  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        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\                         |r|d   }d}t        |t^              rU|ja                         sEtc        |je                         t>        jf                  jh                        r|jk                         }nd}|rt        |tl              r j
                  jo                  |jp                        }t        |t>        jr                  jt                        rtw        jx                  |      t{        j|                  |j~                  j                        d<   nt        |t              ro|j                  }t        |t>        jr                  jt                        r?tw        jx                  |      t{        j|                  |j~                  j                        d<   t        |t              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 rM  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  )rs  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  	positionsr   rZ   r  r  )headerr  r  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, %sTrD  r   )IrN  rt   rr   rp   r  r   r  r   dont_skip_tracingpreviously_inlined_functionsr{  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_enabledra  BytecoderR  r  r  r  trace_call_logr  r^   r  r   rw   is_realizedr  	peek_typerJ  rK  r  r   r  r  r  r  rP  rQ  r0   rO  forward__code__r   r  rs   r-   &InliningGeneratorInstructionTranslatorr|  r}  r~  )r  r~  r   r  r  tracing_ctxprevious_result
sub_localsr  r2  r   r  r  arg0should_checkmoduler  r  r  r  s   `                @@@r   r|  z1InliningInstructionTranslator.build_inline_tracer  s    $*.
 	
 
  $}}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 7DL$ 34T=M=M=Odnn.@<<>D#(Ld$45#]]88IF!&%((*>*>? $KK/ %001H1HI.  &CD!ZZF!&%((*>*>? $KK/ %001H1HI. d$8999;''44,,F&  3''44,,F K  
	L  1D4E4E4G3H$--/JhJhIi j8<=3??,==>k&SRSWS`S`SbRccde&11 	 	
	s%   Q/ /	T8AT S8TTc                N   | j                   }d|_        d|_        | j                  }t	        j
                         }|j                  r| j                  |j                        }	 |5  | j                          d d d        | j"                  |_        d|_        | j$                  j&                  rt)        j*                  d       S | j,                  J | j.                  |j.                  u r%|j0                  j3                  | j0                         |xj4                  | j4                  z  c_        t        j                  d|       | j$                  j6                  j8                  j;                  |       t<        j>                  stA        | tB              r| jD                  rtG        |      rttA        | tB              rd| jH                  rXtA        | tB              sJ g }| j,                  jK                         s| j,                  g}t        jL                  tN        | |       y | j,                  S tG        |      rMtA        | tB              sJ | j,                  jK                         sJ tQ        | jR                  tU                     S | j,                  S # 1 sw Y   xY w# t        j                  $ r#}d| d| }t        j                  |        d }~wt        t        f$ 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  r  nullcontextr  r  r  r   r   r  r  r;   r<   r  r  r   r   r!  rh   rj  rx  rW  r|  r  r  r  traced_coder   r   r  rN  r  is_generator_from_ctx_managerr-   generator_exhaustedis_constant_noner  r  rz   generated_itemsra   )r   r  r  
strict_ctxr  rX  r   s          r   r}  z*InliningInstructionTranslator.inline_call_J  s   &+#(,%{{$002
""55f6M6MNJ	2 
& +/*C*CF',1F);;""#**400##///>>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Y' 	 !AL 	II*D1	 +/*C*CF',1F)sH   #J %J6J JJ L+K		LK##$LL
 
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__)rm  r  r  r   )r   r$  rW  rY  r{  r|  r}  r~  rm  r  r  r  r  r  r  r  r  r  ) get_globalsrN  r   __dict__r   r  inlined_code_cacher{  rm  r  r  r!   r    r   r+   r|  r   rF  rG  r  r  r  r  r  r  funcvarr  r  rx  r  r6  r  )r   r  r  r{  r|  r}  r~  r  rW  rY  r  cachedrm  r  r  r   rM  s                   r   rG  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_mode  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   r  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  rF  r   rM  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  rF  r  r:   )r   r   r  rM  s      r   r  z3InliningInstructionTranslator.create_call_resume_at  s5    
 %%707PQQ5L		
r   c                F    | j                         | _        d | _        t        r   )r  rx  r   r9  r  s     r   r  z*InliningInstructionTranslator.RETURN_VALUE  s    #xxz#' r   c                H    | j                  |      | _        d | _        t        r   )rT  rx  r   r9  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_rn  ___unnamed_scope)rW  r^  r`  r  r  rs  rt  r   rd   rM   r   r  rO   rN   rU  rS   )	r   r   ra  rb  rc  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   )rn  rW  r[  r   rw  rF  r^  r  r  r3  r>  r4  rb   ro  )r   r   r   r   r  r  r  rM  s          r   r^  z*InliningInstructionTranslator._load_global5  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)ri  r  )r   rw  rW  rF  rl  r  rN  r   r:   rn  r  r  
store_attr)r   r   r  r   _fglobals_valuer  r   rM  s          r   rl  z*InliningInstructionTranslator.STORE_GLOBALF  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  rz  r   rb   )r~  ro   r   ztrace_rules.SkipResult)
r  r   r~  ro   r   r  r  rz  r   r  r  )r  r   r  r  r{  rz  r|  rz  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}  rG  r  r  r  r  r  r  r  r  r  r^  rl  rN  rO  s   @r   r  r  e  s   *++%%)) ') (	)
 +) 
) ) ?&?	? ?B JJ&J (J +	J
 
'J JX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  )rF  rG  r  r  r  )r   r   r  rM  s      r   rG  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>d  s    4CTCT r   )rv  r   r  rF  r}  r  s   `r   r}  z3InliningGeneratorInstructionTranslator.inline_call_c  s8     dkk;TU 	*7')	* 	* 	*s	   ?Ac                     yr  r   r   s    r   r  zCInliningGeneratorInstructionTranslator.should_compile_partial_graphg  s    r   c                L   | j                         }| j                  j                  |       t        | j                        t        kD  rt
        j                  | j                  t        j                  d              t        j                  s| j                  r|| _        t        y r   )r  r  r   r   rv   r   InfiniteGeneratorErrorr>  rh   rj  r   r  r  rx  r;  )r   r   tops      r   YIELD_VALUEz2InliningGeneratorInstructionTranslator.YIELD_VALUEk  s~    hhj##C(t##$'99,,,		"))$/05511#&D 	 2r   c                    | j                   d   }t        |t              sN| j                          t	        j
                  | t              j                  | |gi       }| j                  |       y y r  )	r  rN  rz   r  rb   ro  r	  r?  r>  )r   r   r  ress       r   GET_YIELD_FROM_ITERz:InliningGeneratorInstructionTranslator.GET_YIELD_FROM_ITERy  sV    jjn#34HHJ!''d3AA$rRCIIcN 5r   c                0    d| _         t        | 	  |      S rr  )r  rF  r  r   r   rM  s     r   r  z3InliningGeneratorInstructionTranslator.RETURN_VALUE      #' w#D))r   c                0    d| _         t        | 	  |      S rr  )r  rF  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  ry  Unreachable sub-generator coder   @Should only be encountered while implementing generator support.r  r   r   )r   r  r  r  r:   r  rN  r   r   r>  r  r  r   r  r  rh   rj  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  ry  r*  r  r   r  r  zSEND with bad typez
TOS type: z(Attempted to SEND with unsupported type rM  )r   r  r  rN  ry   rq   r   r  collectionsabcIteratorr  r  r>  r  r   r  rR  r  rh   rj  r  r:   r`   r  s        r   SENDz+InliningGeneratorInstructionTranslator.SEND  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   rG  r}  r  r  r  r  r  r  r  rN  rO  s   @r   r  r  Y  s7    **3***$#L*r   r  )r   r   r   ztypes.ModuleType)r   r;  )r   r   r   Generator[None, None, None])rJ  zCallable[..., object]r   zCallable[..., Any])rT  r  r   r   )rd  r   r   r   )r   r   rp  Callable[[object], bool]r>  r   r   r   )r~  r  r   r   )r  )r  rb   r  r   r   r   )rp  r  r>  r   r   r<  )r   r   r  r1   r  r  r   r   )r>  r   r%  r   r   zYCallable[[Callable[..., None]], Callable[[InstructionTranslatorBase, Instruction], None]])r   rA   r  r  rp  zCallable[[], int]r   r  (  r   
__future__r   r  collections.abcr  r6  r   ra  rH  r   rE  r  r  r   rk  r~  rR  	threadingri  ru  rO  rP  r   typingr   r   r   r   r	   r
   typing_extensionsr   r  torch._loggingtorch._dynamo.dynamo_profilerr   r   torch._dynamo.excr   r   torch._guardsr   r   r   torch._logging.structuredr   %torch.fx.experimental.symbolic_shapesr   torch.utils._functoolsr   r   r   r   r   r  r   r   bytecode_analysisr   r   r   r    bytecode_transformationr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   codegenr1   comprehension_graph_breakr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   funcname_cacher=   guardsr>   r?   output_graphr@   rA   rB   	polyfillsrC   rD   rE   rF   rG   replay_recordrH   rI   r  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   rg   variables.constantrh   variables.ctx_managerri   rj   rk   rl   ry  rn   variables.functionsro   rp   rq   rr   rs   rt   ru   variables.iterrv   variables.lazyrw   rz  rx   ry   rz   r{   r|   r}   variables.miscr~   r   r   r   r   r   r   variables.nn_moduler   r   variables.setsr   r?  r   variables.tensorr   r   r   variables.torch_functionr   r   variables.user_definedr   r   r   r   r   r   r   r   torch._subclasses.fake_tensorr   r  r   	getLoggerr   r  r  getArtifactLoggerr  r  r  r  r  r!  r   r?  r   r   containsr   r  r   r   cacher   	dataclassr   r   r   r  r  r  r  r  r#  r%  r  r   r  r9  r;  rK  rU  rh  rv  r  r  r  r  r  r=  r  r?  rQ  r   rD  r  _nb_opsr|  r  rv  r  r  )r   r   r   r   s   0000r   <module>r     s  0 #      
        	 
       I I $   R O C C / < /      " '  L   ) / N N  : 
	 	 	 ;
 
 
 G F R R C 0  /   / /    Q ' 2 W W  ==<'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  ) )   < I I IX 
 
 
 / / /3 3. 4 4 )!) ) )& $!$ $ $   D	~ 		I 	9 A . .&'
#'&' ' 
	'T B@&@F]&].2]=]@	R!R'0R;LR	RBBB"BBJJ J2 ` ` `FP8;'P8;fp^5 ^B	 w 
 FA	 	!#v-F12JWVABZL3I	
 :=:=
:= (:= !	:= :=zqJ$= qJh-J Il'RZs   .V3$V