
    rh5                    	   U d 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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! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( dd	l)m*Z* d
dl+m,Z,m-Z-m.Z.mZ/m0Z0m1Z1 d
dl2m3Z3m4Z4m5Z5m6Z6 d
dl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ d
dlAmAZA d
dlBmCZC d
dl-mDZDmEZEmFZFmGZGmHZHmIZImJZJ d
dlKmLZL d
dlMmNZNmOZO d
dlPmQZQmRZR d
dlSmTZTmUZU d
dlVmWZWmXZX d
dlYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z` d
dl0maZambZb d
dlcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZk d
dllmmZmmnZnmoZo d
dlpmqZqmrZrmsZs d
dltmuZu d
dlvmwZw d
dlxmyZymzZzm{Z{ d
dl|m}Z}m~Z~ d
dlmZmZmZmZmZmZmZ d
d lmZ d
d!lmZ d
d"lmZmZmZmZmZ d
d#lmZmZmZmZmZmZ d
d$lmZ d
d%lmZmZmZ d
d&lmZmZ d
d'lmZmZmZmZmZ erd
d(lmZ  ejR                  e      ZejX                  j[                  ed)      ZejX                  j[                  ed*      ZejX                  j[                  ed+      ZejX                  j[                  ed,      Z ejd                         Z ejh                         D  ci c]  \  } }|  eu|      jj                   c}} Zeeef   ed-<    euejt                        jj                  Z euejx                        jj                  Zd. ed/<   d0 ed1<   d2Zej~                  d3ed4ej                  fd5       Zej                   G d6 d7             Zej                   G d8 d9             Zej                   G d: d;             Zej                   G d< d=             Z G d> d?      Zej~                  d@        Zej                  dgdB       Zej                  dgdC       Zej                   G dD dE             Z G dF dGeͫ      Z G dH dIeϫ      Z G dJ dKeϫ      ZdLej,                  dMef   fdNZdOdAdPej,                  egef   dQefdRZdSZdhdTZdPej,                  egef   dQefdUZdV Z G dW dXeګ      Zej                   G dY dZ             Z G d[ dAe۬\      Z G d] d^eݫ      Zej                  d_k\  r6ej                  D cg c]  \  }} eed`|v r|dad ndb|dad         c}}Z G dc ddeݫ      Z G de dfe      Zyc c}} w c c}}w )ia  
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.
    N)AnyCallablecastNoReturnOptionalTYPE_CHECKINGUnion)patch)TensorifyScalarRestartAnalysis)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_call_functioncreate_instructioncreate_jump_absolutecreate_swapget_code_keysInstructionis_generator	unique_id)code_context)	PyCodegen)ArgsMismatchErrorBackendCompilerFailedcollapse_resume_framesformat_graph_break_messageget_stack_above_dynamounimplemented_v2Unsupported)get_funcname)GuardBuilderinstall_guard)GraphCompileReasonOutputGraph)DummyModuleExecutionRecorder)ContinueExecutionCacheReenterWith)
AttrSourceDictGetItemSourceGlobalSourceGlobalWeakRefSourceLocalCellSourceLocalSourceSource)is_builtin_constantis_forbidden)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)ConstantVariable)ContextWrappingVariableGenericContextWrappingVariableWithExitFunctionVariable)ConstDictVariableSetVariable)BaseUserFunctionVariableLocalGeneratorFunctionVariableLocalGeneratorObjectVariableNestedUserFunctionVariableSkipFunctionVariableUserFunctionVariableUserMethodVariable)MAX_ITERATOR_LIMIT)LazyVariableTracker)BaseListVariableListIteratorVariableListVariableSliceVariableTupleVariable)CellVariableExceptionVariableGetAttrVariableNullVariablePythonModuleVariableUnknownVariable)NNModuleVariable)supported_comparison_opsSymNodeVariableTensorVariable)SymbolicTorchFunctionStateTorchFunctionModeVariable)RemovableHandleVariableUserDefinedClassVariable!UserDefinedExceptionClassVariable"UserDefinedExceptionObjectVariableUserDefinedObjectVariable)CompilePackagegraph_breaks
trace_calltrace_sourcetrace_bytecodecompare_op_handlersc                 2    t        | g t        |      i       S N)handle_containsreversedtxargs_s      q/var/www/html/ai-insurance-compliance-backend/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 inzihttps://github.com/pytorch/pytorch/issues/new?&labels=oncall%3A+pt2&projects=&template=pt2-bug-report.ymlnamereturnc                 ,    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)r   s    r   _import_moduler      s     ""4((r   c                   ^    e Zd ZU eed<   eed<   eed<   eed<   dZeed<   dZ	e
e   ed<   d	 Zy)
SpeculationEntryfilenamelinenoinstruction_pointerinstFfailedN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   SpeculationRestartAnalysis)selfr   s     r   fail_and_restart_analysisz*SpeculationEntry.fail_and_restart_analysis   s:     ;;"![[//N@N,,NKKr   )__name__
__module____qualname__str__annotations__intr"   r   boolr   r   r1   r    r   r   r   r      s8    MK
FD+/FH'(/	Lr   r   c                   v    e Zd ZU dZ ej
                  e      Zee   e	d<   dZ
ee	d<   d Zd Zded	ed
ef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_factoryentriesr   indexc                     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   r   r   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   __doc__dataclassesfieldlistr   r   r   r   r   r   r   r   r   r   r   r   r   r      sV     '8k&7&7&MGT"#ME3N--%(-	-r   r   c                   T    e Zd ZU  ej                  e      Zeeef   e	d<   defdZ
y)
LocalStater   automatic_dynamicr   c                 b    dj                  d | j                  j                         D              S )N
c              3   L   K   | ]  \  }}| d |j                            yw): N)render).0kvs      r   	<genexpr>z$LocalState.render.<locals>.<genexpr>-  s*      
%)QqcAHHJ< 
s   "$)joinr   itemsr   s    r   r   zLocalState.render,  s/    yy 
-1-C-C-I-I-K
 
 	
r   N)r   r   r   r   r   dictr   r   rK   r   r   r   r   r   r   r   &  s6    8I8I8I9tC!445 
 
r   r   c                   <    e Zd ZU eed<   eed<   dZeee      ed<   y)DistributedState
compile_pglocal_stateN
all_states)	r   r   r   r   r   r   r   r   r   r   r   r   r   r   3  s!    O-1Jj)*1r   r   c                       e Zd ZU  e       Zee   ed<   ededdfd       Zedede	fd       Z
ed	d       Zede	fd       Zy)
TensorifyStateforce_specializationsr   r   Nc                 :    | j                   j                  |       y r{   )r   addclsr   s     r   
specializezTensorifyState.specialize@  s    !!%%e,r   c                     || j                   v S r{   )r   r   s     r   should_specializez TensorifyState.should_specializeD  s    1111r   c                 8    | j                   j                          y r{   )r   r   r   s    r   r   zTensorifyState.clearH  s    !!'')r   c                 2    t        | j                        dk(  S r   )r   r   r   s    r   emptyzTensorifyState.emptyL  s    3,,-22r   r   N)r   r   r   setr   r   r   classmethodr   r   r   r   r   r   r   r   r   r   :  s     '*e3s8+-s -t - - 2c 2d 2 2 * * 3d 3 3r   r   c                  4    t        j                  t              S r{   )torchdynamo_loggingget_step_loggerlogr   r   r   _step_loggerr   Q  s    ..s33r   InstructionTranslatorBasec              #   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   V  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   h  sA     $ii## %		 #				s   A+A AAAc                   \    e Zd ZU eed<   eed<   eed<   dZeee	e
f      ed<   d Zd Zd Zy)	BlockStackEntryr   targetstack_indexN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   r6   tupler   s    r   	resume_fnzBlockStackEntry.resume_fn  s    +++))?;!!//  1$eD,=,=,K,K&L  t//!344r   c                     | j                   J |r| j                   j                         s|s| j                   j                  |      S y r{   )r   exit_on_graph_breakexit)r   r   is_graph_breaks      r   r  zBlockStackEntry.exit  sG      ,,,t00DDF$$))"--  r   )r   r   r   r"   r   r   r   r   r	   rP   rQ   r   r   r  r   r   r   r   r   r  sJ      	 (%'EEF -5.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)ReturnValueOpNr  r   r   r   r  r    r  r   r  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
  fn.c                     t        t        j                  |       j                        t	        |       t        j                  |       dddt        ffd       }|S )Nr   InstructionTranslatorr   c                 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   inspect	signature
parametersrN   	functoolswrapsr"   )r  r  r  r  s     @@r   stack_opr    s]    !!"%001ER F__RD* D+ D D Kr   r   truth_fnr  c                 R   |t         j                  us|ryt        | j                  t              sJ | j                  }| j
                  |   }|j                  dk7  ry|dz  }d}| j
                  |   }|j                  dk(  rrt        |j                  t              sy|j                  }|dz  }| j
                  |   }|j                  dvry|dz  }|j                  dk(  r|dz  }| j
                  |   }|j                  dk7  ry| j                  t        j                  |             y	)
NFLOAD_ASSERTION_ERRORr   zassertion error
LOAD_CONST)CALL_FUNCTIONPRECALLCALLr   RAISE_VARARGST)operatortruth
isinstancer   r   instructionsr   argvalr   r  rO   create)r   r  r  current_instruction_pointerr   	error_msgs         r   &_detect_and_normalize_assert_statementr+    s.   , 	&4d..444"&":":89D{{,,1$ "I89D{{l"$++s+KK	 	$q(#  !<=;;BB 	$q(#;;)#'1,'  !<={{o%II%%i01r   Fc                 r   |(t         j                  j                  j                         }	 |d   j                  |d   j
                  f}d}t        j                  r/t               }dj                  t        j                  |            }nt               |z   }t        |      }dj                  t        j                  |            }d|d    d|d    d	| d
t        j                  r| d| dz  nt        |      z  t         j                  j!                  dd fd       t"        j%                  t&        j(                        r1t*        s+t-        j.                  |      rt"        j1                         y t"        j1                  d|d   |d   |       y # t        $ r | d   | d   f}Y iw xY w)Nco_filenameco_firstlinenor   zGraph break in user code at r   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!log_graph_break.<locals>.<lambda>  s    / 
 r   c                  B     d rt        j                          S d S )Nr   r   )	traceback
format_exc)exc_infouser_stack_traces   r   r   z!log_graph_break.<locals>.<lambda>#  s+    ./rH)2F2F2H1]^ Z\1]^ r   )metadata_fn
payload_fnzmGraph break (user stack suppressed due to duplicate graph break) in user code at %s:%s
Graph Break Reason: %s)torch_guardsr   extract_stackr   r   
IndexErrorr   verboser+   r   r6  format_listr)   r   _loggingtrace_structuredgraph_break_logisEnabledForr   DEBUGexplainrD   r   debug)	code_optionsr   r8  
user_stack	frame_locstack_above_dynamo_formattedstack_above_dynamouser_stack_formattedr9  s	     `     @r   log_graph_breakrO    s   ]]11??A

^,,jn.C.CD	 $& ~~35')ww!!"45(
$ ,-
:
+J7
779#8#8#DE
&y|nAil^ D%h '!	!  ~~+, -a#$ %HH	
 	C 455	NN##
 _ $  	$$W]]3+//	:
 		
 	|aLaL		
}  
 ')*
	
s   F F65F6c                 z     ddg t         j                  dd	fd	dddt        f fd}|S )
NzData-dependent branchingzyDetected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.z1Use `torch.cond` to express dynamic control flow.c           	         t        | j                  t        
d| 	             | j                         sJ | j	                         r=d| j                          }t        j                  |       t        j                  |      | j                  |       t        j                  d       | j                  j                  | t        dt        |       | | j                         g      d      }| j!                          | j#                  | j$                  |      }r| j                  |       | j#                  |j&                  |      }t(        j*                  d	k\  r%| j                  j-                  t/        d
      g       t/        |j0                  |d         }|j3                  |       | j                  j-                  |g|z   |z          y )Nattempted to jump with gb_typecontextexplanationhintsr   BSkipping frame because there is a graph break in a for/while loop
zgeneric_jump triggered compilezgeneric_jump r   r   
stack_pops      TO_BOOLr   )r   )rO  rI  r*   should_compile_partial_graphmaybe_has_backedgeframe_summaryr   infor   	SkipFramer  rH  r   compile_subgraphr1   rH   popcreate_call_resume_atnext_instructionr   sysversion_infoadd_output_instructionsr   r   copy_positions)r   r   value	extra_msgmsgall_stack_locals_metadataif_nextif_jump	jump_inst_explanation_gb_type_hintsr  s            r   jump_graph_breakz&generic_jump.<locals>.jump_graph_breakK  s   - 1%9(		
 00222""$U%%'(*  HHSM--$$		%		23$(KK$@$@%/	{;d>P>P>R=S  %A %
! 	
,,!!#<
 IIe,,T[[:STw&KK//1CI1N0OP&t{{71:F	  &++YK',AG,KLr   r   r   r   c                 d   | j                         }t        j                  rBt        |       r4| j                         }|j	                         rmt        |j                               r| j                  |      S | j                         r | ||       n(t        dd| dg t        j                  ddd       t        |t              rJ | j                  j                  dt         j"                  gt%        ||fi         | j                  |       y t        |t&              r|j(                  }t        |t         j*                        s|d	k7  }t         j,                  j.                  j0                  j3                  |      }|s(t        d
t5        |      dg t        j6                         | j                  |       y  | j                  j                  dt         j8                  gt%        |fi        }t;        | |t=        |j>                  |             } | j                  j                  dt         j"                  gt%        ||fi         | j                  |       y |j	                         rt        |t@              r>|jB                  r2tE        |jB                  jG                  tH        jJ                                |j                               r%r| jM                  |       | j                  |       y y t        |t              r| j                         r | ||       y t        |tN              rS| j                  jQ                  |jR                        } |      r%r| jM                  |       | j                  |       y y t        |tT              r(	 |jW                  | d      }	t        |	t^              r|	ja                  | g i       }t        |tb              rWt        |jd                  t
        tf        f      r7 |jd                        rr| jM                  |       | j                  |       y t        |t&              r5|ji                         rir| jM                  |       | j                  |       y t        dd|	 d| dg        y  d      r%r| jM                  |       | j                  |       y y y y t        |t              sW|jk                  |       rF tm        |jo                  |                   r%r| jM                  |       | j                  |       y y t        |t&              r	 t        |j(                  t         j*                        r|ji                  | j                        }
ntq        |j(                  d	k7        }
 |
      r%r| jM                  |       | j                  |       y y t        |tt        jv                        r. d      r%r| jM                  |       | j                  |       y y ddl!m<} |jB                  N ||jB                        r< |j{                               r%r| jM                  |       | j                  |       y y t        d|        y # tX        jZ                  $ r] tY        j\                  |        	 |jW                  | d      }	n0# tX        jZ                  $ r tY        j\                  |        d }	Y nw xY wY =w xY w# tX        jr                  $ r*}| j                         r | ||d|       cY d }~S  d }~ww xY w)Nz>Data-dependent assertion failed (cannot compile partial graph)zvalue: zuDynamo has determined when encountering a data-dependent assert failure that it should not compile the partial graph.zUse `torch._assert()` to raise a hard AssertionError when the check fails. This error will propagate back the user code that called the compiled function (i.e. Dynamo will not trace any exception handling).zRemove the assert statement.zMove the assert statement outside of any context managers in order to graph break with partial graph compilation (if fullgraph=False).rS  r  r   z#Assertion failed on symbolic shapesr   )example_value__bool____len__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   )rn  r   )is_constant_sourcerR  )>rf  r    rewrite_assert_with_torch_assertr+  is_python_constantr   as_python_constantjumpr`  r,   r   FUNDAMENTALr%  rl   r   create_proxyr<  _assert_asyncrG   rk   sym_numSymBoolfxexperimentalsymbolic_shapesexpect_truer   
USER_ERRORscalar_tensorrM   rA   noderS   sourcer0   
make_guardr/   SEQUENCE_LENGTHr  ri   get_submodule
module_keyrs   var_getattrr   ObservedAttributeErrorhandle_observed_exceptionr[   r  rO   rm  r   evaluate_exprhas_unpack_var_sequencer   unpack_var_sequencer   	UserErrorr   BackwardHookVariabler|  get_real_value)r   r   rm  r*  sym_exprresultscalar_to_tensor_proxyscalar_to_tensormodxeval_resulter|  rt  ru  rv  rw  r  r  s                r   innerzgeneric_jump.<locals>.innery  s*   !%336tXtL)-I'')002399T?*668$T47$ `")% 1%H.::u
 ;N* %0(((#'' '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
 u~/D4U4U4WT4//0++++E,<,<=C}IIe$		$  89	%%dJ7 !/0r26f&67JLL4+=  - IIe,		$8++- IIe,		$$ U"*1#Zx @%X  D>		%(IIdO " . .. E>2u7T7T8
 E55d;<=IIe$		$ > / emmU]];"'"5"5dkk"BK",U]]a-?"@K
 $IIe$		$ % y==>~IIe$		$ 
 3||',>u||,LE0023		%(IIdO 4
 !$5eW= , 	] -- --d3))$	:A11 11$7Ap == 446+D$2aSRRs[   Y? >A[2 ?([/(Z;:[/;*[(%[/'[(([/.[/2\/\*#\/)\**\/)r   )r   r  r"   )r  r  r  rt  ru  rv  rw  s   `` @@@@r   generic_jumpr  ?  sb    )H	@ 		&	&;F
,M ,M\{/ {{ { {z Lr   c                       fd}|S )Nc                      t        j                         dddt        f fd       }dddt        dt        ffd|S )Nr   r   r   c                 P   | j                         }|j                  r"|j                  J  | ||j                        S 	  | |      S # t        $ r@}| j                  r>|j                          t        dd| j                   ddgt        j                  |       t        |t        j                        r | j                         s t        | j                  dt        |      |j                          | j#                         r>d| j%                          }t&        j)                  |       t        j*                  |      ||j                          |j-                  d	       t/        |j0                  |j                         |_        Y d }~nd }~ww xY w|j3                          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.)rT  rU  rV  rW  from_excT)r8  r   rJ  rY  graph_break)	speculater   r   r-   active_generic_context_managersremove_from_statsr,   r   CAUSED_BY_EARLIER_GRAPH_BREAKr%  r   UncapturedHigherOrderOpErrorr`  rO  rI  r   
real_stackra  rb  r   rc  rd  add_to_statsr1   ro  r   )r   r   speculationexcpro  handle_graph_breakinner_fns        r   wrapperz>break_graph_if_unsupported.<locals>.decorator.<locals>.wrapper;  s   ..*K!!"))555)$k6H6HII)Sd++ 'S77 **,$ R"CDDhDhCi j %Dc.LL "&	 dC$D$DE88:%%!t9#	 **,]--/02  HHSM--,$6&&(!!-0%7$//%R""O'SP 113s   A
 

FD6FFr   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                        }| j                  j                  | ||z
        }t        |       }g }| j                  D ]  }t        |j                  t              r:|j                  |j!                         j#                  |j$                  |             W|j                  J t        |j                  t&              sJ |j                  j)                  |       |j                  |j!                         j+                  |j$                  |              | j                  j-                  |j/                                ~t         j                  dk\  r|j                  dk(  r| j0                  | j0                  j3                         nd}t5        |      dkD  r<t         j                  dk  sJ | j                  j-                  t7        d	|
      g       t9        |j                  d      }	|	d   j;                  |       | j                  j-                  |	       nF|j<                  J t?        j>                  |      }
d |
_         | j                  j-                  |
g       | j                  j-                  |       | jC                  |z
         tE              D ]  }| jG                  tI                       | j                  j-                  | jK                  | jL                  |             y )Nr]     r]     r!  r   rZ  r   r   r\  KW_NAMESr'  Fr-  )'ri  rj  r   disstack_effectopmapargopcoder   re  r&   block_stackr%  r   rn   extend_outputr   try_except_torch_function_moderI  rP   reconstruct_typetry_finallyrk  get_instructionskw_namesr  r   r   r   rl  r   copyexn_tab_entryr  ranger  rh   rg  rh  )r   r   r   r  rp  cgcleanupbr  
call_insts	inst_copyr   r  s               r   r  zIbreak_graph_if_unsupported.<locals>.decorator.<locals>.handle_graph_breakm  s      G+$$w.KK6)  #//IIi($(( $$SYYv%6A B  #//TXXF(,(D(DV|0C )E )% 4B)+G%% V ann.GH$$DDOOW
 ~~111!!..3JLLL//3  !:!:2??G!TUV KK//0C0C0EF7*t{{f/D }}0 MM446 
 x=1$++g555KK77+JxHI 2$((EB
2--d333J? {{*** IIdO	*.	'33YK@KK//8IId\)*4[ -		/+,-KK//**))+Dr   )r  r  r"   r1   )r  r  r  r  s   ` @r   	decoratorz-break_graph_if_unsupported.<locals>.decorator:  sY    		"/	45 /	4[ /	4 
#/	4bG	-G	G	 'G	R r   r   )r  r  s   ` r   break_graph_if_unsupportedr  9  s    || r   c                   $     e Zd ZdZd fdZ xZS )BytecodeDistpatchTableMetazTInstalls a `cls.dispatch_table` on every subclass to speed up calls to self.OPCODE()c                 >   t         	|   |||       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).rS  r,   r   SUPPORTABLE)r   r   s     r   _missingz5BytecodeDistpatchTableMeta.__init__.<locals>._missing  sS    2!(+dV4[\b[ccef;F8 D_ _ '22		r      )super__init__r  r  r   getattrr  partialr  getdispatch_table)
r   r   basesdctr  r   opr  i	__class__s
            r   r  z#BytecodeDistpatchTableMeta.__init__  s    uc*
	 "iioo/
 VY%6%6x%HII
 
 >C4[In003I	
 Js   ,B3Br   )r   r   r   r   r  __classcell__r  s   @r   r  r    s    ^J Jr   r  c                       e Zd ZU dZ ej
                  e      Zee   e	d<    ej
                  d      Z
ee   e	d<   d Zd Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd ZeZy)ExceptionStackzU
    Exception stack that it is shared among all InstructionTranslator instances
    r   
_exc_stackN)default_current_exceptionc                     d | _         y r{   r  r   s    r   clear_current_exceptionz&ExceptionStack.clear_current_exception  s
    "&r   c                 4    | j                  |       || _        y r{   )._set_context_and_break_context_reference_cycler  r   vals     r   set_current_exceptionz$ExceptionStack.set_current_exception  s    ;;C@"%r   c                 v    | j                   J | j                  | j                          | j                          y r{   )r  r   r  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{   r  r   s    r   get_current_exceptionz$ExceptionStack.get_current_exception  s     &&222&&&r   c                     |j                   x}rt        |      t        ur|S t        | j                        |z   dkD  r5| j                  |   }| j                  ||dz
         |j                  |       |S Nr   r   )__context__typerO   r   r  _set_context_recursiveset_context)r   r  prev_idxctxprevs        r   r  z%ExceptionStack._set_context_recursive  sk    ??"C"S	9I(IJt(*Q.??8,D''hl;OOD!
r   c                     |x}}d}	 |j                   }t        |      t        u ry ||u r|j                  t        d              y |}||u ry |r|j                   }| }Vr   )r  r  rO   r  )r   r  oslow_oslow_update_togglerU  s         r   _break_context_reference_cyclez-ExceptionStack._break_context_reference_cycle  sy    
 F"mmGG} 00#~.t45AF{ !++%7!7# r   c                 v    | j                  |t        | j                        dz
         | j                  |       y )Nr   )r  r   r  r  r  s     r   r  z=ExceptionStack._set_context_and_break_context_reference_cycle  s.    ##CT__)=)AB++C0r   c                 6    | j                   j                         S r{   )r  rf  r   s    r   rf  zExceptionStack.pop   s    ""$$r   c                 :    | j                   j                  |       y r{   )r  r   r  s     r   r   zExceptionStack.append#  s    s#r   c                 ,    t        | j                        S r{   )r   r  r   s    r   r{  zExceptionStack.__len__&  s    4??##r   c                      | j                   |   S r{   )r  )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=)r  r  r   s    r   __str__zExceptionStack.__str__,  s"    "$//##?t'>'>&@AAr   )r   r   r   r   r   r   r   r  rJ   r   r  r   r  r  r  r  r  r  r  rf  r   r{  r  r  __repr__r   r   r   r  r    s     ):(9(9$(OJ_%O4EK4E4Ed4S1S'&'
'841
%$$&B Hr   r  c            %       H    e Zd ZU eed<   eeef   ed<   eeef   ed<   eed<   e	e   ed<   e
e   ed<   eed<   e	e   ed<   eed	<   e
e   ed
<   eed<   e	e   ed<   eed<   eed<   e
e   ed<   e	e   ed<   eed<   e
e   ed<   e
eegef      ed<   e
e   ed<   eed<   e
d    ed<   e	eee	e   f      ed<   e
d   ed<   d Zd Zd Zd Zd Zd Zd ed!e	e   d"eeef   fd#Zd$ Zd% Zdd'Zd( Z d) Z!d* Z"e#jH                  d+k\  rd, Z%nd- Z%e&d.        Z'd/ Z(d0 Z)d1 Z*d2e
e   fd3Z+d4e	e   fd5Z,d6efd7Z-d8ed6e	e   fd9Z.d: Z/d; Z0d< Z1d= Z2d> Z3e/Z4d? Z5d@ Z6dA Z7e8jr                  dB        Z:dC Z;dD Z<e=dE        Z>dF Z?dG Z@dH ZAeAZBdI ZCe=dJ        ZDdK ZEdL ZFeFZGeFZH eIeJj                  dM      ZL eIeJj                  dM      ZN eIeJj                  dN      ZO eIeJj                  dN      ZPdO ZQdP ZRdQ ZSdR ZTdS ZUdT ZVdU ZWdV ZXdW ZYdX ZZd6e[fdYZ\dZ Z]d[ Z^d\ Z_d] Z`d^ Zad_ Zbd` Zcda Zddb Zedc Zfdd Zgde Zhdf Zi ejdgh      di        Zk ejdgh      dj        Zl ejdgh      dk        Zmdl Zndm Zodn Zpdo Zqdp Zrdq Zsdr Ztds Zudt Zvdu Zwd6efdvZx ejdwh      dx        Zydy Zzdz Z{d{ Z|d| Z}d} Z~efd~Zd ZeZd Zd ZeZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZeZd Zd Zd Zd Zd Zd Zd Z eeJjP                        Z eeJjT                        Z eeJj                        Z eeJjZ                        Z eeJj^                        Z eeJjb                        Z eeJjf                        Z eeJjj                        Z eeJjn                        Z eeJjr                        Z eeJjr                        Z eeJjx                        Z eeJj|                        Z  ejdgh       eeJj                              Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Z eeJj                        Zd Ze#jH                  d+k\  rd Zd Zd Zd ZddZ ejdgh      d        Zd Zd ZeFZeFZ eIeJj                  dM      Z eIeJj                  dM      Z eIeJj                  dM      Z eIeJj                  dM      Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Zd Z ejdgh      d        Zd Zd Zd Zd Zd Zd Z	ddZ
d Zd Zd Ze&dÄ        Zej                   deegef   fdń       Zd6efdƄZ	 	 ddede	e   deeef   deeef   deeef   deeef   deeef   deeef   ded̐ej(                  dededΐedede
e   de
eej.                        de
d   d6d&f$ fdфZ xZS )r   r   symbolic_localssymbolic_globalssymbolic_torch_function_statestackr   current_instructionr  r   r  accept_prefix_instprefix_instsinline_depthinconsistent_side_effectscurrent_speculationr  exn_vt_stackexec_recorderstrict_checks_fnstart_pointis_leaf_tracerparentdebug_localsrt   packagec                     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_effectsN  s     *.&r   c                     | j                   j                  }| j                  J | j                  | j                  d  D ]8  }|j                  dv r y|j                  t
        v s&|j                  }||k  s8 y y)N)RETURN_VALUERETURN_CONSTFT)r  offsetr   r&  r   r   r'  )r   
cur_offsetr   jump_offsets       r   ra  z,InstructionTranslatorBase.maybe_has_backedgeV  s    ( --44
''333%%d&>&>&@A 	 D{{>>{{l*"kk+	  r   c                     t        | d      s^t        | j                  d   xs g       | _        t	        | t
              r-| xj                  | j                  j                         z  c_        | j                  S )N	_cellvarsco_cellvars)r   r   rI  r-  r%  InliningInstructionTranslatorr!  cellvarsr   s    r   r0  z"InstructionTranslatorBase.cellvarsu  Z    t[)"4#4#4]#C#IrJDN $ =>$++"6"6"88~~r   c                     t        | d      s^t        | j                  d   xs g       | _        t	        | t
              r-| xj                  | j                  j                         z  c_        | j                  S )N	_freevarsco_freevars)r   r   rI  r3  r%  r/  r!  freevarsr   s    r   r5  z"InstructionTranslatorBase.freevars~  r1  r   c                 ~    t        | d      s&| j                         | j                         z   | _        | j                  S )N_cell_and_freevars)r   r0  r5  r7  r   s    r   cell_and_freevarsz+InstructionTranslatorBase.cell_and_freevars  s2    t12&*mmo&GD#&&&r   c                 
   t        | j                  | j                        }| j                  j	                         D ci c]  \  }}||v s|| c}}| _        | j
                  j                  j                  |        y c c}}w r{   )r   r&  r  r  r   r   side_effectsprune_dead_object_new)r   readsr   r   s       r   prune_dead_localsz+InstructionTranslatorBase.prune_dead_locals  sn    !$"3"3T5M5MN!11779 
QQ%ZAqD 
 	  66t<	 
s   A?A?r  r   kwargsc                    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{   )r%  rJ   )r   r  s     r   r   z:InstructionTranslatorBase.call_function.<locals>.<genexpr>  s      
 q/*
   rm  r  z$Attempt to trace forbidden callable )r%  rJ   r   r   all	itertoolschainvaluesr   rm  r  callabler?   AssertionErrorr  r  )r   r  r   r>  r  s        r   r  z'InstructionTranslatorBase.call_function  s     "o...$%%%&$''' 
__T6==?;
 
 	
 
 2wxxH2tuuH*|H/E #Gz!RSS		"""4v67r   c                 ^    t        |t              st        |      }|j                  | ||      S )zD
        Redirect the call to the generator "call_function"
        )r%  rV   r  r   r  r   r>  s       r   inline_generator_functionz3InstructionTranslatorBase.inline_generator_function  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_coderJ  r/  inline_callrI  s       r   inline_user_function_returnz5InstructionTranslatorBase.inline_user_function_return  sF     44bkkm9T11"dFCC0<<T2tVTTr   Nc                     || j                   }| j                  dkD  rd| j                   dnd}t        | j                  j                  |      }|dnd| d}| j                  j                   d| d| j                  j
                   | | S )Nr   z (inline depth: )r   r   r   z in )r   r  r.   f_coder.  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   z    )rW  	linecachegetlinerR  r.  r   rstrip)r   log_strlines      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_locrR  r.  rS  is_trace_source_log_enabledtrace_source_logrH  rF   r^  )r   r   s     r   starts_linez%InstructionTranslatorBase.starts_line  sl    ;;& &&KK##VT[[-@-@	
 ++""4D4T4T)UV ,r   c                    | j                   }|y| j                  |   x| _        }|dz   | _         |j                  r| j                  |j                         | j                  s\| j                         rL| j                         r<| j                         | _        | j                  j                  r| j                  |      S | j                  r6t        j                  d|j                  |j                  | j                         | j!                  |       	  | j"                  |j$                     | |       | j&                  j(                   S # t*        $ r  t,        j.                  $ r}| j1                  |       Y d}~yd}~wt2        t4        f$ r Y yt6        $ r< | j                  t8        j                  d        t8        j                  dd       Y nw xY w| j                  j;                          y)	z<Process exactly one instruction, return False we should exitNFr   zTRACE %s %s %sTzempty checkpointzstep triggered compiler8  )r   r&  r  rd  r  r`  is_non_empty_graphr  r  r   step_graph_breakis_trace_bytecode_log_enabledtrace_bytecode_logrH  r   r'  update_block_stackr  r  r   r   r   r   ObservedExceptionexception_handlerr  r
  r-   r   r   )r   ipr   r  s       r   stepzInstructionTranslatorBase.step  s   %%:*.*;*;B*?? 4#%6 T--. 

113'')'+~~'7D$''..,,T22--$$ $++t{{DJJ 	%	?,D,T48{{....- 	$$ 	""1%|, 	 	?''/		,-II.I>		? 	  ::<s%   6E
 
G&E<<GAGG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   r-  )NOPJUMP_BACKWARDr   )r  r   r  r   rf  r   )r   r   r   s      r   rk  z,InstructionTranslatorBase.update_block_stack  s     &&E (()Q.D,<,<R,@,G,GG(8(8(<(C(CC $$((* D H /  ##;S(S t//0A555$$((* )T#r   c                      y r{   r   r   r   s     r   rk  z,InstructionTranslatorBase.update_block_stack/  s    r   c                 4    | j                   | j                     S r{   )r&  r   r   s    r   rh  z*InstructionTranslatorBase.next_instruction2  s      !9!9::r   c           	      >   | j                   j                  rJ | j                  J | j                  rJ | j                   j	                  | dt        d| j                         g             | j                   j                  t        |      g| j                  z          y )NTstep_unsupported)partial_convertr   )
r   output_instructionsr  r  re  r1   rb  rk  r   r&  )r   continue_insts     r   rh  z*InstructionTranslatorBase.step_graph_break6  s    ;;2222''333 ::~$$ %&84;M;M;O:PQ 	% 	

 	++!-01D4E4EE	
r   c                 ,    t        j                  d       S r{   )r   current_framer   s    r   run_ctx_mgrz%InstructionTranslatorBase.run_ctx_mgrG  s     ++D11r   c                 `   | j                         5  t        | j                  j                         	 | j                  j                  |        | j                  | _        | j                         r	 | j                         r| j                  j3                          t5        | t6              r5| j                  j9                          | j                  j;                          	 d d d        y # t        $ r  t        $ r  t        $ r}t        |d      rpd|j                  v rbt        j                  j!                  | j                  j"                  | j                  j$                        j'                  ddd      }||_          d }~wt*        $ r1}| j,                  r| j,                  j/                         |_         d }~ww xY w# | j                  j3                          t5        | t6              r5| j                  j9                          | j                  j;                          w w xY w# 1 sw Y   y xY w)Nro  zData-dependentFT)print_outputinclude_strideinclude_device)r  r   rR  r.  r   push_txr   r  ro  r   r(   RuntimeErrorr   ro  r<  r  GraphModule
nn_modulesgraphprint_readablepartial_fx_graph	Exceptionr  
get_recordexec_recordpop_txr%  r  r  mark_bytecode_tracing_stop)r   r  readable_graphs      r   runzInstructionTranslatorBase.runM  s    (	=dkk--.&=##D)#'#;#; iik iik. ""$ d$9:KK'')
 KK::<Q(	= (	= 2 (  
1e$)9QUU)B%*XX%9%9..0A0A&$n%*4PT %  #
 *8A& %%$($6$6$A$A$CAM	 ""$ d$9:KK'')
 KK::< ;E(	= (	=sJ    H$AC( AH$(F=A=F  F=,F88F==G  A!H!!H$$H-r  c                     |#t        |t              sJ dt        |              | j                  j	                  |       y )Nz"push expects VariableTracker, got )r%  rJ   rH   r  r   r  s     r   r  zInstructionTranslatorBase.pushx  s?    {jo> 	
0?	
> 	

#r   valsc                 4    |D ]  }| j                  |        y r{   r  )r   r  r  s      r   	push_manyz#InstructionTranslatorBase.push_many~  s     	CIIcN	r   r   c                 6    | j                   j                         S r{   )r  rf  r   s    r   rf  zInstructionTranslatorBase.pop  s    zz~~r   nc                 p    g t        t        |      D cg c]  }| j                          c}      S c c}w r{   )r}   r  rf  )r   r  r   s      r   r  zInstructionTranslatorBase.popn  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)N.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 comprehensionsrS  z*Attempted to read undefined local variablez+Could not find a local variable with name `__stack)r'  r  f_localsadd_local_varr  r  unwrapKeyError
startswithreplacer,   r   r  rf  )r   r   r   new_names       r   	LOAD_FASTz#InstructionTranslatorBase.LOAD_FAST  sP   {{$$--"7,,T4==3FG	IId**40779:4 ??9%  $$T* &3  	s##||C<HIId228<= 	$ W",TF 3&[\`[aab$cF.99		 !H(/"MdVST U9-889	#	s6   ,B+ +E0C76E70D*'E)D**)EEc                    |j                   | j                         v sJ | j                  |j                      }| j                  j                  j                  |      }| j                  |       | j                  rW|j                   | j                  v r>| j                  j                  |j                   | j                  |j                             y y y r{   )
r'  r8  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                  |<   y r{   )r'  rf  set_name_hintr  )r   r   r   	loaded_vts       r   
STORE_FASTz$InstructionTranslatorBase.STORE_FAST  s4    {{HHJ	%%.T"r   c                 2    | j                   |j                  = y r{   )r  r'  rv  s     r   DELETE_FASTz%InstructionTranslatorBase.DELETE_FAST  s      -r   c                 R   |j                   | j                         v sJ | j                  |j                      }| j                         }| j                  j
                  j                  ||       t        |t              sJ |j                  |j                  |j                         y y r{   )r'  r8  r  rf  r   r:  
store_cellr%  rc   
local_namer  )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                        x| j                  |<   }|S )Nrm  )r  rO   r(  r'  _constants_cache)r   r   r  r  s       r   _load_constz%InstructionTranslatorBase._load_const  sa    HH9#**==##A&-=-D-D4;;-WWD!!!$s
r   c                 D    | j                  | j                  |             y r{   )r  r  rv  s     r   r  z$InstructionTranslatorBase.LOAD_CONST  s    		$""4()r   c           	         |j                   }| j                  rn|| j                  v r*| j                  j                  || j                  |          n6|| j                  v sJ | j                  |   | j                  j
                  |<   || j                  vr| j                  |      S || j                  v r\| j                  j                  | j                  |      }| j                  | j                  j                  j                  ||             y | j                  |   }| j                  t        j                  | |t        |                   y r{   )r'  r  	f_globalsadd_global_var
f_builtinsbuiltinsload_builtinr  r   r:  r  load_globalrJ   buildr9   )r   r   r   variablerm  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   rJ   r  )r   module_namemodule_sourcefglobals_values       r   nn_modules_globals_vtz/InstructionTranslatorBase.nn_modules_globals_vt  s6    /**;7'4$$T>=IIr   c                    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\  rq  )ri  rj  r  	PUSH_NULLr  rv  s     r   LOAD_GLOBALz%InstructionTranslatorBase.LOAD_GLOBAL  sn    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.rS  )rf  r'  r9   r  objectr   r:  track_global_existingr%  ro   r,   store_global)r   r   rm  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                  }||vs	||   |u sJ |||<   | j                  j                  |       t        |      S )z-Create an alias to a module for use in guardstorch_package>r   <r  _dot_	__import_)r<  r#  package_importer_package_imported_modulesr  r   add_import_sourcer   global_scopeupdate_co_namesr9   )r   r  rm  aliasr  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+>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
        r  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__r  r   )r  r  r!  r   warning
rpartition)r   r#  specs      r   calc_packagez&InstructionTranslatorBase.calc_package.  s    
 ..$$]3~~!!*-Gt{{$:?KK 	   N;;KK8  
 nnZ0G/!,,S1!4r   c           
      l   | j                  d      \  }}|j                         }|j                         }|j                  }t        j                   d| d| d| }|| j
                  v r| j
                  |   }t        |      }n{	 t        |||| j
                        }|d
k7  r#| j                         }| j                  |||      }|s&|j                  d      d
   }	| j                  |	      }n| j                  |      }| j                   r| j                   j#                  |       t%        t&        j(                  t*        f      r| j-                  t/        ||             y t        dt1        |      dg 	       y # t        $ r, t        dd| d| d| dg t        j                  	       Y w xY w)Nrq  r   )fromlistr  globalszImport failurezmodule_name: z, fromlist: z, level=z"Failure when attempting to import.rS  r   r  r  zBad import resultz%Import result is not a Python module.)r  r  r'  r4   LOCAL_MOD_PREFIXr  r9   
__import__r  r,   r   r  r  r  	partitionr  r  add_local_modrE   types
ModuleTyper3   r  rg   rH   )
r   r   r  r  r  recorded_namerm  r  pkgtop_level_module_names
             r   IMPORT_NAMEz%InstructionTranslatorBase.IMPORT_NAMEK  s   ))A,x((*..0kk !112!E7!H:Q{mT 	 DNN*NN=1E!-0F"% NN	 z'')"//S%H (3(=(=c(B1(E%++,AB++K8,,]EB%%**K89II*5@A+C	;   ,+K=XJhW\V]^ D9-889	 s   E> >1F32F3c                 H    | j                  |       | j                  |       y r{   )DUP_TOP
_load_attrrv  s     r   IMPORT_FROMz%InstructionTranslatorBase.IMPORT_FROM  s    Tr   c                 :   || j                   vrt        d| d      | j                   |   }t        |      rBt        | j                  j
                        }t        ||      }t        j                  | ||      S t        |      sJ t        j                  |      S )Nzname 'z' is not definedr  )r  r-   rF  r9   r   %name_of_builtins_dict_key_in_fglobalsr8   rJ   r  r>   rO   r(  )r   r'  r  builtins_source
var_sources        r   load_builtin_from_argvalz2InstructionTranslatorBase.load_builtin_from_argval  s    (vh.>?@@oof%C=*AAO +?FCJ"((sJ??&s+++#**55r   c                 X    | j                  | j                  |j                               y r{   )r  r  r'  rv  s     r   r  z&InstructionTranslatorBase.load_builtin  s    		$//<=r   c                     | j                   J | j                  J t               j                  d| j                   | j                  z
         | j                  |j
                     | _         | j                   | _        y )Nir_count)r   r  rC   	incrementindexofr   rv  s     r   r  zInstructionTranslatorBase.jump  sr    ''333+++''0043C3CC	
 $(<<#< 33r   FTc           	          | j                   j                  t        ||j                  t	        | j
                                     y r{   r  r   r   r   r   r  rv  s     r   
SETUP_LOOPz$InstructionTranslatorBase.SETUP_LOOP  +    dkk3tzz? STr   c           	          | j                   j                  t        ||j                  t	        | j
                                     y r{   r  rv  s     r   SETUP_EXCEPTz&InstructionTranslatorBase.SETUP_EXCEPT  r  r   c                 8    | j                   j                          y r{   )r  rf  rv  s     r   	POP_BLOCKz#InstructionTranslatorBase.POP_BLOCK  s    r   c                 &    | j                  |       y r{   setup_or_before_withrv  s     r   
SETUP_WITHz$InstructionTranslatorBase.SETUP_WITH      !!$'r   c           	          | j                   j                  t        ||j                  t	        | j
                                     y r{   r  rv  s     r   SETUP_FINALLYz'InstructionTranslatorBase.SETUP_FINALLY  s+    dkk3tzz? STr   c                 &    | j                  d        y r{   r  rv  s     r   BEGIN_FINALLYz'InstructionTranslatorBase.BEGIN_FINALLY  s    		$r   c                     | j                  d      \  }}|J | j                  |       | j                  |j                  | t        j                  d       gdz  i              y )Nrq  r]  )r  r  r  rO   r(  )r   r   r  r   s       r   WITH_CLEANUP_STARTz,InstructionTranslatorBase.WITH_CLEANUP_START  sX    IIaL	c{{		#		$$$T,<,C,CD,I+JQ+NPRSTr   c                 H    | j                  d       | j                  d        y )Nrq  )r  r  rv  s     r   WITH_CLEANUP_FINISHz-InstructionTranslatorBase.WITH_CLEANUP_FINISH  s    		!		$r   c                    | j                         j                         }	 |j                  |       }| j                  |       | j                  |       y # t        t
        j                  f$ r}t        |t
        j                        rt        j                  |        t        j                  dk\  r5| j                  |       | j                  t        j                  d              | j                  |       Y d }~y d }~ww xY wNr  )rf  realizenext_variabler  StopIterationr   ObservedUserStopIterationr%  r  ri  rj  rO   r(  r  )r   r   itr  r  s        r   FOR_ITERz"InstructionTranslatorBase.FOR_ITER  s    XXZ!	""4(CIIbMIIcNs<<= 	!S::;--d3 7*
 		"		*11$78IIdOO	s   3A C?-BC::C?c                 l    t        |t        j                  t        f      r|j	                  | g i       }|S r{   )r%  r   rN   rq   r  r  s     r   _create_exception_typez0InstructionTranslatorBase._create_exception_type  s6    )++-NO

 ##D"b1C
r   c                     | j                  |      }t        | j                        rVt        |t        j
                        r<|j                  t        u r*t	        j                  t              j                  | g i       }| j                  j                  |       | j                  |      r*t        j                  |j                        } |d|       t!        dt#        t              dg t$        j&                         y )Nzraised exception zFailed to raise exceptionz.Attempted to raise a non-Exception type/value.rS  )r*  r#   rR  r%  r   rd   exc_typer%  rN   r  r  r  r  _isinstance_exceptionr   get_dynamo_observed_exceptionr,   r   r   r  )r   r  observed_exception_types      r   _raise_exception_variablez3InstructionTranslatorBase._raise_exception_variable  s     ))#.
 %3	 ; ;<-++L9GGbRTUC 	//4 %%c*&)&G&G&U#),=cU*CDD/HH1%001		
r   c                 &   |j                   dk(  rt        | j                        s(t        d      }t	        j
                  t        | |g       t        | j                        sJ | j                  d   }| j                  |      sJ |       | j                  |       y |j                   dk(  r!| j                  d   }| j                  |       y | j                         }| j                         }	 | j                  |       | j                  j                         }| j                  |      }|j                  | t        d      |       y # | j                  j                         }| j                  |      }|j                  | t        d      |       w xY w)Nr   zNo active exception to reraise)r   r-  r   	__cause__)r  r   r  rO   r   raise_observed_exceptionr  r-  r0  r  rf  r  r*  call_setattr)r   r   ro  r  from_vtcurr_exccauses          r   r"  z'InstructionTranslatorBase.RAISE_VARARGS  sW   88q=t(()&'GH,,\4seL t(()))##B'C--c27C72**3/XX]**R.C**3/ hhjG((*CR..s3  ,,BBD33G<%%d,<[,I5Q  ,,BBD33G<%%d,<[,I5Qs   .E A	Fc                     | j                   d   }t        |t              sJ |j                  t        u rt        dddg        y | j                  |       y )Nr-  z CLEANUP_THROW with StopIterationr   zRReceived StopIteration when handling generator.throw/close. This is not supported.rS  )r  r%  rd   r,  r%  r,   RERAISEr   r   toss      r   CLEANUP_THROWz'InstructionTranslatorBase.CLEANUP_THROW'  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  )ri  rj  rf  r'  r0  r  )r   r   r  r   _exc_tbs         r   r9  z!InstructionTranslatorBase.RERAISE5  s     w&((*C{{HHJ..s3 		#..s388:D((*C((*C**3/r   c                 L    t        |t        j                  t        t        f      S r{   )r%  r   rd   rq   rr   r  s     r   r-  z/InstructionTranslatorBase._isinstance_exceptionL  s&    ++12
 	
r   c                    t         j                  dk\  rlt        | j                        dk\  sJ | j                  d   }| j                  d   }| j	                  |      sJ t        |j                        }t        d       }nkt        | j                        dk\  sJ | j                  d   }| j                  d   }| j	                  |      sJ t        |j                        }t        d       }| j                  ||||gi        y )Nr     r-     irr  )	ri  rj  r   r  r-  rN   r,  rO   r  )r   r   r  r  typtbs         r   WITH_EXCEPT_STARTz+InstructionTranslatorBase.WITH_EXCEPT_STARTV  s    w& tzz?a'''BB**R.C--c222!#,,/C!$'Btzz?a'''BB**R.C--c222!#,,/C!$'B2S"~r2r   c           	      >
   d}t         j                  dk\  rQ| j                  j                  }|rt	        | j
                        |j                  kD  r3| j                          t	        | j
                        |j                  kD  r3|j                  r8| j                  t        j                  | j                  j                               | j                  | j                  j                                | j                  |       y | j
                  j!                          t#        |       t$        u r8t'        dt)        |      |g t*        j,                  t*        j.                         |t	        | j0                        r<| j0                  j                         }|j2                  j4                  dk(  r| j7                  d       | j                  j                          t	        | j0                        dk(  rX| j
                  j!                          t#        |       t$        u r+t'        dt)        |      |d	z   g t*        j8                         || j0                  j                         }|j2                  j4                  dk(  r| j                  j                         }| j                  j;                          t	        | j
                        |j<                  kD  r3| j                          t	        | j
                        |j<                  kD  r3t?        d
dd d      }| j0                  jA                  tC        |d t	        | j
                                     t	        | j                        dk\  rr| j                  d   }| j                  t        jD                                | j                  |       | j                  t        jF                  |jH                               nl| j                  t        j                  d              | j                  t        j                  d              | j                  t        j                  d              | j                  t        jD                                | j                  |       | j                  t        jF                  |jH                               | j                  |       y | j
                  j!                          t#        |       t$        u r8t'        dt)        |      |g t*        j,                  t*        j.                         |)NzDynamo found no exception handler at the top-level compiled function when encountering an exception. Exception will propagate outside the compiled region.r  zObserved exceptionrS  EXCEPT_HANDLERr]  r   z#Observed exception (EXCEPT_HANDLER)z  This graph break is unexpected.g    .Arq  rr  )%ri  rj  r  r  r   r  depthrf  lastir  r   rO   r)  r  r  r  r   r  r  r,   r   r   r  r  r  r   r   r  
DYNAMO_BUGr  r   r"   r   r   rh   rN   r,  )r   raised_exceptionobserved_exn_gb_explanationr  block_stack_entryexception_varexcept_handler_instold_exceptions           r   rm  z+InstructionTranslatorBase.exception_handlero  s   d 	$
 w& 44BBM
 $**o(;(;;HHJ $**o(;(;; !&&II!2243K3K3R3RS
 		$++AACD 		-( 

  ":!66$ 4 #$4 5$?.99.::	 '&4##$ %)$4$4$8$8$:!',,337GG IIaL%%))+4++,1 

((*:)>>,(M(+,<(=,G"D-E&E(9(D(D&E /.(,(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#7Gq&Q#  ''#$7s4::O
 t(()Q.$($5$5b$9M IIi779:IIm,IIi778N8NOP IIi88>?IIi88>?IIi88>? 		)3356		-(		)33M4J4JKL 		+, 

  ":!66$ 4 #$4 5$?.99.::	 '&r   c                    | j                         }t        | j                        dk(  rt        d       }n| j                  d   }| j	                  |       | j	                  |       | j                  j                          y )Nr   r-  )rf  r   r  rO   r  r  )r   r   r  prev_excs       r   PUSH_EXC_INFOz'InstructionTranslatorBase.PUSH_EXC_INFO  se    ( hhjt  !Q&'-H((,H		(		#99;r   c                    t         j                  dk\  rB| j                         }t        | j                        sJ | j                  j                          y t        | j
                        dkD  sJ | j
                  d   j                  j                  dk7  rt        d      | j
                  j                          | j                  d       t        | j                        sJ | j                  j                          y )Nr  r   r-  rI  zYBug in Dynamo tracing of exception handling.Top of the block stack is not EXCEPT_HANDLER.r]  )
ri  rj  rf  r   r  r  r   r   rG  r  )r   r   r   s      r   
POP_EXCEPTz$InstructionTranslatorBase.POP_EXCEPT  s    w&
At(()))!!#t''(1,,,#((//3CC$D    "IIaL t(()))!!#r   c                    t        | j                        dk\  sJ | j                         }t        j                  dk\  r| j                  d   }n| j                  j                         }t        |t        t        t        t        f      s,t        dt        |      d| dg t        j                         t        j                  dk\  r=| j                  |      s,t        dt        |      d	| dg t        j                         t        |t              r|j                  }n|g}|D ]  }t        |t        t        t        f      s,t        d
t        |      d| dg t        j                         | j                  |      r"t!        |j"                  |j$                        r yt        |t&        j                        st!        |j$                  |j$                        s y y)Nrq  r  r-  z Exception with bad expected typez"`except ...` has unsupported type r  rS  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  rf  ri  rj  r%  rN   rb   rq   rr   r,   r   r   r  r-  r   
issubclassr,  r  r   )r   expected_exc_typesexc_instanceexpected_typesexpected_types        r   check_if_exc_matchesz.InstructionTranslatorBase.check_if_exc_matches  s   4::!###!XXZw&  ::b>L
  ::>>+L 12	
 :./@AS@TTUV5)445	 w&--l; 8-"efresst u9-889	 (-8/55N #N , 	M#65 !A."CM?RS T9-889	 )),7J%%  = L)*C*CD!1!1J /	2 r   c                 h    | j                  t        j                  | j                                      y r{   )r  r   rO   r^  rv  s     r   CHECK_EXC_MATCHz)InstructionTranslatorBase.CHECK_EXC_MATCHm  s"    		),,T-F-F-HIJr   c                 H    | j                         s| j                  |       y y r{   )r^  r  rv  s     r   JUMP_IF_NOT_EXC_MATCHz/InstructionTranslatorBase.JUMP_IF_NOT_EXC_MATCHp  s    ((*IIdO +r   c                     |j                   dk(  r| j                  |       y | j                  t        |j                      | | j	                  d      i              y )Nzexception matchrq  )r'  r`  r  ry   r  rv  s     r   
COMPARE_OPz$InstructionTranslatorBase.COMPARE_OPt  sD    ;;++  &II)$++6tTYYq\2NOr   c                 b    | j                  t        t              | j                         gi        y r{   )r  rN   iterrf  rv  s     r   GET_ITERz"InstructionTranslatorBase.GET_ITERz  s!    ?40488:,Cr   r   r  c                     | j                  |j                        }| j                         }| j                  ||i        y r{   r  r'  rf  r  )r   r   r   r  s       r   r  z'InstructionTranslatorBase.CALL_FUNCTION}  s1    yy%XXZ2tR(r   c           	         |j                   dk(  rt        i       }| j                         }ni|j                   dk(  r!| j                         }| 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   z%Variadic function call with bad flagszflags: zHAttempted to call a variadic function (CALL_FUNCTION_EX) with bad flags rS  r\  r  z0Variadic function call with bad args/kwargs typezargs type: z, kwargs type: z2Expected args to be a list and kwargs to be a dict)r'  rS   rf  r,   r   rL  ri  rj  r%  rf   r^   has_force_unpack_var_sequencerb   force_unpack_var_sequencers   rN   call_custom_dictr   rH   r  keys_as_python_constantr  r   )r   r   
kwargsvarsargsvarsnullr  s         r   CALL_FUNCTION_EXz*InstructionTranslatorBase.CALL_FUNCTION_EX  s    ;;!*2.JxxzH[[AJxxzH?!$++/fgkgrgrfst5)445	 w&88:DdL111XXZw&3+;+;g+E88:DdL111&
44T:$X%G%G%MNH j";<(99$jQJ($45Z)>
 J%gh&7%8PZH[G\]P5)445	  779
2x~~z:r   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{   )rf  r  r'  r%  rb   r~  r  r   r   zipr  )r   r   argnamesr   r  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                 R   | j                  t        j                  |d             |j                  d   }| j                  d   |   }t
        j                  dk  r'| j                  t        j                  ||             y | j                  t        j                  ||             y )Nrq  r  r   co_namesr  )	r  r   r  r'  rI  ri  rj  r   LOAD_METHODr   r   r  r'  s       r   LOAD_METHOD_SUPERz+InstructionTranslatorBase.LOAD_METHOD_SUPER  s    ;..tA>?kk!n"":.s3g%OOK//VDE[00fEFr   c                     | j                  t        j                  |d             |j                  d   }| j                  d   |   }| j                  t        j                  ||             y )Nrq  r  r   ry  )r  r   r  r'  rI  r   r{  s       r   LOAD_ATTR_SUPERz)InstructionTranslatorBase.LOAD_ATTR_SUPER  sX    ;..tA>?kk!n"":.s3++D@Ar   c                 b   | j                  |       | j                         }t        j                  dk\  r#| j	                  |       | j                  |       y t        j                  dk\  r#| j                  |       | j	                  |       y | j	                  |       | j	                  d        y )Nr\  r  )r   rf  ri  rj  r  r  r   r   objs      r   rz  z%InstructionTranslatorBase.LOAD_METHOD  s{    hhjw&IIcNNN4 ( NN4 IIcNIIcNIIdOr   c                     | j                  |j                        }| j                         }|J | j                         }| j                  ||i        y r{   ri  )r   r   r   dummyr  s        r   CALL_METHODz%InstructionTranslatorBase.CALL_METHOD  sF    yy%
}}XXZ2tR(r   c                     | j                         }t        t              j                  | |t	        j
                  |j                        gi       }| j                  |       y r{   )rf  rN   r  r  rO   r(  r'  r  )r   r   r  r  s       r   r   z$InstructionTranslatorBase._load_attr  sN    hhj )77"))$++67

 			&r   c                     t         j                  dk\  r!|j                  dz  r| j                  |       y | j	                  |       y )Nr  rq  )ri  rj  r  rz  r   rv  s     r   	LOAD_ATTRz#InstructionTranslatorBase.LOAD_ATTR  s8    w&xx!|  &r   c                 j   | j                         }|j                  r| j                  |      S | j                  d      \  }}t	        |t
              r1t	        |t              s!| j                  rJ d|j                   d       	 t        t              j                  | |t        j                  |j                        |gi        y # t        $ rS}| j                         s t        j!                  dd       |j#                          |j%                  d       Y d }~nd }~ww xY w|j'                          y )Nrq  zMutating module attribute z during export.zSTORE_ATTR triggered compileTrf  r  )r  r   store_attr_graph_breakr  r%  ri   rO   exportr'  rN   setattrr  r(  r-   r`  r   rH  r  r  r   )r   r   r  r  r  r  s         r   
STORE_ATTRz$InstructionTranslatorBase.STORE_ATTR  s	   nn&..t4499Q<Sc+,ZEU5V {{ ,T[[MI?	*G$22&--dkk:C@
  	*446II4tID!NN=))	* 	--/s   A C 	D!A	DD!c                    t        | j                  d       | j                         st        dddg        | j                  j                  | t        d| j                         g      d	      }| j                  j                  t        j                  |      g       | j                  d       | j                  j                  | j                  | j                  |             y )
NzSTORE_ATTR-caused graph breakrX  z-Should not compile partial graph (STORE_ATTR)r   zDynamo has determined when encountering an unsupported STORE_ATTR instruction (i.e. `obj.attr = val`) that it should not compile the partial graph.rS  
store_attrrq  rZ  )rO  rI  r`  r,   r   re  r1   rb  rk  r  r  rg  rh  r   r   rp  s      r   r  z0InstructionTranslatorBase.store_attr_graph_break	  s    ))2QR002Go %)KK$@$@%lT5G5G5I4JK %A %
!
 	++TYYt_,=>		!++&&t'<'<>WX	
r   c                     | j                         }t        t              j                  | |t	        j
                  |j                        gi        y r{   )rf  rN   delattrr  rO   r(  r'  r  s      r   DELETE_ATTRz%InstructionTranslatorBase.DELETE_ATTR)	  s>    hhj .."))$++67	
r   c                 0    t        dt        |              )Nz1create_call_resume_at not overridden by subclass rG  r  )r   r)  rp  s      r   rg  z/InstructionTranslatorBase.create_call_resume_at1	  s    ?T
|L
 	
r   c                 0    t        dt        |              )Nz8should_compile_partial_graph not overridden by subclass r  r   s    r   r`  z6InstructionTranslatorBase.should_compile_partial_graph6	  s    FtDzlS
 	
r   r   c                 Z    | j                  d      \  }}}|j                  | d||gi        y )Nr]  __setitem__r  call_method)r   r   r  r  keys        r   STORE_SUBSCRz&InstructionTranslatorBase.STORE_SUBSCR;	  s+    		!S#mc3Z<r   c                 V    | j                  d      \  }}|j                  | d|gi        y )Nrq  __delitem__r  )r   r   r  r  s       r   DELETE_SUBSCRz'InstructionTranslatorBase.DELETE_SUBSCR@	  s'    99Q<SmcUB7r   c                 n    | j                  |j                        }| j                  t        |             y r{   )r  r'  r  rb   r   r   r   s      r   BUILD_TUPLEz%InstructionTranslatorBase.BUILD_TUPLED	  %    		$++&		-&'r   c                 n    | j                  |j                        }| j                  t        |             y r{   )r  r'  r  ra   r  s      r   BUILD_SLICEz%InstructionTranslatorBase.BUILD_SLICEH	  r  r   c                     | j                  |j                        }| j                  t        |t	                            y Nmutation_type)r  r'  r  r`   rI   r  s      r   
BUILD_LISTz$InstructionTranslatorBase.BUILD_LISTL	  s+    		$++&		,u4D4FGHr   c                     t         j                  rt        dddg        | j                  |j                        }t        |t                     }| j                  |       y )Nzmissing BUILD_SET handlerr   z:Missing BUILD_SET bytecode handler (for testing purposes).rS  r  )r   +inject_BUILD_SET_unimplemented_TESTING_ONLYr,   r  r'  rT   rI   r  )r   r   r   new_sets       r   	BUILD_SETz#InstructionTranslatorBase.BUILD_SETP	  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, ...]`).rS  r  )r  r'  extendrl  NotImplementedErrorr,   r   r   r  r  rI   )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  rb   rv  s     r   BUILD_TUPLE_UNPACKz,InstructionTranslatorBase.BUILD_TUPLE_UNPACKl	  s    t7r   c           	          | j                  |j                  dz        }t        t        |d d d   |dd d               }| j	                  t        |t                            y )Nrq  r   r  )r  r'  r   rt  r  rS   rI   )r   r   r   ds       r   	BUILD_MAPz#InstructionTranslatorBase.BUILD_MAPq	  sS    		$++/*U3Q3Zqt!t-.		#A5E5GHIr   c                 T   | j                  |j                        }|D cg c]#  }t        t              j	                  | |gi       % }}i }|D ]/  }t        |t              sJ |j                  |j                         1 | j                  t        |t                            y c c}w r  )r  r'  rN   r   r  r%  rS   updater   r  rI   )r   r   r   r  r  s        r   BUILD_MAP_UNPACKz*InstructionTranslatorBase.BUILD_MAP_UNPACKv	  s    		$++&MRS&44TA3CSS 	#Aa!2333MM!''"	# 			.0	
 Ts   (B%c           
      d   | j                         }| j                  |j                        }t        |t              sJ |j                         sJ |j                  |       }t        |      t        |      k(  sJ | j                  t        t        t        ||            t                            y r  )rf  r  r'  r%  rb   r~  rl  r   r  rS   r   rt  rI   )r   r   keysrE  s       r   BUILD_CONST_KEY_MAPz-InstructionTranslatorBase.BUILD_CONST_KEY_MAP	  s    xxz4;;'$...&&(((--d34yCK'''		Sv&'.0	
r   c                     | j                  d      \  }}|j                  dkD  sJ | j                  |j                      j	                         }t        |t              sJ |j                  | d||fi        y )Nrq  r   r  )r  r'  r  r  r#  r%  rS   r  )r   r   r   r   r  s        r   MAP_ADDz!InstructionTranslatorBase.MAP_ADD	  sg    yy|1{{Qjj$((#++-#0111maVR8r   c                     | j                         }|j                  dkD  sJ | j                  |j                      }t	        |t
              sJ |j                         sJ |j                  | d|gi       S )Nr   r   rf  r'  r  r  r%  rT   
is_mutabler  r   r   r   r  s       r   SET_ADDz!InstructionTranslatorBase.SET_ADD	  sh    HHJ{{Qjj$((##{+++~~tUQC44r   c                     | j                         }|j                  dkD  s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	  se    HHJ{{Qjj$((##{+++~~hR0r   c                 ^   | j                         }|j                  dkD  sJ | j                  |j                      j	                         }t        |t              sJ |j                         sJ | j                  j                  j                  |       |j                  j                  |       y r   )rf  r'  r  r  r#  r%  r`   r  r   r:  mutationr   r   r  s       r   LIST_APPENDz%InstructionTranslatorBase.LIST_APPEND	  s    HHJ{{Qjj$((#++-#|,,,~~  ))#.		r   c                 ^   |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  rT|dz  r| j                         }|dz  r| j                         }|dz  r| j                         }|dz  r| j                         }| j                  t        || j                  ||||             y )	Nr  co_qualnamer  r\     rB  rq  r   )r  ri  rj  rf  r   rm  rO   r(  r  r  rX   r  )	r   r   flagsfn_namecodedefaultsclosureannotations
kwdefaultss	            r   MAKE_FUNCTIONz'InstructionTranslatorBase.MAKE_FUNCTION	  s   g%hhjGxxzw& 4::}555&--DJJ4J4JKG
g%t|((*t|"hhjt|!XXZ
t|88:		&
	
r   c           	      0   | j                         }t        |t              r'|j                  | t	        |j
                              }nt        |t              rxt        |j                  t              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)idxesz+Failed to unpack object for UNPACK_SEQUENCEzV cannot be unpacked into a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`).rS  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.)rf  r%  rl   r  r  r'  re   r  r  as_proxyr   rM   rk  rl  r,   r   r   r  r   rL  r}   r  )r   r   r  r  proxyr  s         r   UNPACK_SEQUENCEz)InstructionTranslatorBase.UNPACK_SEQUENCE	  sW   hhjc>*))$eDKK6H)IC_-*SWWn2U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.rS  )r'  rf  rk  r   rl  r   r}   r  rb   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   c                      y r{   r   rv  s     r   rs  zInstructionTranslatorBase.NOP
      r   c                 $    | j                          y r{   rf  rv  s     r   POP_TOPz!InstructionTranslatorBase.POP_TOP
      
r   c                     | j                         }| j                         }| j                  |       | j                  |       y r{   rf  r  r   r   ar  s       r   ROT_TWOz!InstructionTranslatorBase.ROT_TWO
  s.    HHJHHJ		!		!r   c                     | j                         }| j                         }| j                         }| j                  |       | j                  |       | j                  |       y r{   r  )r   r   r  r  cs        r   	ROT_THREEz#InstructionTranslatorBase.ROT_THREE
  sD    HHJHHJHHJ		!		!		!r   c                    | j                         }| j                         }| j                         }| j                         }| j                  |       | j                  |       | j                  |       | j                  |       y r{   r  )r   r   r  r  r  r  s         r   ROT_FOURz"InstructionTranslatorBase.ROT_FOUR&
  sZ    HHJHHJHHJHHJ		!		!		!		!r   c                 h    | j                         }| j                  |       | j                  |       y r{   r  )r   r   r  s      r   r  z!InstructionTranslatorBase.DUP_TOP0
  s#    HHJ		!		!r   c                     | j                         }| j                         }| j                  |       | j                  |       | j                  |       | j                  |       y r{   r  r  s       r   DUP_TOP_TWOz%InstructionTranslatorBase.DUP_TOP_TWO5
  sD    HHJHHJ		!		!		!		!r   c                     |dk(  r!t        t              j                  | |gi       S |dk(  r!t        t              j                  | |gi       S |dk(  r!t        t              j                  | |gi       S |S )Nr   rq  r]  )rN   r   r  reprascii)r   rm  flags      r   _convert_valuez(InstructionTranslatorBase._convert_value=
  sp    19"3'55dUGRHHQY"4(66teWbIIQY"5)77ugrJJr   c                    | j                         }t        |t              r?ddlm}m}  |j                   |||      |j                        }| j                  |       y | j                  ||dz        }t        j                  d|j                         z   dz         }| j                  t        t        j                        ||gi        y )Nr   )LazySymNodeFormatStringr]   r  r]  z{:})rf  r%  rk   torch._dynamo.variables.lazyr  r]   r(  r  r  r  rO   r  r  rN   r   format)r   fmt_specr  rm  r  r]   fmt_vars          r   _format_valuez'InstructionTranslatorBase._format_valueF
  s    
e_-
 /'..'x8E IIe##E54<8"))$1L1L1N*NQT*TU?3::6%8H"Mr   c                     |j                   }|dz  dk(  r| j                         }nt        j                  d      }| j	                  ||      S )NrB  r   )r  rf  rO   r(  r  )r   r   r  r  s       r   FORMAT_VALUEz&InstructionTranslatorBase.FORMAT_VALUEZ
  sE    DLT!xxzH'..r2H!!(E22r   c           
      @   g }g }i }| j                  |j                        D ]:  }t        |t              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 conflictrS  zBUILD_STRING type errorzLFormat string part type is not correct - expected constant or format string.r   )r  r  r%  rO   r   r   StringFormatVariableformat_stringr  sym_argsr   r  
sym_kwargsr,   r   r  r  r   r  r(  r   )r   r   format_string_partsr   r>  parts         r   BUILD_STRINGz&InstructionTranslatorBase.BUILD_STRINGc
  sd   )+&(-/IIdhh' 	D$ 01#**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 notrd  r  )r'  r   rd  )r   r   
new_argvalnew_insts       r   IS_OPzInstructionTranslatorBase.IS_OP
  sM    {{a4;;!#333;;!J!J%l:F!r   c                     |j                   dk(  s|j                   dk(  sJ | j                  d      \  }}|j                   }| j                  |j                  | d|gi              |dk(  r| j	                  |       y y )Nr   r   rq  __contains__)r'  r  r  r  	UNARY_NOT)r   r   leftrightr  s        r   CONTAINS_OPz%InstructionTranslatorBase.CONTAINS_OP
  sp    {{a4;;!#333iile[[		%##D.4&"EF7NN4  r   c                     | j                         }|j                  dkD  sJ | j                  |j                      }t	        |t
              sJ |j                         sJ |j                  | d|gi        y )Nr   r  )rf  r'  r  r  r%  r`   r  r  r  s       r   LIST_EXTENDz%InstructionTranslatorBase.LIST_EXTEND
  se    HHJ{{Qjj$((##|,,,~~hR0r   c                     | j                  t        t              j                  | | j	                         gi              y r{   )r  rN   r   r  rf  rv  s     r   LIST_TO_TUPLEz'InstructionTranslatorBase.LIST_TO_TUPLE
  s*    		/%(66tdhhj\2NOr   c                 d   | j                   d   }| j                  |      sJ |j                  t        u r|t	        j
                  t              j                  | t        d      gi       }|j                  | t        d      |       |j                  | t        d      |       || j                   d<   y y )Nr-  zgenerator raised StopIterationr  r2  )
r  r-  r,  r%  r   rN   r  r  rO   r4  )r   r   r  new_vals       r   STOPITERATION_ERRORz-InstructionTranslatorBase.STOPITERATION_ERROR
  s     jjn))#...<<=(//=KK!"BCDG
   '7'FL  '7'DcJ$DJJrN )r   c                    | j                         }|j                  dkD  sJ | j                  |j                      j	                         }t        |t              sJ |j                         sJ |j                  | d|gi        y r  )	rf  r'  r  r  r#  r%  rS   r  r  r  s       r   
DICT_MERGEz$InstructionTranslatorBase.DICT_MERGE
  so    HHJ{{Qjj$((#++-#0111~~hR0r   c                 $    | j                          y r{   r  rv  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 )Nr-  r{  )r  r~  r  rO   r(  r   r  r  r:  s      r   GET_LENz!InstructionTranslatorBase.GET_LEN
  s\    jjn!!#II&--c#2H2H2J.KLMIIcoodIr2>?r   c                 4   | j                   d   }t        |t              sJ t        |j                  t        j
                  j                        r%| j                  t        j                  d             y | j                  t        j                  d             y Nr-  TF)
r  r%  rS   r   collectionsabcMappingr  rO   r(  r:  s      r   MATCH_MAPPINGz'InstructionTranslatorBase.MATCH_MAPPING
  sh    jjn#0111cii!8!89II&--d34II&--e45r   c                 v   | j                   d   }|j                         sJ |j                         }t        |t        j
                  j                        r@t        |t        t        t        f      s%| j                  t        j                  d             y | j                  t        j                  d             y r(  )r  r~  r  r%  r)  r*  Sequencer   bytes	bytearrayr  rO   r(  )r   r   r;  	tos_values       r   MATCH_SEQUENCEz(InstructionTranslatorBase.MATCH_SEQUENCE
  s    jjn%%'''**,	i!9!9::UI.D
 II&--d34II&--e45r   c                 2   | j                   d   }| j                   d   t        t              sJ t        fd|D              rq| j	                  t        |D cg c]  }j                  | |       c}             t        j                  dk  r%| j	                  t        j                  d             y y | j	                  t        j                  d              t        j                  dk  r%| j	                  t        j                  d             y y c c}w )Nr-  rr  c              3   &   K   | ]  }|v  
 y wr{   r   )r   r   tos1s     r   r   z7InstructionTranslatorBase.MATCH_KEYS.<locals>.<genexpr>
  s     &QqDy&s   r  TF)r  r%  rS   rB  r  rb   getitem_constri  rj  rO   r(  )r   r   r;  r   r5  s       @r   
MATCH_KEYSz$InstructionTranslatorBase.MATCH_KEYS
  s    jjnzz"~$ 1222&#&&IIm#$NQT%7%7a%@$NOP')		*11$78 * II&--d34')		*11%89 * %Os   Dc                 D    | j                  | j                  d             y )NrG  )r  r  rv  s     r   r  z.InstructionTranslatorBase.LOAD_ASSERTION_ERROR
  s    		$//0@ABr   c                 D    t        ddddgt        j                         y )Nz'LOAD_BUILD_CLASS bytecode not supportedr   zPDynamo does not support tracing classes that are defined in the compiled region.z5Move the class definition out of the compiled region.rS  r  rv  s     r   LOAD_BUILD_CLASSz*InstructionTranslatorBase.LOAD_BUILD_CLASS
  s)    =jG"..		
r   c                 p    |j                   dk(  r| j                  |       d| _        y | j                  rJ y )Nr   F)r  append_prefix_instr  rv  s     r   RESUMEz InstructionTranslatorBase.RESUME  s5    88q=##D)&+D#.....r   c                 4    t        |j                     | |      S r{   )_binary_op_lookupr  rv  s     r   	BINARY_OPz#InstructionTranslatorBase.BINARY_OP"  s    $TXX.tT::r   c                      y r{   r   rv  s     r   r   z!InstructionTranslatorBase.PRECALL%  r  r   c                     | j                   d   |j                     }t        |t              sJ |D ]  }t        |t              rJ  | j
                  J t        j                  |      | _        y )N	co_constsr  )rI  r  r%  r   r   r  rO   r(  )r   r   r  r   s       r   r  z"InstructionTranslatorBase.KW_NAMES(  sl    $$[1$((;(E*** 	)DdC(((	)}}$$$(//h?r   c                 6    | j                  t                      y r{   )r  rf   rv  s     r   r  z#InstructionTranslatorBase.PUSH_NULL0  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                  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   rq  r   r   )ri  rj  rf  r%  rb   r~  r  r  rm  r  r  rf   r   r   rt  r  )	r   r   call_kwr  contentsr  r   rv  r>  s	            r   _callzInstructionTranslatorBase._call3  sn    ##w...xxzHh68;V;V;XXX224H.2mmt}}**H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. .	E7c                 &    | j                  |       y r{   rH  rv  s     r   r!  zInstructionTranslatorBase.CALL\  s    

4r   c                 V    | j                  | j                  |j                             y r{   )r  r  r  rv  s     r   COPYzInstructionTranslatorBase.COPY`  s    		$**dhhY'(r   c                     | j                   |j                      | j                   d   c| j                   d<   | j                   |j                   <   y Nr-  )r  r  rv  s     r   SWAPzInstructionTranslatorBase.SWAPc  s=    04

DHH90EtzzRT~-

2

DHH9-r   c                      y r{   r   rv  s     r   CACHEzInstructionTranslatorBase.CACHEn  r  r   c                 &    | j                  |       y r{   r  rv  s     r   BEFORE_WITHz%InstructionTranslatorBase.BEFORE_WITHq  r  r   c           	         | j                         }t        |t        t        f      s&t	        dd| d|j                          dg d       t        |t              r+|j                         s| j                  j                  |       t        |t        t        f      sJ t        ||j                        }t        j                  dk\  rk|j                  r>| j                  r/|j                  j                  | j                  d   j                  urd }n-| j                  j                  j                  }n|j                  }| j!                  |       |rt        | t"              r;| j                  j                  t%        ||t'        | j(                        |             n9| j                  j                  t%        ||t'        | j(                                     | j!                  |j+                  |              y )	NzUnsupported context managerz$Attempted SETUP_WITH/BEFORE_WITH 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 generalrS  r  r-  )rf  r%  rP   rQ   r,   python_type_namesupports_graph_breaksr  r   rR   r   ri  rj  r  r  rh  r  r  r   r   r  enter)r   r   r  r  r   s        r   r  z.InstructionTranslatorBase.setup_or_before_witht  s   hhj)+IJ
 5>seDCCDXDXDZC[[mn	  s:;--/0077< )+IJ
 	
 
 (KK

 w&
 !!$$%%,,D4D4DR4H4O4OO..<<CC[[F		$$ 56  ''#D&#djj/3G   ''fc$**o(VW		#))D/"r   c                 V    | j                   sJ | j                  j                  |       y r{   )r  r  r   rv  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"  )ri  rj  r  r%  r  r'  rf   r   r:  track_cell_newr<  rv  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<  rv  s     r   COPY_FREE_VARSz(InstructionTranslatorBase.COPY_FREE_VARS      %r   c                 &    | j                  |       y r{   r]  rv  s     r   RETURN_GENERATORz*InstructionTranslatorBase.RETURN_GENERATOR  r_  r   c                 n    t         j                  dk\  r| j                          y | j                  d       y )Nr\  rq  )ri  rj  rf  r  rv  s     r   END_FORz!InstructionTranslatorBase.END_FOR  s$    w&HHJIIaLr   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 rS  )	r%  r  r  r'  rf   r,   r   r  r  rv  s     r   LOAD_FAST_CHECKz)InstructionTranslatorBase.LOAD_FAST_CHECK  s`    d**..t{{DA<PCMdkk][5)445	 	tr   c                     |j                   | j                  vr| j                  t                      n| j	                  |       t               | j                  |j                   <   y r{   )r'  r  r  rf   r  rv  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                  dz  r| j	                  |       y | j                  |       y )Nrq  r  r   )r  r   r  r  rz  r   rv  s     r   LOAD_SUPER_ATTRz)InstructionTranslatorBase.LOAD_SUPER_ATTR  sB    ;..tA>?88a<T"OOD!r   c                    |j                   dk(  r| j                  |       y |j                   dk(  r| j                  |       y |j                   dk(  r8| j                  t	        | j                         j                  |                    y t        dd|j                    d|j                    dg t        j                         y )	Nr]        z Missing CALL_INTRINSIC_1 handlerzCALL_INTRINSIC_1 operand: z,No handler implemented for CALL_INTRINSIC_1 z instruction.rS  )
r'  r   UNARY_POSITIVEr  rb   rf  rl  r,   r   r  rv  s     r   CALL_INTRINSIC_1z*InstructionTranslatorBase.CALL_INTRINSIC_1  s    ;;!$$T*[[A%[[AIImDHHJ$H$H$NOP:4T[[MBJ4;;-Wde6)556	r   c                 f    | j                         }| j                          | j                  |       y r{   r  r:  s      r   END_SENDz"InstructionTranslatorBase.END_SEND  s!    hhj
		#r   c                 *    | j                  |d       y )NT)rF  rJ  rv  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  )rh  r   rv  s     r   r_  z!InstructionTranslatorBase.TO_BOOL  s'     $$++ 0
 
 	
 
r   c                    |j                   }| j                         }t        |t              sJ | j                         }|dz  r||_        n&|dz  r||_        n|dz  r||_        n|dz  r||_        | j                  |       y )Nr  rB  rq  r   )	r  rf  r%  rX   r  r  r  r  r  )r   r   r  r  attrs        r   SET_FUNCTION_ATTRIBUTEz0InstructionTranslatorBase.SET_FUNCTION_ATTRIBUTE  su    XXZ"8999xxz4<BJT\!BNT\ BMT\BK		"r   c                 v    | j                  | j                  | j                         |j                               y r{   )r  r  rf  r'  rv  s     r   CONVERT_VALUEz'InstructionTranslatorBase.CONVERT_VALUE#  s%    		$%%dhhj$++>?r   c                 N    | j                  t        j                  d      d       y )Nr   r   )r  rO   r(  rv  s     r   FORMAT_SIMPLEz'InstructionTranslatorBase.FORMAT_SIMPLE&  s    +2226:r   c                 D    | j                  | j                         d       y r   )r  rf  rv  s     r   FORMAT_WITH_SPECz*InstructionTranslatorBase.FORMAT_WITH_SPEC)  s    488:q)r   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>/      r   TF)r   count_callsrg  r   s    r   rg  z,InstructionTranslatorBase.is_non_empty_graph,  s%    ;;""$q(&2D#r   c           
          |g }dj                  t        j                  | j                         gt	        t        |            z               S )Nr   )r   r6  rA  rb  r   r}   )r   additional_stack_framess     r   format_frame_summaryz.InstructionTranslatorBase.format_frame_summary3  sL    "*&(#ww!!##%&h7N.O)PP
 	
r   c           	          t        j                  t        | j                  dd      | j                  t        | j                  dd      d      S )Nr.  	<unknown>rS  F)lookup_line)r6  FrameSummaryr  rR  r   r   s    r   rb  z'InstructionTranslatorBase.frame_summary<  s?    %%DKK<KKDKKK8	
 	
r   c                     t        | j                  dd      }t        j                  d      }|j	                  |      d uS )Nr.  r  z.*torch/nn/modules.*)r  rR  recompilematch)r   r   nn_modules_patterns      r   is_co_filename_from_nn_modulesz8InstructionTranslatorBase.is_co_filename_from_nn_modulesD  s:    4;;{CZZ(?@!''1==r   c                     | j                   j                  |t        j                  |            }t	        t        |      j                  t        j                               |S r{   )	r   install_global_by_idweakrefrefr0   r:   r  r/   WEAKREF_ALIVE)r   r  rm  global_names       r   store_global_weakref_by_idz4InstructionTranslatorBase.store_global_weakref_by_idI  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_modeP  s    {{**444r   check_fnc              #   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   r  priors      r   strict_translation_modez1InstructionTranslatorBase.strict_translation_modeT  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 r  )r   r   r   rR  r.  r   r&  r   s    r   r  z#InstructionTranslatorBase.speculate`  s|    ''333''!+++##((KK##KK$$q(d66:;	
 	
r   r&  r  r  r  rI  rR  r  r   distributed_stater  c                 j   t         |           || _        || _        || _        || _        || _        |	| _        g | _        d| _	        d | _
        t        d      | _        g | _        g | _        d| _        d | _        d| _        g | _        || _        || _        t+        | j(                        | _        || _        || _        || _        || _        |
| _        |$t8        j:                  rt=        |
||      | _        nd | _        i | _         i | _!        || _"        d| _#        d | _$        d | _%        d| _&        d | _'        g | _(        || _)        tT        jV                  dk\  r>dd	l,m-}m.}m/}m0} |
jb                  ||z  |z  |z  z  r| je                  tg        d              || _4        d| _5        d gtm        |
jn                        z  | _8        tr        ju                  tv        jx                        | _=        t|        ju                  tv        jx                        | _?        t        j                  |
j                  |       y )
Nr   rs  r-  T)r  r  rI  F)r]  
   r   )CO_ASYNC_GENERATORCO_COROUTINECO_GENERATORCO_ITERABLE_COROUTINE)Cr  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  rI  rR  r   replay_record_enabledr4   r  nn_module_stack	num_callsr  	one_graphr  r  r   r!  r"  r#  ri  rj  resume_executionr  r  r  r  co_flagsr  rN   r  r  r   rC  r  rj  rE  r   rF  ri  rc  rb  rY  	lazycacher.  )r   r   r&  r  r  r  rI  r  r  r  rR  r  r  r   r  r  r  r#  r  r  r  r  r  s                         r   r  z"InstructionTranslatorBase.__init__j  s+   * 	.!2 . 0-J*
#$ #5e#< UW,"&( 0</:4;L;L/M 	 *3*4,8&, 6#?#?!2W<"D "&D BD)+#'  $"w&  |+.CCFXX 		/$/0().&BF#K
 B

 ++GMM: 	* ))'--8 	( 	F..	:r   r{   )F)NN(  r   r   r   r2   r   r   r   rJ   rm   r   r   r   r"   r   rO   r   r   r   r  r4   r   r   r%  ra  r0  r5  r8  r=  r  rJ  rO  rW  r^  rd  ro  ri  rj  rk  propertyrh  rh  r  r  r  r  rf  r  r  r  r  r  r  LOAD_CLOSUREr  r  r  r  cached_propertyr  r  r  r   r  r  r  r  EAGER_IMPORT_NAMEr  r  r  r  JUMP_FORWARDJUMP_ABSOLUTEr  r#  not_ru  r$  rt  JUMP_IF_FALSE_OR_POPJUMP_IF_TRUE_OR_POPr  r  r  r  r  r  r  r   r(  r*  r   r0  r"  r<  r9  r-  rG  rm  rU  rW  r^  r`  rb  rd  rg  r  r  rr  rw  r|  r~  rz  r  r   r  r  r  r  rg  r`  r  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  rs  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r"  DICT_UPDATEr$  r&  r,  r2  r7  r  r:  r  posrm  negUNARY_NEGATIVEr  invertUNARY_INVERTpowBINARY_POWERmulBINARY_MULTIPLYmatmulBINARY_MATRIX_MULTIPLYfloordivBINARY_FLOOR_DIVIDEtruedivBINARY_TRUE_DIVIDEr  BINARY_MODULOBINARY_REMAINDERr   
BINARY_ADDsubBINARY_SUBTRACTgetitemBINARY_SUBSCRlshiftBINARY_LSHIFTrshiftBINARY_RSHIFTand_
BINARY_ANDor_	BINARY_ORxor
BINARY_XORipowINPLACE_POWERimulINPLACE_MULTIPLYimatmulINPLACE_MATRIX_MULTIPLY	ifloordivINPLACE_FLOOR_DIVIDEitruedivINPLACE_TRUE_DIVIDEimodINPLACE_MODULOINPLACE_REMAINDERiaddINPLACE_ADDisubINPLACE_SUBTRACTilshiftINPLACE_LSHIFTirshiftINPLACE_RSHIFTiandINPLACE_ANDixorINPLACE_XORior
INPLACE_ORr=  r@  r   r  r  rH  r!  rL  rO  rt  JUMP_BACKWARD_NO_INTERRUPTPOP_JUMP_FORWARD_IF_TRUEPOP_JUMP_BACKWARD_IF_TRUEPOP_JUMP_FORWARD_IF_FALSEPOP_JUMP_BACKWARD_IF_FALSErQ  rS  r  r<  r[  r^  ra  rc  re  rg  ri  rn  rp  rr  r_  rx  rz  r|  r~  rg  r  rb  r  r  r  
contextlibcontextmanagerr  r  r  CodeTyper   r   CellTyper  r  r  s   @r   r   r   2  s	    #.//3/00#==  !#&$$o&&K'(({####!"233I  -..x(94(?@AA#011u_d?.CCDEE&''.>'
=88 ?#8 S/)*	8,4Un	W+=Z 7"%	+R	 ; ;
"2)=V1 d?3  _  ;c ;d?3 ;!+FV/./ L*J* J J!E( # #*
2:7t $ 6 6>4 LM$X]]E:#HNNE:'t<&x~~t<UU(UU(
 
>R80.
32y'v<:$*ObKPD  Q') ()
  Q'0; (0;d  Q'	- (	-GB )08
*



d 

  Q'= (=8((I
 +7 @ 8 $6 J

 "2
 951$
L:0
N(3
@"!1P%$1 K@6	6:C	
 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6.A6x@P@P7QRM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"	;@"'!R  Q' ()V M!%+HNNEB ,X^^U C ,X]]E B!-hmmU!C(=#~'	*&&;"$  Q'' ('
"@;*

>
 5 5 	*/9JD9P0Q 	* 	*
+ 
8 48.2'i;i; ;'i; sCx.	i;
 S>i; cNi; 38ni; c?23i; sO34i; (Bi; i; i; i; (i; %i;  $$45!i;$ %/0%i;& *+'i;( 
)i; i;r   )	metaclassc                        e Zd Zedd       Zej                  d        Zdee	   de
dedee   ded	   dd
f fdZd ZdefdZ fdZd Zd Zd Zd Zd Zd Zd Z xZS )r  r   c                  "    t         j                  S r{   )tls
current_txr   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 r&  r   r  r  r#  rt   Nc                     t               t        j                  d|j                   d|d    d|d           t        |   t        ||	| ||||||||      ||||||i i 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 t=        | j?                         |      D ]g  \  }}tA        |      }t1        |d      }	 t-        j.                  |jB                  |      }|jK                  |||      }||_        || j                  |<   i tM        |      | _'        |r.tF        j,                  jQ                  | 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/  )local_scoper  rR  torch_function_mode_stackr#  r   )r   r&  r  r  r  r  rI  r  r  r  rR  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   INFOrS  r  r  r2   _throw_if_in_functorchr   r   r  r  r  r  r  r   r8  r%   get_contextr  r   	frozensetr]   r(  r<   r:  r0  rZ  r  r  rt  r5  r;   cell_contents
ValueErrorr   DeletedVariabletrack_cell_existingrm   r  realize_all)r   r&  rR  r  r  r  r  r  rI  compiler_fnr  r  export_constraintsframe_stater   r  r  r#  r8  r	  r   rm  local_dynamismvarr:  contents_sourcer  cell_varr  cell_sourcer  s                                 r   r  zInstructionTranslator.__init__  s   ( 	LL((8,}:U9VVWXdeuXvWwx	
 	"$&*C &!%*.+%/= 	 	
B 	##% T[[001 _	43F3F3H _	#,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td'O 5H4N4N5L  ,::<H ++HlC+::<H&*#-5$$T*G#6N "$--/7; 6
d-d3"-dT"R?#6#=#=**O$L (;;| '+#-5$$T*6  2L)2D.  (1'D'D'P'P(((${_	 _	 _	Z " ?#,#<#<#>L?[_	 _	 _	 _	sQ   M.BL5<D9L56 LA+L5ML2	/L51L2	2L55L>	: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eagerr  zhIf you are reaching here, it means dynamo failed for one of the following reasons:
- Calling torch.func.zP(compiled_fn) function from eager mode is not supported. Ensure that torch.func.zp is also wrapped within a torch.compile function. For more information, see PyTorch issue #128711.
- torch.func.z2(fn) requires the function to be inlined by dynamoz%Unsupported functorch tracing attemptr   rS  )r<  _dynamolookup_backendr  getattr_staticr   r  _C
_functorchpeek_interpreter_stackTransformTypeVmapGradJvpr  r   lowerr,   )r   r  r  ciforbidden_keysr   ro  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   r  c                     t        |t              r| j                  |j                     S t        |t              r| j
                  |j                     S t        r{   )r%  r<   r  r  r9   r  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                 "    t         |           y r{   )r  r  )r   r  s    r   r  zInstructionTranslator.run  s    r   c                 0   t         j                  dk\  rJ| j                  j                  }|r2| j                  r%|j
                  | j                  d   j
                  uryt        d | j                  D              xr | j                   xr | j                   S )Nr  r-  Fc              3   <   K   | ]  }|j                           y wr{   )r   r   r  s     r   r   zEInstructionTranslator.should_compile_partial_graph.<locals>.<genexpr>  s     :A:rA  )	ri  rj  r  r  r  r   rB  r  r  )r   r   s     r   r`  z2InstructionTranslator.should_compile_partial_graph  s    w&,,::E$$D<L<LR<P<W<W(W:)9)9:: 9NN"9888	
r   c                 h	    d  _         |j                  dk(  rt        d      gS |j                  dk(  rt        d|j                        gS t	         j
                  |      t         fd j                  j                         D              }t        |d   j                        t        fd|D              }t        fd|D              }t        j                  dk  rt        |      dk(  sJ d	       t         j                        t        |d   j                        z
  }|t        |      z   }t!               }t#        |d   j$                  |d   j&                        D ]p  \  \  }	}
}t)        t*         j                  |         }|j-                  |       |j/                  t1        ||	z
  d
z                |j3                  t        d             r |d   j4                  D ]O  \  }}
t)        t*         j                  |         }|j-                  |       |j3                  t        d|             Q t7        d|j8                   d      }t;        j<                   j>                   j@                  |j8                  t        d  jB                  D              |||t        d  jB                  D              t        |d   j$                        t        |d   j4                        t        |d   j                              } tE        jF                   j>                        jI                  dd              }|+tK        jL                  |      tE        jF                  |      d<   |jN                  r3 jP                  jS                  ||       |jU                  ||d|       d }n_ jP                  jS                  |tW        jX                  | jZ                  |             |j/                  |j]                  |d|             |} j^                  * j^                  ja                  | jZ                  d   |       |j/                  |D cg c]  }|jc                  |       c}       |j/                  te        |d             |j3                  t        d             |jg                         S c c}w )Nr'  r(  r  c              3   N   K   | ]  }|v r|j                         vr|  y wr{   )r8  )r   r   r<  r   s     r   r   z>InstructionTranslator.create_call_resume_at.<locals>.<genexpr>  s0      
Ezat'='='?? 
s   "%r   c              3   ,   K   | ]  }|vs|  y wr{   r   r   r   argnames_null_sets     r   r   z>InstructionTranslator.create_call_resume_at.<locals>.<genexpr>  s     OqA=N4NO   	c              3   ,   K   | ]  }|v s|  y wr{   r   r5  s     r   r   z>InstructionTranslator.create_call_resume_at.<locals>.<genexpr>  s     PA>O9OaPr7  r  z&variables should not be NULL in < 3.12r   r  r  __resume_at_T)	with_uuidc              3   H   K   | ]  }|j                   j                    y wr{   )r   r)  r1  s     r   r   z>InstructionTranslator.create_call_resume_at.<locals>.<genexpr>  s     <a!((//<s    "c              3   <   K   | ]  }|j                           y wr{   )r   r1  s     r   r   z>InstructionTranslator.create_call_resume_at.<locals>.<genexpr>  s     :A!++-:rA  orig_graphmodulec                       y r{   r   r   r   r   r   z=InstructionTranslator.create_call_resume_at.<locals>.<lambda>  r  r   r   F)4r   r   r   r'  r   r&  r   r  r  r   locals_null_keysri  rj  r   r  stack_null_idxesr&   rt  stack_ctx_argsstack_ctx_idxes_origr   rP   r  r  r    append_outputlocals_ctx_argsr$   r)  r5   lookuprR  r   r  r%   r  r  r  r  r4  r   install_global_unsafemake_function_with_closurer  FunctionTyper  load_function_namer#  add_resume_functioncreate_loadr   r  )r   r   rp  all_argnamesru  argnames_null	stack_lenr  r  r  r   i_origr  r   new_codeorig_graphmodule_maybepackage_namer   r6  r<  s   `                 @@r   rg  z+InstructionTranslator.create_call_resume_at  s!   #' ;;.(&~677[[N*&~dkkJKK!$"3"3T: 
))..0
 
   9! < M MNOLOOPPPg%}%*T,TT* 

Oc*CA*F*W*W&XX	CM)t_ "%a(77%a(==
 	<NFQF
 .

60BCC  $[Q):;</	:;	< 13CC 	LGD!.0D0DT0JKC  $/TJK		L <}5F#9#@#@KKKKKK<4+;+;<<:)9)9::+A.==>+A.>>?+A.??@$
 "
!9!9$++!F!J!J"
 " "-EL[[&FL$$X./AB KK--dH=))$$	JL KK--e((4>>4H R224yIJL<<#LL,,$..4l 	X>"..+>?
-eU;<
+N;<""$$ ?s   R/c                     | j                   j                         D ]G  }t        |t              st	        |j                         t        j                  j                        sG y y)NTF)	r  rE  r%  rp   rY  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 )Nr-  r  )r   r  r%  rW   r_   rl  rI   )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                  sf| j                  j                         dk(  rI| j                  s=| j                         s-| j                  s!| j                  st        j                  d      d | _         t               t         j"                  d| j$                  j&                   d|j(                   d       t*        j-                  d|j(                         | j                  j/                  | t1        d| j3                         gd	
            }t5        |      dk(  sJ |d   j6                  rJ |j(                  dk(  rt9        d      nt9        d|j:                        }| j                  j=                  |g       t>        )Nr	  r   z#because no content in function callztorchdynamo done tracing r   rQ  z%s triggered compilereturn_valueF)r  rX  r   r'  r(  r  ) rX  r   r  rC   r
  r   allow_empty_graphsr   r  r  rV  r  r  r   rd  r   r   r  rR  rS  r   r   rH  re  r1   rb  r   r@  r   r'  rk  r  )r   r   rp  return_insts       r   _returnzInstructionTranslator._return-  s   //1''333+++''0043C3CC	

 ))'')Q.22==?KKNN-- EFF#' LL'(;(;'<Bt{{m1M	
 			($++6$(KK$@$@%!3!3!5 6E %A %
! ,-222,Q/@@@@ {{n, ~.#N4;;G 	
 	++[M:r   c                 &    | j                  |       y r{   r]  rv  s     r   r'  z"InstructionTranslator.RETURN_VALUEW      Tr   c                 &    | j                  |       y r{   r_  rv  s     r   r(  z"InstructionTranslator.RETURN_CONSTZ  r`  r   )r   r  )r   r   r   staticmethodr  r  r  r  r   r"   r   r  r   r   r  r  r=   r-  r  r`  rg  rV  rX  r]  r'  r(  r  r  s   @r   r  r    s      # #\;'\ (\  %!\" $$45#\$ *+%\& 
'\|> 
_%B	(Tr   r  r  INPLACEr]  BINARY_c                       e Zd ZU dZee   ed<   eed<   ed        Z	e
d        Ze
dedee   fd       Zd	 Zded
ej                   deeef   deeef   dededdf fdZed        Zd Zd Zd Zd Zd Zd Z fdZ fdZ xZ S )r/  z Trace and inline a called methodsymbolic_resultr!  c                     t        j                  t        dt        d   i      5  | j                  ||||      }|j	                         cd d d        S # 1 sw Y   y xY w)NunimplementedrN  )r
   r   r@   build_inline_tracerinline_call_)r   r!  funcr   r>  tracers         r   rN  z)InliningInstructionTranslator.inline_calln  sQ    ZZ?H]4K"LM 	),,VT4HF&&(	) 	) 	)s   $AAc                 z   | 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        t        | dd       d      r/| j                  j                   |fv 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.rS  _torchdynamo_disableF_torchdynamo_disable_msgz2Skip inlining `torch.compiler.disable()`d functionzSkip inlining function z= since it was wrapped with `torch.compiler.disable` (reason: rQ  z(Remove the `torch.compiler.disable` callT)is_inlined_callr   )!produce_trampoline_autograd_applyr  _originz"allowlist in dynamo known functionr   zAvoid calling the function `r  r  z:Apply `@torch._dynamo.dont_skip_tracing` to the function `zw` to force tracing into the function. More graph breaks may occur as a result of attempting to trace into the function.z Please file an issue to PyTorch.z.Attempted to inline function marked as skippedz
qualname: z, name: z, filename: `z`, skip reason: z?Dynamo developers have intentionally marked that the function `z` should not be traced.)has_selfr,   r   r%  rZ   r  r!  get_functionr   check_verboseskippedtorch._dynamo.variables.miscrq  r   r  r  rr  
SkipResultr   get_filenameget_namer   )rk  ro  r  rq  fn_qualnamerW  s         r   check_inlineablez.InliningInstructionTranslator.check_inlineablet  s   ==?6D	k d01g6L6L!77
 ((!!#%?C LD--/05d6G6G6I5J K::=aA ? **4F>>V wtT40)<1U B #--?  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   rk  r   c                 L    t        |t        t        t        t        f      sJ |j                         d } j                  j                  }t        j                  s"|r |j                  j                  d       x}r|}|ht        |t              rt        dd| dg        t        j                  |      }|j                   du sJ t        j                  s|r||j                  <   	 |j#                   ||      }t5        j6                  |j9                               D ]8  }
t        |
t:              rt        dd| d|
 dg t<        j>                         : j@                  dv rL|rt        |d   tB        jD                        s-t        ddj@                   d| dj@                   dg        d}tF        jH                  jJ                  jL                  jO                  d      r&dtQ        jR                        jQ                          }tT        jV                  dk\  r? jX                   jZ                   fd}t\        j_                  dta        |             tb        j_                  d||jd                         |rt        |d   tf              r j                  ji                  |d   jj                        }t        |tF        jl                  jn                        r?tq        jr                  |      tu        jv                  |jx                  jz                        d<   t}              r&t         | j                   j                  |      }|S t        |t              rJ t         | j                   j                  |      }|S # t$        $ r}t'        dj)                  t+        |      d|j-                          d|j/                          d	|j                         j0                   |D 	cg c]  }	|	j3                          nc c}	w c}	|
            d }~ww xY w)NzEAttempted to inline function marked as skipped (SkipFunctionVariable)z+Attempted to inline a SkipFunctionVariable zdAttempted to inline a function that was previously determined to be marked as intentionally skipped.rS  Fz;{reason}.
  func = {func}, args = {args}, kwargs = {kwargs}'z' r   )r   rk  r   r>  z:Encountered unconverted argument when attempting to inlinezfunc: z, arg: zWAn argument to an inlined function was not successfully converted to a VariableTracker.)r  __setattr__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   )rW  	positionsr   rB   r[  rS  )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, %sr=  )Br%  rZ   rX   rV   rW   rM  r   r  r   dont_skip_tracingpreviously_inlined_functionsr  rY   r,   r/  r|  rv  	bind_args	TypeErrorr'   r  r   rz  ry  r/  python_typerC  rD  rE  rJ   r   rL  rS  r   rs   r<  rB  	_internal	log_stateis_artifact_enabledr  Bytecoderi  rj  r  rR  trace_call_logrH  rF   r   r   ri   r  r  r  r  r  r  r%   r  forward__code__r#   &InliningGeneratorInstructionTranslatorr  r  )r!  rk  r   r>  r  tracing_ctxprevious_result
sub_localsr  r  r   r  r  modulerl  r  r  r  s   `              @@@r   ri  z1InliningInstructionTranslator.build_inline_tracer  s    $*.,	
 	
 
  $}}mm33
 ''K"-"J"J"N"Nd#   )>$ 45 cI$P~ 3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   z2H'IJ		%tVV]]C JtAw(89]]00a1C1CDF&%(("6"67
 KK' (()@)@A&
 ;''44F&  "$(DEEE2''44F c  		#NUUq6T]]_-R0A0A0C/DAdmmoFdFdEef7;<#//+<<!	 V  		s%   ,N 	P#AP4PPP#c                 f   | j                   }| j                  }t        j                         }|j                  r| j                  |j                        }	 |5  | j                          d d d        | j                  J | j                  |j                  u r%|j                   j#                  | j                          |xj$                  | j$                  z  c_        t        j                  d|       | j&                  j(                  j*                  j-                  |       t.        j0                  st3        | t4              rl| j6                  r`t9        |      rIt3        | t4              r9| j:                  r-t3        | t4              sJ t        j<                  t>        |        y | j                  S t9        |      rMt3        | t4              sJ | j                  jA                         J tC        | jD                  tG                     S | j                  S # 1 sw Y   xY w# t        j                  $ r#}d| d| }t        j                  |        d }~wt        j                  $ r.}d| d| }t        j                  |       t        |      |d }~wt        $ r t        j                  d|        w xY w)Nz!Observed exception DURING INLING z : zSKIPPED INLINING r   zFAILED INLINING %szDONE INLINING %sr  )$r!  rR  r  nullcontextr  r  r  r   rl  r   rH  rd  r-   r  rf  r  r  r  r  r   r  traced_coder   r   rL  r%  r  is_generator_from_ctx_managerr#   generator_exhaustedr3  r%  r  r_   generated_itemsrI   )r   r!  r  
strict_ctxr  ro  s         r   rj  z*InliningInstructionTranslator.inline_call_4  s8   {{$002
""55f6M6MNJ	 
 ##///>>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,,]DA+++D!!$(NOOO++>>@HHH+(("2"4 
 +++a $$ 	5dV3qcBCIIcN}} 	*%dV2aS1CIIcNc") 	II*D1	s<   H H(H HH J0/IJ0#)J$J0r  r  r  r  funcvarr   Nc                 
   |j                         }|d   }t        |t              s|j                  }|j                  j
                  }	d }
|	r*|	j                  j                  |      r|	j                  |   }
|
't        |      }
t        |
       |	r|
|	j                  |<   t        | -  |j                  i ||||||
t               D ci c]  }|t        ||       c}||j                  |j                  dz   |j                   |j"                  |j$                  |j&                         || _        || _        |j,                  | _        d | _        |j0                  j3                         | _        |j4                  | _        y c c}w )N__builtins__r   )r   r  r  r  r  r  r  r&  rI  rR  r  r  r   r  r  r#  )get_globalsr%  r   __dict__r   r  previously_cleaned_instructionsr  r   r   r  r  r!   r  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  s               r   r  z&InliningInstructionTranslator.__init__n  sm    '')	~.
*d+#,,J mm33::>>tD*JJ4P/5L-DP;;DA==!+-*G%7DG!!WT1--G==,,q0"22,,$66NN! 	 	
$ ))#%55::<)) Hs   F 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!  rb  r   s    r   r  z)InliningInstructionTranslator.run_ctx_mgr  s     ++DKK,E,E,GHHr   c                      yr   r   r   s    r   r`  z:InliningInstructionTranslator.should_compile_partial_graph  s    r   c                 "    t        dddg        y )NzGraph break in inlined functionr   z2Graph breaks in an inlined call are not supported.rS  )r,   r  s      r   rg  z3InliningInstructionTranslator.create_call_resume_at  s    5L		
r   c                 F    | j                         | _        d | _        t        r{   )rf  rf  r   r  rv  s     r   r'  z*InliningInstructionTranslator.RETURN_VALUE  s    #xxz#' r   c                 H    | j                  |      | _        d | _        t        r{   )r  rf  r   r  rv  s     r   r(  z*InliningInstructionTranslator.RETURN_CONST  s#    #//5#' r   c                    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        ||      }|||fS )Nr   namedtuple_r  ___unnamed_scope)r  r  r  r<  r#  r  r  r   rL   r7   r   r  r9   r8   )	r   r   r  r  r  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99r   c                    |j                   }|| j                  vr| j                  |      S | j                  j                  | j                  u rt
        |   |       y | j                  |      \  }}}| j                  j                  j                  ||      r6| j                  | j                  j                  j                  ||             y | j                  |   }| j                  t        j                  | ||             y r{   )r'  r  r  r   r  r  r  r  r:  has_pending_mutation_of_attrr  	load_attrrJ   r  )r   r   r   r   r  r  rm  r  s          r   r  z*InliningInstructionTranslator._load_global  s    {{t~~%$$T**;;##t~~5 G &,0,M,Md,S)A{M{{''DD[RVW		$++22<<[$OPt,		///e]KLr   c                 l   | j                   j                  | j                  u rt        |   |       y | j                         }t        |t              rt        d|j                  dg        |j                  }| j                  |      \  }}}| j                   j                  j                  |||       y )Nz3Storing Tensor hook handle in globals (inline call)r  rS  )r   r  r  r  r  rf  r%  ro   r,   r'  r  r:  r  )r   r   rm  r   _fglobals_valuer  r   r  s          r   r  z*InliningInstructionTranslator.STORE_GLOBAL  s    ;;##t~~5 G &HHJE%!89 Q KK 8	 ;;D.2.O.OPT.U+O[!KK$$//T5Ir   )!r   r   r   r   r   rJ   r   r   r   rN  rb  r|  r   ri  rj  r  r  r   r   rm   rU   r  r  r  r  r`  rg  r'  r(  r  r  r  r  r  s   @r   r/  r/  h  s   *o..%%) )
 ; ;z  ?# B8,t7*)7* nn7* c?23	7*
 sO347* (B7* *7* 
7*r % %I


:>M"J Jr   r/  c                   d     e Zd ZU ee   ed<   d
 fdZdefdZd Z	 fdZ
 fdZd Zd	 Z xZS )r  r  c                 N    t        |   |i | g | _        d| _        d| _        y r   )r  r  r  r  r  )r   r   r>  r  s      r   r  z/InliningGeneratorInstructionTranslator.__init__
  s-    $)&)!#( -2*r   r   c                 d   | j                         }| j                  j                  |       t        | j                        t        kD  rt        j                  dt               | j                  t        j                  d              t        j                  s| j                  r|| _        t        y )NzqToo many yield values in generator. Maybe you are inlining an infinite generator. If not, please report a bug at )rf  r  r   r   r\   r   InfiniteGeneratorErrorPT2_ISSUE_TRACKER_URLr  rO   r(  r   rL  r  rf  r
  )r   r   tops      r   YIELD_VALUEz2InliningGeneratorInstructionTranslator.YIELD_VALUE  s    hhj##C(t##$'99,,22G1HJ  			"))$/05511#&D 	 2r   c                     | j                   d   }t        |t              sC| j                          t	        t
              j                  | |gi       }| j                  |       y y rN  )r  r%  r_   rf  rN   rf  r  r  )r   r   r;  ress       r   GET_YIELD_FROM_ITERz:InliningGeneratorInstructionTranslator.GET_YIELD_FROM_ITER!  sN    jjn#34HHJ!$'55dSE2FCIIcN 5r   c                 0    d| _         t        | 	  |      S r  )r  r  r'  r   r   r  s     r   r'  z3InliningGeneratorInstructionTranslator.RETURN_VALUE(      #' w#D))r   c                 0    d| _         t        | 	  |      S r  )r  r  r(  r  s     r   r(  z3InliningGeneratorInstructionTranslator.RETURN_CONST,  r  r   c                    t        | j                        dk\  sJ | j                         }| j                  d   }t        |t              r|j
                  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)	Nrq  r-  Unreachable sub-generator coder   @Should only be encountered while implementing generator support.rS  r   r   )r   r  rf  r%  rO   rm  r,   r$  r   r   r  r  r%  r   r&  r  r(  r   r   r  r;  exs        r   
YIELD_FROMz1InliningGeneratorInstructionTranslator.YIELD_FROM0  s*   4::!###hhjjjn3 01cii6G 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*3A-E%%E*c                    t        | j                        dk\  sJ | j                         }| j                  d   }t        |t        t
        f      s>t        |t              r~t        |j                  t        j                  j                        rPt        |t              r0|j                  $	 |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)Nrq  r-  r  r  r   r  rS  zSEND with bad typez
TOS type: z(Attempted to SEND with unsupported type r  )r   r  rf  r%  r_   rW   rs   rm  r)  r*  IteratorrO   r$  r  r%  r   r&  ri  rj  r(  r  r,   rH   r  s        r   SENDz+InliningGeneratorInstructionTranslator.SENDV  s>   4::!###hhjjjnc02NOPs56399koo&>&>?#/0SYY5F#++D1C IIcN !< b	 ,$WS\N3Fws|nTUV	5 &s'D'DE 
$ '''1
II.55bhh?@IIdOO
$s   +D F A"FFr   )r   r   r   r   rJ   r   r  r"   r  r  r'  r(  r  r  r  r  s   @r   r  r    s9    /**3 "**$#L*r   r  )r   r   )r   FN)r   r)  collections.abcr  r  r   r  r  r   r  rC  rY  r   r#  r  ri  	threadingr6  r  typingr  r   r   r   r   r   r   r	   unittest.mockr
   r<  torch._loggingtorch._dynamo.excr   torch._guardsr   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%   codegenr&   r'   r(   r)   r*   r+   r,   r-   funcname_cacher.   guardsr/   r0   output_graphr1   r2   replay_recordr3   r4   r  r5   r6   r  r7   r8   r9   r:   r;   r<   r=   r>   r?   utilsr@   rA   rB   rC   rD   rE   rF   rG   variables.baserH   rI   rJ   variables.builderrK   rL   rM   variables.builtinrN   variables.constantrO   variables.ctx_managerrP   rQ   rR   variables.dictsrS   rT   variables.functionsrU   rV   rW   rX   rY   rZ   r[   variables.iterr\   variables.lazyr]   variables.listsr^   r_   r`   ra   rb   variables.miscrc   rd   re   rf   rg   rh   variables.nn_moduleri   variables.tensorrj   rk   rl   variables.torch_functionrm   rn   variables.user_definedro   rp   rq   rr   rs   r#  rt   	getLoggerr   r   rB  getArtifactLoggerrD  r  rc  rj  localr  r   r  ry   r   r   r   containsr|   r  r   r  cacher  r   	dataclassr   r   r   r   r   r   r  r   r   r   rG  r   r  r  r
  r  r  r   r+  rG  rO  r  r  r  r  r  r   r  rj  _nb_opsr  r?  r/  r  )r   r   r   r   s   0000r   <module>r     s   0      
        	 
      P P P    < 1 / < /  
 
 
 '    ) / 9 9 A   ;	 	 	 G F R R . 0 
 <   / /   2 W W  'g!..228^L11(LI>>33HnM ^^55h@PQ ioo4R4L4R4R4T',0AqAq'''' T#s(^  "("3"34BBX]]+99
 D ! H 
 D  ) )!1!1 ) ) L L L( @ @ @F 
 
 
 2 2 23 3. 4 4 ) )" $ $ . . .B	~ 		I 	9 f- ?
%?oovhn-? ?D I
Xw6??F8T>: w$ wtDJ J2 Z Z Zza";(a";HEE5 EP w 
 FA	 	!#v-F12JWVABZL3I	
[J$= [J|z-J zgz'Xms   S03"S6