
    Bjp                   	   U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlZddlmZ ddlmZ ddlmZm Z m!Z!m"Z" ddlm#Z#m$Z$m%Z% ddl&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. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7 ddl*m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@mAZA ddlBmCZD ddlEmFZF ddlGmHZH ddlImJZJmKZKmLZLmMZM ddlNmOZOmPZP ddlQmRZRmSZSmTZTmUZUmVZV ddlWmXZX ddlYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_m`Z`maZa ddlbmcZcmdZdmeZemfZf ddlgmgZg ddlhmiZimjZjmkZkmlZlmmZmmnZnmoZo dd lTmpZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z| dd!l}m~Z~ dd"lmZmZmZ dd#lmZ dd$lmZmZ dd%lmZmZmZ dd&lmZ dd'lmZ dd(lmZmZmZmZmZ dd)lVmZ dd*lmZmZmZmZ dd+lmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ dd,lmZ d-ed.<   	 ddlZn# e$ r dZY nw xY wej        r.dd/lmZ dd0lmZ dd1lWmZ dd2lmZ dd3lmZ dd4lmZmZmZ dd5lmZ  ej        eȦ          Ze)j                            ed6          Ze)j                            ed7          Z ej                    Z e%d8          Z e'd9          Z G d: d;          Zdd@Z G dA dB          Z eԦ            Z eԦ            ZdadCedD<    ej        eD          	 dddL            ZdddRZddUZeoj        ddY            Z	 	 ddd_Zda ej                    Zd`eda<   ddcZdddZe G de df                      ZddjZ G dk dl          Z	 	 	 	 	 dddwZddxlmZ ddylmZ  e            Zdzed{<   d|ZddZddZddZddZedZddddddd            Ze G d d                      Ze G d d                      Z edm           G d d                      ZddZe G d d                      Ze G d d                      ZddZddZ	 dddZ	 dddZdddZe G d d                      ZddZdddZddZdZdddddddZ	 	 ddddddd˄Z  G d̄ dͦ          Z	 	 ddd΄ZddЄZddфZ G d҄ dej                  Z G dӄ dԦ          ZddՄZdS )a  
This module implements TorchDynamo's core frame conversion functionality, transforming Python
frames into FX graphs. It handles:

- Frame analysis and bytecode transformation
- Guard creation and management for dynamic behaviors
- Cache management for recompilation
- Error handling and fallback mechanisms

Key classes:
- ConvertFrame: Main entry point for frame conversion with error handling
- ConvertFrameAssert: Implements core frame to graph conversion logic
- Tracker: Tracks input/output code objects during conversion
- CatchErrorsWrapper: Provides error handling and suppression logic

The conversion process preserves program semantics while enabling optimizations
through torch.compile() and related systems.

NOTE: _torchdynamo_orig_backend is used for convert frame wrappers to identify the inner wrapped function.
By going down the _torchdynamo_orig_backend chain, one can recover the original unwrapped backend,
which is checked for during the Dynamo cache lookup.
    )annotationsN)	dataclass)Path)CellTypeCodeTypeFunctionType
ModuleType)AnyNoReturnTypeVar)	ParamSpec)ReferenceType)GlobalStateGuard)CallbackTrigger)get_compile_pg)TensorifyState)compile_contextCompileContext	CompileIdtracing)
structured)compile_time_strobelight_meta#maybe_upload_prof_stats_to_manifoldsignpost_event)_use_lazy_graph_module)ConstraintViolationErrorGuardOnDataDependentSymNode)_forward_from_src)_WaitCounter)DistributedDataParallel)_disable_current_modes any_torch_dispatch_mode_on_stack/is_in_any_mode_without_ignore_compile_internalsis_traceable_wrapper_subclass)CapturedTracebackformat_traceback_short   )config
decoratorsexcgraph_break_hintstrace_rules)_is_registered_backend)remove_dead_coderemove_pointless_jumps) check_inst_exn_tab_entries_validInstructionis_generator propagate_inst_exn_table_entriestransform_code_object)CacheSizeRelevantForFramecompute_cache_sizeexceeds_recompile_limitis_recompilation)code_context)always_optimize_code_objects
Constraint
dynamo_tlsinnermost_backendinnermost_fn	skip_codeTorchPatcher)augment_exc_messageBackendCompilerFailedFailOnRecompileLimitHitformat_error_msgInternalTorchDynamoErrorPackageErrorResumePrologueTracingErrorShortenTracebackTorchRuntimeErrorUncapturedHigherOrderOpErrorunimplementedUnsupported	UserError)reset_user_object_tracking)CheckFunctionManager'get_and_maybe_log_recompilation_reasonsGuardedCode)Hooks)DynamoTracerOutputOutputGraphCommon)_log_size_mismatch_recompilelog_frame_dynamic_whitelistput_code_state)ExecutionRecord)TORCH_DYNAMO_RESUME_IN_PREFIX)DistributedStateExceptionStackInstructionTranslator
LocalStateSpeculationLog)is_numpy)ConvertFrameReturnFrameActionFrameExecStrategywrap_guarded_code)_get_error_on_graph_breakchromium_event_timedCleanupManagerCompileTimeInstructionCountercountersdynamo_timedformat_bytecodegen_record_file_name#get_hook_for_recompile_user_contextget_metrics_contextincrement_frameis_namedtupleistype
LazyStringmaybe_disable_inference_mode*maybe_disable_inference_mode_for_fake_proporig_code_mapreset_graph_break_dup_checkersetup_compile_debug	to_int_ustroubleshooting_urlwrite_record_to_file)#torch_function_mode_stack_state_mgrzModuleType | Nonenp)Callable)WeakIdKeyDictionary)
CompilerFn)CompilePackage)WrapBackendDebug)BytecodeHook
CacheEntryDynamoFrameType)FrameStateSizeEntrybytecodegraph_breaks_T_Pc                      e Zd ZdS )TODO_UNKNOWNN)__name__
__module____qualname__     ^/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/torch/_dynamo/convert_frame.pyr   r      s        Dr   r   	fake_mode3torch._subclasses.fake_tensor.FakeTensorMode | NonereturnNonec                    | dS | j         j        j        }|j                                         |j                                         dS )z:Clear WeakIdRef entries from a FakeTensorMode's describer.N)fake_tensor_convertermeta_converter	describerlookup_tensorclearlookup_storage)r   r   s     r   _clear_fake_mode_weakrefsr      sM     />HI!!###""$$$$$r   c                  .    e Zd ZddZddZdd	Zdd
ZdS )Trackerr   r   c                :    g | _         t                      | _        d S N)seensetseen_idsselfs    r   __init__zTracker.__init__   s    35	"%%%r   
strong_objr   c                     t          |           j        vrOt          j        | fd          } j                            |            j                                       d S d S )Nc                8    j                                       S r   )r   remove)_idxr   s    r   <lambda>zTracker.add.<locals>.<lambda>   s    DM4H4H4M4M r   )idr   weakrefrefr   appendadd)r   r   objr   s   `  @r   r   zTracker.add   st    nndm##+j*M*M*M*M*MNNCIS!!!Mc""""" $#r   itemboolc                .    t          |          | j        v S r   )r   r   )r   r   s     r   __contains__zTracker.__contains__   s    $xx4=((r   c                j    | j                                          | j                                         d S r   )r   r   r   r   s    r   r   zTracker.clear   s.    	r   Nr   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r      sd        ( ( ( (# # # #) ) ) )     r   r   zGlobalStateGuard | Noneinitial_global_statesrcstrglobalsdict[str, Any]	co_fieldsdict[str, str] | Noner   c                P    t          | ||          }t          |j                   |S r   )original_forward_from_srcr?   __code__)r   r   r   results       r   fx_forward_from_src_skip_resultr      s*     'sGY??FfoMr   coder   skipint	list[str]c                   t          j        t                    t          j        d|z                                             }t          j        |          }t          t          j	        fd|                    | j
        | j        t          j        | j                  dgz   t          j                            dfd           fd|D             d| j
         d	| j         d
| j         gz   }|S )N   r   c                    | d         k    S )Nfilenamer   )fconvert_frame_interns    r   r   z"log_dynamo_start.<locals>.<lambda>  s    a
m';; r   )linenamer   dynamo_startc                     d iS )Nstackr   )r   s   r   r   z"log_dynamo_start.<locals>.<lambda>  s    %  r   c                Z    g | ]'}|j         k    d |j         d|j         d|j          (S )Line: , Name: , Filename: )r   linenor   ).0framer   s     r   
<listcomp>z$log_dynamo_start.<locals>.<listcomp>  sP       >111 	POOuzOOu~OO111r   r   r   r   )r   intern_string__file__r%   extractsummaryfrom_tracebacklist	itertools	takewhileco_firstlinenoco_nameco_filenametorch_loggingtrace_structured)r   r   captured_tbframes_internedstack_stringsr   r   s        @@r   log_dynamo_startr     s3   %3H==#+T:::BBDDK /<<O;;;;	
 	
  'L"01ABB	
 	
	E 
N##            
 	[$ZZdlZZHXZZ		M r   fnCallable[_P, _T]c                V     t          j                   d fd            } |_        |S )	a@  
    Context manager to:
        1) Save/restore torch.is_grad_enabled() state
        2) Save/restore torch random state
        3) Monkey patch torch.fx.graph_module._forward_from_src

    NOTE: Python random state is preserved in eval_frame_cpp.cpp instead,
    so that it wraps more of the compilation pipeline.
    args_P.argskwargs	_P.kwargsr   r   c                    t                      }t          j                    }t          j                                        5  t                      5  t                      5  t          j                    }t          j                    }t          j	                    }t          j        
                                }t          j                    }t          j                                        }	d }
t          j                                        rTt          j                                        5  t          j                                        }
d d d            n# 1 swxY w Y   t          j                            dd          }t          j        j        j        }t*          t          j        j        _        t-                      }t/          j                    }|                    t          j        j                                                   t9                       	  | i ||                                 |                                 t          j                            |           t          j        j         !                    |           t          j"        ||           t          j        #                    |	           t          j$        |           t          j        
                                }||k    rt          j        %                                 |
Ut          j                                        5  t          j        #                    |
           d d d            n# 1 swxY w Y   t          j        &                    dd|           |t          j        j        _        |'                                s J d|(                                 d            cd d d            cd d d            cd d d            S # |                                 |                                 t          j                            |           t          j        j         !                    |           t          j"        ||           t          j        #                    |	           t          j$        |           t          j        
                                }||k    rt          j        %                                 |
Ut          j                                        5  t          j        #                    |
           d d d            n# 1 swxY w Y   t          j        &                    dd|           |t          j        j        _        |'                                s J d|(                                 d            w xY w# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )Ncudamatmul)	warn_onlyzGlobal z7state changed while dynamo tracing, please report a bug))r   r   is_grad_enabled_C_PreserveDispatchKeyGuardrr   rs   is_inference_mode_enabled$are_deterministic_algorithms_enabled-is_deterministic_algorithms_warn_only_enabled$_is_default_mobile_cpu_allocator_setget_default_dtyperandomget_rng_stater   is_availableDisableTorchFunction_get_fp32_precision_getterfxgraph_moduler   r   rv   
contextlib	ExitStackenter_context_symbolic_trace_maybe_revert_all_patchesrN   close_set_grad_enabledautograd	grad_mode_enter_inference_modeuse_deterministic_algorithmsset_rng_stateset_default_dtype#_unset_default_mobile_cpu_allocator_set_fp32_precision_settercheckreason)r   r   guardsprior_grad_modeprior_inference_modeprior_deterministicprior_warn_onlyprior_mobile_allocator_stateprior_dtypetorch_rng_statecuda_rng_statecuda_matmul_fp32_precprior_fwd_from_srccleanup
exit_stackcurr_mobile_allocator_stater   s                   r   _fnz"preserve_global_state.<locals>._fn1  s   !##/11 H..006	 6	(**6	 6	 7886	 6	
 $)#B#D#D "'"L"N"N#QSSO==?? )  133K#l88::O!Nz&&(( @X2244 @ @%*Z%=%=%?%?N@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$)H$G$G% %! "'!6!H6UEH!3)++G#-//J$$(BBDD   '(((r4*6**  """**?;;;(>>?STTT2'?    **?;;;'444HAACC , 03NNNH@@BBB!-6688 A A
00@@@A A A A A A A A A A A A A A A33H&;   ;M%7||~~  ffmmoofff ~i6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	>   """**?;;;(>>?STTT2'?    **?;;;'444HAACC , 03NNNH@@BBB!-6688 A A
00@@@A A A A A A A A A A A A A A A33H&;   ;M%7||~~  ffmmoofff ~~~~~i6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	 6	s   W#WCV4&E	V4EV4EB9V4O7DV40 MV4M  V4#M $A.V4WW#7DV1	 T:.V1	:T>>V1	T>A/V1	1V44V88W;V8<W?W#W	W#W	W##W'*W'r   r   r   r   r   r   )	functoolswraps_torchdynamo_orig_backend)r   r)  s   ` r   preserve_global_stater.  &  sH     _R> > > > > >@ %'C!Jr   r   r   r   c                "   | j         t          v rdS | j         j        D ]}|| j        v rv| j        |         }t	          |t
                    r&|j                            d          s	|t          u r dS t          r't          j        r|t          u st          |          r dS i d
fd| j                                        D ]} |          r dS t                              d| j         j        | j         j        | j         j                   d	S )z+Check if the frame has torch.* related bitsTztorch.r   objectr   r   c           	     "    t                     }|v r|         S d|<   t           t          j        t          j        j        f          s4t           t                    r,t           t          j        j                  rd|<   |         S t          j
        rHt          rAt           t          j                  st           t          j                  rd|<   |         S t           t          t          f          r&t!          fd D                       |<   |         S t           t"                    rGt                                                     }t!          fd|D                       |<   |         S t           t&          t(          t*          t          d          t,          f          rd|<   |         S t/                     r<t1           d          r,t!           fd j        D                       |<   |         S dS )z)Recursively check if the obj has a tensorFTc              3  .   K   | ]} |          V  d S r   r   r   v
has_tensors     r   	<genexpr>z:has_tensor_in_frame.<locals>.has_tensor.<locals>.<genexpr>  s+      ">">Q::a==">">">">">">r   c              3  .   K   | ]} |          V  d S r   r   r3  s     r   r6  z:has_tensor_in_frame.<locals>.has_tensor.<locals>.<genexpr>  s+      "A"AQ::a=="A"A"A"A"A"Ar   N_fieldsc              3  J   K   | ]} t          |                    V  d S r   )getattr)r   r4  r5  r   s     r   r6  z:has_tensor_in_frame.<locals>.has_tensor.<locals>.<genexpr>  s5      "T"T1::gc1oo#>#>"T"T"T"T"T"Tr   )r   
isinstancer   TensornnModulerp   type
issubclassr(   trace_numpyr{   ndarraygenericr   tupleanydictvaluesr   r   floatr   ro   hasattrr8  )r   obj_idrG  r5  r   s   `  r   r5  z'has_tensor_in_frame.<locals>.has_tensor  s   CXF## cEL%(/:;; !	3!	",S%(/"B"B!	  $HVF##		 RZ((	 -7sBJ,G,G	
  $HVF##C$'' 	"">">">">#">">">>>HVF##C 	 #**,,''F""A"A"A"A&"A"A"AAAHVF##C#sE4::t<== 	$HVF##3 	GC$;$; 	""T"T"T"T"T"T"T"TTTHVF## 5r   z0skipping because no torch.* %s             %s %sF)r   r0  r   r   )f_coder:   co_names	f_globalsr;  r	   r   
startswithr   r{   r(   rA  r_   f_localsrG  logdebugr   r   r   )r   r   r   valuer5  r   s       @@r   has_tensor_in_framerS  v  sP    |333t <( 	 	eo%%/'*C#z** ''1158E\\tt f( cRii8C==itt "H( ( ( ( ( ( (V &&((  :e 	44	 II	 #   5r   Fe	ExceptionDynamoFrameType | Noneexportc                    d }t          | d          r,t          | |          }t          || j                   || _        t          | |           d S )Nexec_recordrW  )rI  rk   ry   rY  record_filenamerA   )rT  r   r   rW  r[  s        r   exception_handlerr\    s]     Oq-   ,.q$77_am<<<+&))))))r   z)typing.Counter[int | FrameStateSizeEntry]FRAME_COMPILE_COUNTERfuncc                <    t           j        rt          |           S | S r   )r(   cprofilecprofile_wrapper)r^  s    r   maybe_cprofilerb    s     &%%%Kr   c                H     t          j                   d fd            }|S )	Nr   r   r   r   r   r   c                 N   t          j                    }|s
J d            t          t          j                            t          j                    j         dt          |          
                    dd           d                    }t          j                    }	 t          j                    } |j        g| R i |}t          j                    |z
  }n4# t          $ r' t                               d           d} | i |}Y nw xY wt                               dj        ||           t'          j        |          }	 |                    |           n+# t,          $ r t                               d|           Y nw xY wt                               d	|           |                    d
          }		 t1          j        ddddddt          |          gt0          j                  5 }
t1          j        dddt          |	          g|
j                   t                               d|	           d d d            n# 1 swxY w Y   n# t:          $ r t                               d           |                    t&          j        j                   !                    d           |                    t&          j        j"                  !                    d           Y nw xY wtG          t          |                    xr#tH          j%        &                    dfd           |S )NzTrace id is Noner   /z.profilezfailed to enable cProfiler   z7### Cprofile for %s trace id [%s] took %.3f seconds ###zCannot write to %szRaw profile at %sz.svg	gprof2dotz-fpstatsz"--node-label=total-time-percentagez!--node-label=self-time-percentagez--node-label=total-time)stdoutdotz-Tsvgz-o)stdinz Generated SVG from profile at %szxFailed to generate SVG from profile -- dumping stats instead.Try installing gprof2dot and dot for a better visualization   linkc                     d dS )Ncprofile_manifold_url)r   urlr   )manifold_links   r   r   z;cprofile_wrapper.<locals>.profile_wrapper.<locals>.<lambda>"  s    !8OO r   )'r   current_trace_idr   ospathjointempfile
gettempdirr   r   replacecProfileProfiletimeruncall
ValueErrorrP  	exceptionwarningrg  Stats
dump_statsOSErrorwith_suffix
subprocessPopenPIPE
check_callrh  FileNotFoundError
sort_statsSortKeyTIMEprint_stats
CUMULATIVEr   r   r   r   )r   r   trace_idprofile_pathprofstart_tsretvalprofile_latencypssvg_pathgprof2dot_processrp  r^  s              @r   profile_wrapperz)cprofile_wrapper.<locals>.profile_wrapper  s   !244+++++xGLL#%%=LL3x==#8#8c#B#BLLL 
 
 !!	+y{{H
 "T\$888888F"ikkH4OO 	+ 	+ 	+MM5666OT4*6**FFF	+ 	EM		
 	
 	
 \$	>OOL)))) 	> 	> 	>MM.=====	>'666++F33	E!87-%% "   J #%GT3x==9+2    >III!J J J J J J J J J J J J J J J" ! 	E 	E 	EKKN   MM&.-..::2>>>MM&.344@@DDDDD	E @
 
 
= 	 N++OOOO   s\    :C .DDE %FF84I ,AI 4I  II II BK! K!r*  )r+  r,  )r^  r  s   ` r   ra  ra    sE    _TD D D D D DL r   c                      e Zd ZU dZded<   dS )ConvertFrameBoxNzbool | Noneerror_on_graph_break)r   r   r   r  __annotations__r   r   r   r  r  )  s$         (,,,,,,,r   r  frame_state$dict[str, int | FrameStateSizeEntry]r   c                   d| vrt           | d<   t           dz  a | d         }t          |t                    sJ t          |         }t          |xx         dz  cc<   d }t	          j                    x}r|j        }t          |||          S )N_idr'   )compiled_autograd_idframe_idframe_compile_id)FRAME_COUNTERr;  r   r]  r   current_compile_idr  r   )r  r  r  r  priors        r   get_compile_idr  .  s     K*E5!Hh$$$$$,X6(###q(###1333u :$91)   r   c                  H    e Zd Z	 	 	 	 	 d"d#dZed$d            Zddd%d!ZdS )&ConvertFrameAssertTFNcompiler_fnr~   	one_graphr   rW  export_constraints
Any | NonepackageCompilePackage | Nonerecompile_limit
int | Noner   r   c                    t                       || _        || _        || _        || _        || _        || _        t                      | _        d S r   )	ru   r-  
_one_graph_export_export_constraints_package_recompile_limitr  _box)r   r  r  rW  r  r  r  s          r   r   zConvertFrameAssert.__init__F  sN     	&''')4&##5  /#%%			r   *Callable[[CompilerFn], ConvertFrameAssert]c                      fdS )Nc                T    t          | j        j        j        j                  S Nr  )convert_frame_assertr  r  r  r  backendr   s    r   r   z8ConvertFrameAssert._clone_with_backend.<locals>.<lambda>[  s0    3OL$ 1 
  
  
 r   r   r   s   `r   _clone_with_backendz&ConvertFrameAssert._clone_with_backendY  s    
 
 
 
 	
r   r   r   r   r   cache_entryCacheEntry | NonehooksrR   r  r  r   r   r`   c               |   t                       |j        }t          ||          }t                              |           |t
          v rt                      S t          j        	                    d          r6t          j        	                    d          |j
        k    rt                      S |j
        dk    r(|j                            d          rt                      S |j
        dk    rt                      S |j
        dk    rT|j                            t          j                            t           j        j                            rt                      S |j
        dk    r|j        dk    rt                      S |j
        dk    r-|j        dk    r"t'          |j                  st                      S t+          |          r t-          d	d
ddgt.          j                   t3          |          st                      S t5          j                    }|r%d|j        j        v r|j        }|rd|j        j        v |r#|j        t:          j        u rt          d          S t>          }	tA                      atC          |          }
|
j"        }tG          dd|j
        |tI          |
          |j        |j%        |j&        |j'        d           |j
                            tP                    s8|j
         d|j         d|j%         }tR          j*        +                    |           	 tY          t[          |
                    }| j.        t_          j0        | j.                  ntc          j2                    }|5  |5  tg          |j        |j4        |j5        |j        |j6        | j7        | j8        | j9        | j:        ||||||
|dz   | j;        | j<                  }d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   |	an# |	aw xY wt^          j=        r'| j;         ddl>m?} |@                    | j;                   |S )NTORCHDYNAMO_DEBUG_FUNCTIONz	<genexpr>)ztransformers/file_utils.pyztransformers/utils/generic.pyzdiffusers/utils/outputs.py__setattr__r   z<module><string>z<lambda>zAttempt to trace generator z<Generators cannot be compiled directly with `torch.compile`.zbCall a generator from inside of a non-generator Python function and compile that function instead.gb_typecontextexplanationhintsztorch/_dynamo/convert_frame.pyF)apply_to_codedynamoz_convert_frame_assert._compile)r   r  
compile_idr   r   
cache_sizeaccumulated_cache_size :r  r'   )r  r  r   r  convert_frame_box)DynamoCache)Arn   rK  r6   input_codesr   output_codesr`   rr  environgetr   r   endswithrN  rs  dirnamer   optimr   r   
f_builtinsr2   rK   r+   FUNDAMENTALrS  sys	_getframef_backr)   "_nonrecursive_disable_wrapper_coder   r   r  r  r   r   r   +num_cache_entries_with_same_id_matched_objsnum_cache_entriesrY   r<   traced_frame_infosr   r   r   r  r(   patchr
  nullcontext_compilerM  rO  closurer-  r  r  r  r  r  caching_precompiler  r  record_package)r   r   r  r  r  r   r   r  
prev_frameprev_initial_global_stater  r  infocompile_ctxrecompile_ctxr   r  s                    r   __call__zConvertFrameAssert.__call__c  s     	|'{;;
<%'''JNN788	(
;<<LL%'''<;&&4+;+D+D,
 ,
& &'''<=(( &'''<:%%$*:*E*EGOOEK011+
 +
%
 &'''
 <:%%$*:j*H*H%''' LJ&& J..)** /
 &''' 
	4Z5 '2		 	 	 	 #5)) 	(%''' ]__
 	+0J4E4QQQ#*J 	+0J4E4QQQ 	;!Z%RRR%E:::: %9!/11#K00
&,<$!*oo#/"&"5(T*4*F 	
 	
 	
 |&&'DEE 	7lMMT%5MM8KMMD)00666 	=).*D*DEEK
 (4 T-BCCCC+-- 
   m  !LON$M2OL, +) M&*i%                               . $=  #< <<<<$ 	6)B,,,,,, &&t}555sV    AP 2O45AOO4O!	!O4$O!	%O4(P 4O88P ;O8<P PTFNNN)r  r~   r  r   rW  r   r  r  r  r  r  r  r   r   )r   r  r   r   r  r  r  rR   r  r  r   r   r   r`   r   r   r   r   propertyr  r  r   r   r   r  r  E  s         )-)-&*& & & & && 
 
 
 X
  Z Z Z Z Z Z Z Zr   r  Tr  r~   r  r  r  r  r  r  r  c                *    t          | |||||          S )zHFully convert a frame into an FX graph, raising an exception if we fail.)r  )r  r  rW  r  r  r  s         r   r  r     s(       r   )OrderedDict)RemovableHandlezdict[int, BytecodeHook]_bytecode_hooksbytecode_hook_side_effectstypes.CodeTypetuple[str, ...] | Nonec                    t          j        |           sdS t          j        |                               t                    }|dS |S )zReturn Dynamo's replayed Python side-effect sources for compiled code.

    Returns ``None`` when ``code`` was not produced by Dynamo or no metadata was
    attached to it.
    N)r9   has_contextget_contextr  '_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY)r   side_effectss     r   get_compiled_code_side_effectsr    sR     #D)) t+D1155/ L tr   c                :    t          t          |                     S )zNReturn whether Dynamo recorded replayed Python side effects for compiled code.)r   r  r   s    r   compiled_code_has_side_effectsr  /  s    .t44555r   src_codedst_codec                    t          j        |           sd S t          j        |           }t          |v r)|t                   t          j        |          t          <   d S d S r   )r9   r  r  r   )r  r  src_contexts      r   _copy_code_contextr
  4  sb    #H-- *844K.+==?@ 	 **+RSSS >=r   hookr   r  c                L    t          t                    }| t          |j        <   |S )a*  Register hooks for bytecode generated by Dynamo. The hook can do some
    logging, as well as return a new code object to be used. Hooks can query
    `get_compiled_code_side_effects(new_code)` for replayed Python side effect
    sources. Please refer to `BytecodeHook` for the hook signature.
    )r  r  r   )r  handles     r   register_bytecode_hookr  >  s"     _--F!%OFIMr   rW  r  r  distributed_stater  dict[str, object]localsbuiltinsr  tuple[CellType]tf_mode_stack'list[torch.overrides.TorchFunctionMode]speculation_logr^   instructionslist[Instruction]code_options+dict[str, int | FrameStateSizeEntry] | Noner  DistributedState | NonerS   c               .   ddl mm                                  t	                      }t          |	| ||||||
||||||||          d	fd}	  |             t                    }|j        }|J |j        sJ |j        |	d d <   |
	                    |j
                   t          |	           t          |	           t          t          |	                    |	d d <   n)# t          $ r}t          d          |_         d }~ww xY w|S )
Nr   )bisecttranslation_validation_enabled)r  r  exn_vt_stackr  r  r   r   c                    	 j                                          t          j         j                  5                                  5                                   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   nw# t          j        $ r                                   t          j	        t          j
        t          j        f$ r  t          $ r!              r  j         j                    w xY wj                                          i _        d S # j                                          i _        w xY wr   )outputmark_bytecode_tracing_startr   tracing_contextset_current_txrunr*   UnspecializeRestartAnalysisr   SpeculationRestartAnalysisTensorifyScalarRestartAnalysis	SkipFramerU  	shape_envcall_cleanup_hooksrO  )r  r  tracerr  s   r   
run_tracerztrace_frame.<locals>.run_tracerx  s   	!M55777677  9N9N9P9P  

                             . 	 	 	!!###*.M
 	 	 	
  	 	 	--// 0v}.///	
 M,,... FOOO M,,... FO    se   2B B
A+B+A/	/B2A/	3B6B BB 	B
B D' A4DD' '"E	T)errorr   )torch.fx.experimental.validatorr  r  restartr[   r\   rS   output_graphoutput_instructionsupdater  r3   r0   r/   r.   rU  _torch_dynamo_tracer_output)r   r   r  r  r  r  r  r  r  r  r  rW  r  r  r  r  r   r.  tracer_outputr"  rT  r  r-  r  s           `            @@@r   trace_framer7  L  s   ( WVVVVVVV!##L"'!+#  F(! ! ! ! ! ! ! ! !,
*622+!!!)))) 4QQQF/000(666(66601A,1O1OPPQQQ   (:6(N(N(N% s   BC, ,
D6DDc                  R    e Zd ZU dZded<   ded<   ded<   	 	 	 	 dddZ	 	 dddZdS )DynamoOutputao  
    Represents the core data returned from a single dynamo run, including:
      - Guards, wrapped inside tracer_output.output_graph.guards
      - Generated bytecode
      - Other information needed for compilation.
    This data structure should capture all the "interesting" information dynamo
    produces on the frontend side before it enters user backend.
    rS   r6  r  r   zfloat | Nonelast_attempt_start_timeNFr   r  Hooks | Nonesaver   r  r  strict_errorr   rO   c           	     r    | j         j        }|J t          ||||r|j        nd |r|j        nd ||          S N)save_guardsr=  )r6  r2  rO   guard_fail_fnguard_filter_fn)r   r   r  r<  r  r=  r2  s          r   build_guardszDynamoOutput.build_guards  sa     )6'''##(2Ed%*4E!!%
 
 
 	
r   argdefstuple[Any, ...] | None
kwdefaultsdict[str, Any] | NoneGraphCaptureOutputc           
        | j         j        }|J t          t          |                                |j        |j        |j        |j                  |j        |j	        | j
        | j         j        ||| j         j                  S r   )r6  r2  rH  rT   dump_guards_stateimport_sourcesr+  export_metadatatracked_fakes_id_to_sourcetraced_coder   r  rM  )r   rD  rF  r2  s       r   graph_capture_outputz!DynamoOutput.graph_capture_output  s    
 )6'''!..00+&,7  '$M&(
 
 	
r   NFNFr   r  r  r;  r<  r   r  r  r=  r   r   rO   NN)rD  rE  rF  rG  r   rH  )r   r   r   __doc__r  rC  rO  r   r   r   r9  r9    s           &%%%))))
 #)-"
 
 
 
 
, +/,0
 
 
 
 
 
 
r   r9  c                  F    e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   dS )BackendInputa   
    Represents core data structure that dynamo will pass to a backend, including:
      - Graph module
      - Example inputs
      - The FakeTensorMode used for compiling graph.
    This data structure should capture all the information dynamo produces
    on for the user backend.
    r   
backend_idtorch.fx.GraphModuler	  r
   example_inputsz,torch._subclasses.fake_tensor.FakeTensorModer   r}   tensor_to_contextN)r   r   r   rS  r  r   r   r   rU  rU    sW           OOO&&&&;;;;******r   rU  )frozenc                      e Zd ZU ded<   ded<   ded<   ded<   ded	<   d
Zded<    ej        e          Zded<   d
dddZ	ddZ
d
S )GraphRuntimeEnvr  r   dict[str, str]rK  r   used_globalsrE  r  rD  NrG  rF  )default_factoryset[str]external_refsextra_globalsrV  r   compiled_fnCallable[..., Any]rc  r   c                  d | j                                         D             }i || j        |pi ||i}|                     |           t	          j        | j        || j        | j                  }| j	        r| j	        |_
        |S )Nc                >    i | ]\  }}|t          j        |          S r   )	importlibimport_module)r   aliasmodule_names      r   
<dictcomp>z4GraphRuntimeEnv.forward_callable.<locals>.<dictcomp>  s9     
 
 
"{ 9*;77
 
 
r   )r  rD  )rK  itemsr^  _check_external_refstypesr   r   r  rD  rF  __kwdefaults__)r   rV  rd  rc  rK  rM  r   s          r   forward_callablez GraphRuntimeEnv.forward_callable  s    
 
&*&9&?&?&A&A
 
 



 "
 	
 
	 	!!),,,MLL	
 
 
 ? 	0 $B	r   rM  r   c                z    g }| j         D ]}||vr|                    |           |rt          d| d          d S )Nz&Missing required external references: zM. Please load AOT compiled function with `f_globals=<enclosing global scope>`)ra  r   RuntimeError)r   rM  missing_refsr   s       r   rn  z$GraphRuntimeEnv._check_external_refs  sw    % 	) 	)C)####C((( 	^ ^ ^ ^  	 	r   )rV  r   rd  re  rc  rG  r   re  )rM  r   r   r   )r   r   r   r  rF  dataclassesfieldr   ra  rq  rn  r   r   r   r\  r\    s         """"    ########(,J,,,,/k/DDDMDDDD 04     >     r   r\  builtins_dictc                    ddl }i }|                                 D ]0\  }}	 |                    |           |||<   !# t          $ r Y -w xY w|S )zCFilter a builtins dict to only picklable entries for serialization.r   N)picklerm  dumpsrU  )rw  ry  r   kr4  s        r   _safe_builtins_dictr|  $  ss    MMMF##%%  1	LLOOOF1II 	 	 	D	Ms   <
A	A	c                      e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   d
ed<   ded<   ded<   	 	 	 	 d#d$dZd%d Zed&d"            ZdS )'rH  z)
    Minimal version of DynamoOutput
    rT   r2  r]  rK  zlist[CodeType]rN  r   r   rE  r  rD  rG  rF  r   rM  NFr   r  r  r;  r<  r   r  r  r=  r   rO   c           	     \    t          || j        ||r|j        nd |r|j        nd ||          S r?  )rO   r2  rA  rB  )r   r   r  r<  r  r=  s         r   rC  zGraphCaptureOutput.build_guardsA  sM     $#(2Ed%*4E!!%
 
 
 	
r   r\  c           	        ddl m} i }| j        j        j                                        D ])} ||          }||| j        v r| j        |         ||<   *|                     | j                  }dd l	}|D ]e}||vr_|
                    d          r'|| j        v rt          | j        |                   ||<   Bt          ||          rt          ||          ||<   ft          | j        | j        || j        | j        | j        |          S )Nr   )get_global_source_name__builtins_dict__)r   rK  r^  r  rD  rF  ra  )torch._dynamo.sourcer  r2  rL  graph_input_idx_to_local_sourcerG  rM  _get_external_refsr   r  rN  r|  rI  r:  r\  rK  r  rD  rF  )r   r  r^  sourceglobal_namera  	_builtinsr   s           r   get_runtime_envz"GraphCaptureOutput.get_runtime_envS  sX   ?????? .NUUWW	H 	H0088K"dn,,,0N;,G[) //>> 	%$$$  	@ 	@C,&&>>"566 @3$.;P;P(;DN3<O(P(PL%%Y,, @(/	3(?(?L%].%LL'
 
 
 	
r   r`  c                   dd l }t                      } |j        |           D ][}|j        dk    r"|j        r|                    |j                   /|j        dk    r!|j        r|                    |j                   \|S )Nr   LOAD_GLOBAL	LOAD_NAME)disr   get_instructionsopnameargvalr   )r   r  ra  instructions       r   r  z%GraphCaptureOutput._get_external_refsx  s    


"%%% 03/99 	: 	:K!]22% :!%%k&8999#{22% :!%%k&8999r   rP  rQ  )r   r\  )r   r  r   r`  )	r   r   r   rS  r  rC  r  staticmethodr  r   r   r   rH  rH  2  s           $###""""########%%%%
 #)-"
 
 
 
 
$#
 #
 #
 #
J    \  r   rH  c                  8    e Zd ZU dZded<   ded<   dddddZdS )CaptureOutputa  
    CaptureOutput should represent all the information produced from torch
    compiler for a single graph capture. This intends to be consumed by
    various compiler frontends so that we can share as much compiler internals
    as possible and avoid great divergence between different stacks.
    This data structure should eventually contain all the information compiler
    produces as more refactors happens to converge different compiler
    frontends.
    rH  rO  zBackendInput | Nonebackend_inputN)rd  rc  rd  Callable[..., Any] | Nonerc  rG  r   re  c                   | j                                         }| j        J | j        j        }|p| j        j        }|                    |||          S )Nrb  )rO  r  r  rV  r	  rq  )r   rd  rc  runtime_envrV  s        r   rq  zCaptureOutput.forward_callable  sh     /??AA!---'2
!DT%7%D++' , 
 
 	
r   )rd  r  rc  rG  r   re  )r   r   r   rS  r  rq  r   r   r   r  r    s`           -,,,&&&&
 26/3	
 
 
 
 
 
 
 
r   r  modr
   "tuple[FunctionType, object | None]c                B   ddl }t          | t          j        j                  r| j        }t          |d          r|j        }| j        }t          |d          r|j        }t          | j
                  dk    r5t          | j                  dk    rt          t          j        j        j        j                  dk    rt          t          j        j        j        j                  dk    rt          | j                  dk    rt          | j                  dk    rt          t          j        j        j        j                  dk    rht          t          j        j        j        j                  dk    r<|t          j        j        j        k    r"|t          j        j        j        k    r| j        } n.t          | t          j        j                  r| j        } n| j        } t          | d          r| j        | j        fS  |j        |           r| dfS t3          d|            )z
    Utility function to get the function to trace, and optionally a bound self
    object, from a callable (nn.Module, function, or method).
    r   N__self__zUnsupported model code type )inspectr;  r   r=  r>  forwardrI  __func__r  len_forward_pre_hooks_forward_hooksmodulesmodule_global_forward_pre_hooks_global_forward_hooks_backward_pre_hooks_backward_hooks_global_backward_pre_hooks_global_backward_hooksr  GraphModule
_call_implr  
isfunctionrs  )r  r  resolved_forwardresolved_calls       r   get_traced_fnr    s   
 NNN#ux''  ;#Z00 	9/8=*-- 	3)2M
 &''1,,C&''1,,EH$+EFF!KKEH$+ABBaGGC+,,11C'((A--EH$+FGG1LLEH$+BCCqHH EHO$;;;!999 +CCUX122 	.CC,CsJ A|S\))		C	 	  ADy?#??@@@r   inspect.Signaturec                .    t          j        | d          S )NF)follow_wrapped)r  	signature)r   s    r   _get_signaturer    s    R6666r   r   tuple[Any, ...]r   rG  	FrameInfoc           	        ddl }t          |           \  }}||f|z   }|i }t          |          } |j        |i |}|                                 |j        }|j        pd}	|j        j        }
|
s|	rOt          |	          t          |
          k    sJ |
                    d t          |
|	          D                        t          |j        |j        ||j        |j        pd|j        |j                  S )zL
    Create a frame to trace, given a model, args, and optional kwargs.
    r   Nr   c                $    i | ]\  }}||j         S r   )cell_contents)r   r   cells      r   rl  z_get_frame.<locals>.<dictcomp>  s!    OOO*$T4%OOOr   )r  rD  rF  )r  r  r  bindapply_defaults	arguments__closure__r   co_freevarsr  r4  zipr  __globals____dict____defaults__rp  )r  r   r   r  r   self_optr  bound_argumentsrO  r  freevarss              r   
_get_framer    s+    OOO %%LB{T!~r""I$ind5f55O""$$$(Hn"G{&H 
7 
7||s8}},,,,OOHg8N8NOOO	
 	
 	
 

$"$   r   constraints _is_export_deprecated_do_not_user  list[Constraint] | Noner  c                   t          | ||          }t          t          t          i                               5  t	          |||          cddd           S # 1 swxY w Y   dS )a  
    This API captures a full graph for a model, given example inputs to trace with.

    Specifically, it takes a callable (nn.Module, method, or function), args, and
    optional kwargs, and returns Dynamo-captured graph along with other important
    compile-time information. This serves as the common graph-capture mechanism
    for different torch compiler AOT frontends (e.g. AOT precompile, export).

    Note that this API doesn't apply context managers like metrics context,
    and the expectation is that the caller will apply them depending
    on the use case.

    The CaptureOutput is separated into two parts:
    1. Frontend specific information, which includes:
        - guards
        - generated bytecode
        - other information tracked by OutputGraphCommon.
    2. Backend specific information (indexed by unique backend id) such as:
        - fx graph
        - example inputs
    r  N)r  r   r   r  _fullgraph_capture_frame)r  r   r   r  r  r   s         r   fullgraph_capturer  
  s    : sD&))E	r(:(:;;	<	< 
 
'#-M
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   AA!Ac                  V    e Zd ZU ded<   ded<   ded<   ded<   ded<   d	ed
<   ded<   dS )r  r  r   r  r   r  r  r  r  rE  rD  rG  rF  N)r   r   r   r  r   r   r   r  r  1  sf         ####%%%%%%r   c                  ddl m d dfd}	 t          | j        | j        | j        | j        | j        |||d	t                      

  
        }n# t          t          t          f$ rm}t          |           t          j        r |}|j        (|j                            d            |j        }|j        (|                    d           |j        d }~ww xY wt#          |                    | j        | j                            S )Nr   )TracingContextgmrW  rX  list[torch.Tensor]r   c                                                     }|j        }|j        }|J t          | j        d         t
                    sJ t          | j        d         | |||          | S )NrV  )r  r   rY  r;  metar   rU  )r  rX  r$  r   rY  r  r  s        r   fullgraph_compilerz4_fullgraph_capture_frame.<locals>.fullgraph_compilerF  sy     ),,..#-	+=$$$"',/55555$GL!2~yBS
 
 	r   T)r  rW  r  r  restart_reasons)r  rW  rX  r  r   rW  )torch._guardsr  compile_framer   r   r  r  r  r   rL   rJ   rM   rA   r(   verbose	__cause__with_tracebackr  rO  rD  rF  )	r   r  r  r  dynamo_outputrT  cur_exnr  r  s	          @@r   r  r  <  sL    -,,,,,)-M      6%JMLNM*3*EE
 
 
 5yA 
6 
6 
6A> 	!"+,,T222'G + t$$!+5
6 **5=%:JKK  s   >A C)A(CCcallbackConvertFrameProtocolc                X     t           dd           }||S d
dd fd	}| _        |S )N_dynamo_fail_callbackr   r
   r   r   r   c                      t          d          )NzDynamo: expected not to compile nested code - this happens because a Dynamo callback was triggered and succeeded in compiling when running fullgraph=True compiled code.)rs  )r   r   s     r   compile_frame_errorz.get_fail_callback.<locals>.compile_frame_errorz  s    9
 
 	
r   r`   c                     t          j        t          dz             5   | i |cd d d            S # 1 swxY w Y   d S )Nz.compile_frame)mockr  r   )r   r   r  r  s     r   fail_callbackz(get_fail_callback.<locals>.fail_callback  s    Z#335HII 	- 	-8T,V,,	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s   488)r   r
   r   r
   r   r   )r   r
   r   r
   r   r`   )r:  r  )r  r  r  s   ` @r   get_fail_callbackr  u  si    H&=tDDM 
 
 
 
- - - - - - -
 &3H"r   r  r`  c                  	
 t                      d 	
fd}d}t          j                    D ]}|t          j                    _        	 t          d	| d
          5  t           |          \  }}|J t          |||          cddd           c S # 1 swxY w Y   t# t          j
        $ r}t          |t          j                  st          j                     t                              dt#          t$          |j                             t)          |dd          }|r|                                 |                    |j        pt1          t3          |                               t5          j                    }|dk    rt7          dddg            Y d}~rd}~wt          j        $ r}t          |t          j                  st          j                     t)          |dd          }|r|                                 t                              d| j         j         j                     d}~ww xY wdS )a  
    A helper function taking a frame and backend, then return the generated bytecode
    and guards as a common data structure.
    This is a shared interface for multiple compiler frontends (e.g. torch.compile,
    torch.export) that needs to capture a graph out of python code.
    r  r  r  r  r   rS   c                    t          t          j                  }t          || |	
          }|J |S )Nr  )r   rz   r   r7  )r  r  r  r6  r  r  r   r  r  rW  r  r  r   r  r  r  r  s       r   	transformz compile_frame.<locals>.transform  sx     BF/5B
 B
 $1#/!
 
 
& (((r   Ncompile_attempt_Tlog_pt2_compile_event)r6  r   r:  zRestarting analysis due to %sr5  d   z!Excessive RestartAnalysis() callsr  zDynamo attempted to trace the same frame 100+ times. Giving up on compiling as the compile time tradeoff is likely not worth the performance gain.r  zPReceived signal to skip frame (without graph break): %s %s                 %s %s)r  r  r  r  r   rS   )!r^   r   countr   r  attemptri   r4   r9  r*   RestartAnalysisr;  r)  r   r   rP  r  rq   r&   __traceback__r:  _cleanup_output_graphr   restart_reasonr   r?  rz  rK   r*  rQ  r   r   r   )r   r   r  r  r  r  r  r  rW  r  r  r  r  r  r:  r  r   r6  rT  failed_tracer_outputr  s   ``````` `````       @r   r  r    s   0 %&&O                 8 #?$$ 3 3'.$0	:::RVWWW  *?i*P*P'-$000#"/%,C                     " 	 	 	a!CDD '$&&&HH/11?CC  
 $+1.KT#R#R # =$::<<< 0 @CQLLAAA&*ikk#}}?!2     } 	 	 	a!CDD '$&&&#*1.KT#R#R # =$::<<<II #   	I3 3sJ   B73)B+B7+B/	/B72B/	3B77IC)F55IBI		I)r   r  r  r  rR   r  r  r  r5   r  r  ConvertFrameBox | Noner`   c                 
=>?@A ddl m}m} d?t          d          dN=fd            }t          dO
>?Afd            =t                      }                    |           nt          j                    }t          t          j                  5  t          t                              5  t          ddd          5  t          d                                          5  |5  t#          ddd          5  |5  t%                      At'                      x}rt)          |t+                                >nd >d }t-          |          r,|r*t/          
|t1                              }|sdn|d         }|                    |dd           t5                      }|r"d |D             }|                    d|           t7          |          \  }@|rdPd}t8                              d @t=          t          @           ||           |t>                     dQ@fd"}	  |             nj# t@          $ r]}t          j!        rtE          d#          ||rtE          d$          |tG          tH          j%        tH          j%                  |_&         d }~ww xY wt8          '                    d%| j(        | j)        | j*        |d&z   d'+                    tY          j-        d&|z   (          .                                                     t_          | |          } ta          j1                    }!d }"d }#d }$d }%d }&td          j3        j4        j5        6                                 d }'d }(t          j7        st          j8        st          j9        r|d)d*l:m;})m<}*m=}+  |)t          j7                  x},rt}          |,           |*t          j8                  x},rt}          |,           |+t          j9                  x},rt}          |,          	  || ||	          \  }'}(t                       |(r@|(j@        x}-r7|-A                                r#t          |            |rd+|v rt                       |'td          j3        j
        jD        rWt#          d,d-.          5  t8          E                    d/           t          jG        d)           d d d            n# 1 swxY w Y   d }.|(r|(j@        }.|.ri |._H        |.jI        x}/ri |/_J        d)d0l4mK}0 t          |0          }1|#|.t          |.jN                  }2t          |.jO        jN                  }3|.P                                }4t          |.jQ        jR                  }5|.S                                }6t          |.jT                  }7d1 |.jU        D             }8d2 |.jV        D             }9td          j3        j4        j5                                         nQd }2d }3d }4d }5i }6d }7t%          i           }8t%          i           }9t%                      Ata          j1                    |!z
  d3z  ?i d4|1d5| j(        d6| j)        d7| j*        d8|jW        d9|jX        d:|2d;|3d<|4d=|5d>|7d?|"d@|#dA|%dB|&dC|8dD|9A?|'d ut          jY        dt          ?          | t          |6          |$dE	}:|                    |:           |r|(r|(j[        nt                      |_[        |(;|(j@        4|(j@        j]        s(|(j@        j^        j_        j`        6                                 t          ja        };|;t          t                              };|;rp|(rn|(j@        rg|(j@        j^        }<|<jd        6                                 t          |<jf                   t          |(j@        dF          rt          |(j@        jh                   cd d d            cd d d            cd d d            cd d d            cd d d            cd d d            cd d d            S # t          $ r=}t          |          jk        }"t          |          }#t          jm                    g}$t          || |G           td          jo        p                    dHdI dJ K           t          jr        |          \  }%}&t=          |dLd           }(t          |t@          t          t          t          t          t          t          |t          |t          t          t          f          r t          t          |          jk         dMt          |                                         |j                  d d }~ww xY w# td          j3        j
        jD        rWt#          d,d-.          5  t8          E                    d/           t          jG        d)           d d d            n# 1 swxY w Y   d }.|(r|(j@        }.|.ri |._H        |.jI        x}/ri |/_J        d)d0l4mK}0 t          |0          }1|#|.t          |.jN                  }2t          |.jO        jN                  }3|.P                                }4t          |.jQ        jR                  }5|.S                                }6t          |.jT                  }7d1 |.jU        D             }8d2 |.jV        D             }9td          j3        j4        j5                                         nQd }2d }3d }4d }5i }6d }7t%          i           }8t%          i           }9t%                      Ata          j1                    |!z
  d3z  ?i d4|1d5| j(        d6| j)        d7| j*        d8|jW        d9|jX        d:|2d;|3d<|4d=|5d>|7d?|"d@|#dA|%dB|&dC|8dD|9A?|'d ut          jY        dt          ?          | t          |6          |$dE	}:|                    |:           |r|(r|(j[        nt                      |_[        |(;|(j@        4|(j@        j]        s(|(j@        j^        j_        j`        6                                 t          ja        };|;t          t                              };|;rq|(rp|(j@        rj|(j@        j^        }<|<jd        6                                 t          |<jf                   t          |(j@        dF          rt          |(j@        jh                   w w w w w xY w# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )RNr   )BisectValidationExceptionValidationExceptiong        compile_inner)
phase_namer   r   r  r   r  rR   r   4tuple[ConvertFrameReturn, DynamoTracerOutput | None]c           
     0   t          j                    5 }|                    t          j        j                            t          j        t          t          j                                                   |                    t          j                               |                    t                      | ||          }t          j                                        dk    s
J d            |cd d d            S # 1 swxY w Y   t#                      d fS )Nr   zQTorch function mode stack state changed while dynamo tracing, please report a bug)r
  r  r  r   _dynamocallback_handlerinstall_callbacksr   DYNAMOr   r   r  rg   recordrz   r   _len_torch_function_stackr`   )r   r  r  r   r   _compile_inners        r   r  z_compile.<locals>.compile_inner  sC    !## 	u.@@#*C0Q0S0S,T,T   
  = D F FGGG CDDD#^D)U;;F855771<<<c =<< 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	   
 	
s   CC==DD-tuple[ConvertFrameReturn, DynamoTracerOutput]c                
    t          j                     x}}d/d} |d j         j         j                    d j        v }|r(t          j                            d fd fd           d ddlm}  |t          j
                  }	 |rt          j        |          nt          j                    5  t           &' |)#$%!(          }	d d d            n# 1 swxY w Y   nV# t          j        $ rD}
|rt"                              d           |
j        J t)                      |
j        fcY d }
~
S d }
~
ww xY w!!j        
J d            |	j        |	j        }|	j        |	j        }J  |d j         j         j                   |r(t          j                            d fdfd           |j        J |j        }t5          |                                          t9          j                  t<          <   t?          t@          !                                          D ]U\  }}tE          d| d          5   |           }||urtG          |           |d d d            n# 1 swxY w Y   V tH          <   tJ          &                               ||z
  "ddl'm(} |j)        v rddl*m+}  |           d0d }J  |           } |          }d!}|d" j,        d |          d#z  }|d$j,        d |          z  } j,        d |         j,        d |         k    s
J |            d%}|d& j-         d#z  }|d'j-         z  } j-        j-        k    s
J |            d(}|d) j.         d#z  }|d*j.         z  } j.        j.        k    s
J |            |j/        r$|0                                rt)                      |fS |j1        J |j2        tf          j4        <   t          j5                    }tl          j7        r&|8                    tm          j9                               tE          d+d          5  |5  |	:                     |(d u,          }d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   (b|j;        J (<                    |j;                   (=                    |j>        j?                   (@                    |jA        jB                   t                    nd-}d.|z   }t          |jE        |          }|0                                s!|jF        |F                    |j1                   t          |          |fS )1Nprefixr   r   r   line_nor   r   r   r   r   c           	         t                               t          j                  r-t                               t          | ||||                     d S d S r   )bytecode_logisEnabledForloggingDEBUGrQ  rj   )r  r   r   r	  r   s        r   log_bytecodez6_compile.<locals>._compile_inner.<locals>.log_bytecode7  s[     ((77 ""#FD(GTJJ     r   zORIGINAL BYTECODEtorch_dynamo_resume_inartifactc                      j         dz   ddS )N_ORIGINAL_BYTECODEstringr   encodingr   r  s   r   r   z2_compile.<locals>._compile_inner.<locals>.<lambda>L       L+?? (% % r   c                 P    t          j                                                    S r   r  Bytecoder  s   r   r   z2_compile.<locals>._compile_inner.<locals>.<lambda>P  s    3<#5#5#9#9#;#; r   metadata_fn
payload_fnr'   ))get_dynamo_config_override_for_compile_idr  z,No graph captured with export/fullgraph=Truez;compiler collective wasn't run before compilation completedzMODIFIED BYTECODEc                      j         dz   ddS )N_MODIFIED_BYTECODEr  r  r  r  s   r   r   z2_compile.<locals>._compile_inner.<locals>.<lambda>  r  r   c                 P    t          j                                                    S r   r  )out_codes   r   r   z2_compile.<locals>._compile_inner.<locals>.<lambda>  s    3<#9#9#=#=#?#? r   bytecode_hooks_Tr  )BREAKPOINT_MARKERr   )register_breakpoint_codec                    dd l }| j        | j        z   t          | j        |j        z            z   t          | j        |j        z            z   S )Nr   )r  co_argcountco_kwonlyargcountr   co_flags
CO_VARARGSCO_VARKEYWORDS)r   r  s     r   
count_argsz4_compile.<locals>._compile_inner.<locals>.count_args  sY    NNN  ()t}w'99::; t}w'==>>?r   zarg mismatch: zold code object has args z, znew code object has args zfree var mismatch: zold code object has free var znew code object has free var zcell var mismatch: zold code object has cell var znew code object has cell var rC  )r  r<  r  UnknownzTorch-Compiled Region: )r  r   r   r   r   r   r	  r   r   r   r   r   r   r   r   r   )Hrz  r   r   r   r   r   r   graph_id_filterr  r(   debug_dynamo_config_overrider  r
  r  r  r*   r*  rP  rQ  r5  r`   
all_statesr   r6  r:  r2  rD  $get_replayed_side_effect_source_refsr9   r  r   	enumerater  rG  ri   r
  rt   r  r   bytecode_debuggerr%  	co_conststorch._C._dynamo.eval_framer&  co_varnamesr  co_cellvarsrW  is_empty_graphr  cleanupsrf   instancer  rz   r   r  temp_restore_stackrC  guards_stateadd_guarded_codeadd_inlined_sourcer$  rN  update_device_typecurrent_tracergraphr   rQ   guard_managerguard_export_fnrc   )*r   r  r  r:  
start_timer  is_resumption_framer  dynamo_config_overrider  rT  r6  r"  r   r  hook_outputr%  r&  r-  total_argcount_oldtotal_argcount_newmsgbuild_guards_ctxcheck_fncompile_id_strannotation_strguarded_coder#  r  r  r  r  r  r  dynamo_time_before_restartrW  r  r  r   r  r  r  s*   `                          @r   r  z _compile.<locals>._compile_inner.  sS    04y{{:*	 	 	 	 	L	
 	
 	
 7$,F 	N++    <;;; ,    NNNNNN!J!J;"
 "
	G *.3444+-- 
 !.#!'9 +&7#! ! !              ( } 	G 	G 	G J		HIII0<<<%'')FFFFFFFF		G !(,=,H,T,TI -U,TT !)%30<&3&K####L	
 	
 	
  	N++    @??? ,    )555+&==??@@ 	 **+RS #?#9#9#;#;<< 	+ 	+IC555TRRR + +"d422*"(22*8[AAA*H+ + + + + + + + + + + + + + + #'h"""%<z%I"888888 222LLLLLL$$X...	 	 	 	 ###'Z--'Z11T4+;<O=O<O+PTTTTV8+?@SAS@S+TVVV0001#$7%7$789 9 99 9 9 $Ct/?CCCCEx/CEEE8#7777777#Ct/?CCCCEx/CEEE8#7777777 = 	7V2244 	7%''66}(((,2O) &/11.4 	**3FHH   .EEE 	 	GW 	 	$11D('	 2  H	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 (444$$X%:HEEE&&v'='IJJJ&&v'<'BCCC,6,BZ	2^C""	
 
 $$&& 	15+@+L !!&-000 ..==s   )C+ 6CC+ C##C+ &C#'C+ +D>:9D93D>9D>%I77I;	>I;	RQ8,R8Q<	<R?Q<	 RRRr  T)reset_event_log_on_exitr  z+pytorch.wait_counter.entire_forward_compilez_compile.compile_innerentire_frame_compile!dynamo_cumulative_compile_time_us)r  dynamo_compile_column_usz$Unable to find recompilation reasonsF)recompile_reason#inline_inbuilt_nn_modules_candidatec                2    h | ]} |            d d         S )N   r   )r   user_contexts     r   	<setcomp>z_compile.<locals>.<setcomp>0  s4     ! ! !)5tt$! ! !r   recompile_user_contextsr   c                8    d| j          d| j         d| j         dS )N'z' (r  ))r   r   r   r  s    r   format_func_infoz"_compile.<locals>.format_func_info8  s+    U4<UUD,<UUt?RUUUUr   ztorch._dynamo hit config.%s (%s)
   function: %s
   last reason: %s
To log all recompilation reasons, use TORCH_LOGS="recompiles".
To diagnose recompilation issues, see %sr   c                     t          dd  d  dt          t                      dd  ddt           d	g
           d S )NzDynamo recompile limit exceededzLimit type: zLDynamo attempted to recompile the code object too many times, exceeding the z$ cache size limit (currently set to zj). Excessive recompilations can degrade performance due to the compilation overhead of each recompilation.zTo monitor recompilations, enable TORCH_LOGS=recompiles. If recompilations are expected, consider increasing torch._dynamo.config.z to an appropriate value.zSee z) for tips on dealing with recompilations.r  )rK   r:  r(   rx   )
limit_types   r   (raise_unimplemented_cache_limit_exceededz:_compile.<locals>.raise_unimplemented_cache_limit_exceededJ  s    =7:77!Y%/!Y !YU\]ceoUpUp!Y !Y !Y
a;Ea a a ^2]]]	     r   z/Hard failure due to fail_on_recompile_limit_hitz"Hard failure due to fullgraph=TruezBtorchdynamo start compiling %s %s:%s, stack (elided %s frames):
%s   r  r   r'   )_validate_backend_names_validate_dynamo_config_keys_validate_inductor_config_keyszsize mismatch at indexgc
gc_time_us)rV  z run_gc_after_compile: running gc)
curr_framec                    h | ]	}|j         
S r   r   r   ops     r   r\  z_compile.<locals>.<setcomp>  s    $X$X$XR_$X$X$Xr   c                    h | ]	}|j         
S r   rm  rn  s     r   r\  z_compile.<locals>.<setcomp>  s'     ( ( ((*BO( ( (r   g    eA	frame_keyr   r   r   r  r  guard_countshape_env_guard_countgraph_op_countgraph_node_countgraph_input_count	fail_typefail_reasonfail_user_frame_filenamefail_user_frame_linenonon_compliant_opscompliant_custom_ops)	r  dynamo_time_before_restart_shas_guarded_codespecialize_float
is_forward%dynamo_compile_time_before_restart_usstack_tracegraph_node_shapesexception_stack_trace_old_fake_moderZ  r  c                     dddS )Ndynamo_errorr  r  r   r   r   r   r   z_compile.<locals>.<lambda>  s    * (% % r   c                 (    t          j                    S r   	traceback
format_excr   r   r   r   z_compile.<locals>.<lambda>  s    9#7#9#9 r   r  r5  z: )r   r   r  r   r  rR   r   r  )r   r   r  r   r  rR   r   r  )r   r   r   r   )r   r   )r0  r  r  r   rb  rm   r9   r
  r  r   r(   use_lazy_graph_moduler   r   re   r   guardri   r   r   rZ   r]   r8   rP   r>   update_outerrl   r7   rP  r~  r:  rx   rL   fail_on_recompile_limit_hitrC   rb   ra   RUN_ONLYframe_exec_strategyrQ  r   r   r   rt  r%   r   formatr   rz  time_nsr   r  utilsReinplaceCountersr   debug_backend_overrider1  debug_inductor_config_overrider0  rf  rg  rh  r|  rW   r2  has_outputsrV   rU   run_gc_after_compiler  ri  collectlocal_scoperoot_txrO  rk  r   r  r  r+  count_callsrC  nodesget_graph_sizes_structuredplaceholdersr{  r|  r  r  r  rw   r  rd   rW  r$  guards_contextdynamo_guards#invalidate_compile_context_weakrefsr-   r=   rY  r   r   rI  r  rU  r?  r   r  r  r\  r   r   r*   get_exc_messager;  rM   rI   rB   AssertionErrorr   r   rJ   rH   rF   rG   rE   r  r  )Br   r   r  r  r  r  r  rW  r  r  r  r  r   r  r  r   r  r  r  r  r  metrics_contextpackage_code_context
compile_pgrW  reasonsr]  user_contexts_msgexceededra  rd  rT  r  start_time_nsrw  rx  r  ry  rz  rQ  r6  rf  rg  rh  errr2  r"  r-  rk  rq  rr  rs  rt  ru  r  rv  r{  r|  metricsshould_cleartcr  r  rR  rc  r  sB    ````` `` `  `` `                                            @@@@@r   r  r    se   .        ),"o>>>
 
 
 
 
 ?>
, R> R> R> R> R> R> R> R> R> R> R> R> R> R> R> R> R> R> ^R>h *++O&-&9T"""z?U?W?W  	v;<<a az2233a a 	d$	
 	
 	
a a 	BCCIIKKa a 	a a 	$-%H	
 	
 	
a a 	a a %(EE'))): 	% 0Z\\ J J $ (,J'' 	E 	=UL$=$= G ?FU667ST:  	$$$47< 	
 	
 	
 #F"G"G" 	N! !9P! ! !  9;LMMM6z:NN* 4	V V V V
 KK;
 
++  && #        88::::   5 1I   	1< 
 ->#,k.B- -A)   			QL1HGG%-1t8<<<CCEEFF	
 	
 	
4 'tT22 $	"&26/3 -1-33555 )	&2	& 4	&          .-f.KLLLs & oo%2263VWWWs & oo%445  s & !oo%@	*7-i*O*O'L- 3%2%??\3 !,,..3
 ,D111# 3(@DT(T(T0222h }#8 "!$NNN " "HH?@@@JqMMM" " " " " " " " " " " " " " " F 4&3 )%'"#^+6 )&(FO))))))JI"v'9!&-00(+F,<,C(D(D%!'!3!3!5!5#&v|'9#:#: $*$E$E$G$G!$'(;$<$<!$X$Xv?W$X$X$X!( (.4.I( ( ($ #599;;;;"(,%!%#' $&!$(!$'GG!'*2ww$"%%%.2lnn}.LPS-S*Y4< t/ !$"5	
 jT )**F { ()> !. #$4 $%6 Y { +,D )*@  $%6!" '(<#$ $30J$0$<$*$;"9B.: :  +%():%;%;)>9  GB ((111 !  %5M66244 "6 )!.:%29 ; *:IW]]___ "EL#  66G6T6TUU 
  	]%? 	&3CB(..000 .bl;;;}9;KLL 1)6E  
a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a ap  ,	< ,	< ,	< Q,Ia&&K%.%9%;%;$<!auV<<<<N++  :9 ,    @C?R:@ @<$&< $A'DdKKM%)",/'0-$ .  <$  /Aww+77s1vv77  .11t<U,	<f }#8 "!$NNN " "HH?@@@JqMMM" " " " " " " " " " " " " " " F 4&3 )%'"#^+6 )&(FO))))))JI"v'9!&-00(+F,<,C(D(D%!'!3!3!5!5#&v|'9#:#: $*$E$E$G$G!$'(;$<$<!$X$Xv?W$X$X$X!( (.4.I( ( ($ #599;;;;"(,%!%#' $&!$(!$'GG!'*2ww$"%%%.2lnn}.LPS-S*Y4< t/ !$"5	
 jT )**F { ()> !. #$4 $%6 Y { +,D )*@  $%6!" '(<#$ $30J$0$<$*$;"9B.: :  +%():%;%;)>9  GB ((111 !  %5M66244 "6 )!.:%29 ; *:IW]]___ "EL#  66G6T6TUU 
  	]%? 	&3CB(..000 .bl;;;}9;KLL 1)6E   
	 	}
a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a as  (ut8"t!:t
	=s3sD$s8
Is
J*AJ%%J**E(sA!`4's/S
sSsSK*sss3 t
	,t!8t8ue%(D8e  e%%e(((s/g?sgsgK/sss		ss	ss3s  s3#s $s3't
	3s77t
	:s7;t
	>t!
tt!tt!t8!t%%t8(t%)t8,u8t<	<u?t<	 uuuc                  @    e Zd Z	 	 dddZedd            Z	 dddZdS )ConvertFrameNr  r~   r  rR   r  r  r  r  r   r   c                `    || _         t          |d||          | _        || _        || _        d S )NF)r  r  r  )r-  r  _inner_convert_hooksr  )r   r  r  r  r  s        r   r   zConvertFrame.__init__l  sF     *5&2+	
 
 
  /r   *Callable[[WrapBackendDebug], ConvertFrame]c                      fdS )Nc                <    t          | j        j                  S r  )convert_framer  r  r  s    r   r   z2ConvertFrame._clone_with_backend.<locals>.<lambda>  s$    }K 1 
  
  
 r   r   r   s   `r   r  z ConvertFrame._clone_with_backend}  s    
 
 
 
 	
r   r   r   r   r  r  r  r  r   r   r`   c                   t                               |j                   t          d         dxx         dz  cc<   	 |                     |||||dz             }t          d         dxx         dz  cc<   |S # t
          $ rZ}t          |t                    r | j        j        j	        d u}|J | j        j        j	        r t          |t                    r t          |t          t          f          }	|j        }
|	r&t          |dd          st                              t           j                  rt%          |d          rt%          |d	          rt'          t)          |j                            5  |j        }d
                    t1          j        |                    }t5          j        |
          }d| d| t8          j                            dd fd           t                              dt@          j!                   d d d            n# 1 swxY w Y   t@          j"        s|	s t          |dd           }|j        }
tG          ||
||          }|	rtH          %                    |d           ntH          &                    |d           t          |t4          j'                  r!|j(        tS          |j(                  cY d }~S Y d }~nd }~ww xY wtS                      S )Nframestotalr'   r   okloggedFr  
real_stackr  zGraph break: torch.compile cannot properly resume from this graph break, which results in a skip.
torch.compile will skip tracing the frame zN and fall back to eager.
The graph break occurred in the following user code:
r  c                     dddS )Ndynamo_graph_break_reasonr  r  r   r   r   r   r   z'ConvertFrame.__call__.<locals>.<lambda>  s    (C,41 1 r   c                 4      dt          j                     S )N
r  )user_stack_traces   r   r   z'ConvertFrame.__call__.<locals>.<lambda>  s    2B/^/^iFZF\F\/^/^ r   r  T)exc_info
stack_infor[  )r  )r  )*r  r   rK  rh   r  rU  r;  rG   r  r  rJ   rL   rM   r:  graph_break_logr  r  r  rI  r   r   r  r  rt  r  format_listr*   format_frame_infor   r   r   rQ  r(   r  suppress_errorsrD   rP  r  r~  TorchDynamoExceptionr  r`   )r   r   r  r  r  r   r   rT  r  	soft_failr   
user_stackuser_stack_formatted
frame_infor[  	error_msgr  s                   @r   r  zConvertFrame.__call__  s    	%%%7###q(###g	U(({E;TAX )  F Xt$$$)$$$M a	U a	U a	U!788  #(=TI ! (333"'<    !9:: "1{I&>??I<D !8U33! $00??! 1l++ <0H0H ()E)EFF  %&\
/1ww%1*==0 0, &)%:4%@%@
6IS6 6  46 6 ) 77&) ) (_'^'^'^ 8    (--,%)'-~ .   )              4 ) )  &a):DAAO<D(D/5III 6T2222I555 1c677U)5)a>STTTTTTTTTCa	UF "###sD   9A7 7KC2K4BHKH	KH	 B,KKKrR  )
r  r~   r  rR   r  r  r  r  r   r   )r   r  r   r  r  r   r   r   r  r  k  sz        
 *.&*0 0 0 0 0" 
 
 
 X
 s$ s$ s$ s$ s$ s$ s$r   r  c                (    t          | |||          S )zHTry to convert a frame into an FX graph, if error leave frame unmodified)r  r  )r  )r  r  r  r  s       r   r  r    s$     UG_   r   r   c                   ddl m} t          j        }dt          _        t	          | d          5 }t          j        |          }d d d            n# 1 swxY w Y   t          t          j	        |j
                                        t                                                                          |_
        t          j        d          5  	 t          |j        |j
        |j        |j        |j        |ddd t'                      t)          dd          d d i t+          dd          	           |t          _        n# |t          _        w xY w	 d d d            d S # 1 swxY w Y   d S )
Nr'   )eagerFrbr   *   i  )r  r  )
r  r  rW  r  r  r  r  r   r  r  )backends.debuggingr  r(   replay_record_enabledopenrX   loadrF  r   chainr   rm  r)   r  r  r   r  r  r  rR   r5   r   )r   r  original_replay_valin_filer  s        r   replayr  	  s   )))))) 6#(F 	h		 / %g../ / / / / / / / / / / / / / /)/&.*>*>*@*@'))//BSBSTTUUFN		(	/	/ ? ?	?!#'gg4Q:: $b3GGG   $ ,?F((+>F(>>>>()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?s<   AAAEA D:-E:EEE Ec                    t           j        dk     rdS t          j        |           D ]}|j        dk    r|j        dz  c S t          d          )N)      r   RESUMEre  z$RESUME instruction not found in code)r  version_infor  r  r  offsetrs  )r   insts     r   first_real_inst_idxr  (	  sc    
'!!q$T** $ $;("";!#### #
=
>
>>r   c                      e Zd ZddddZdS )r  r   r   r   r   r  r  r  rR   r  r  r   r   r   r`   c                   d S r   r   )r   r   r  r  r  r   s         r   r  zConvertFrameProtocol.__call__2	  s	     !Sr   Nr  )r   r   r   r  r   r   r   r  r  1	  s7         ! ! ! ! ! ! ! !r   c                      e Zd ZddZddZdS )CatchErrorsWrapperr  r  r  rR   r   r   c                \     t          j        |          |            || _        || _        d S r   )r+  r,  r-  r  )r   r  r  s      r   r   zCatchErrorsWrapper.__init__>	  s/    !	!!$''')1&


r   r   r   r  r  r  r  r`   c           	        |J t                               |j                   t          j        |j        |          }t
          j        dk    r|j        t          |j                  k    }n|j        t          |j                  k    }t          j
        rt                      }nt                      }|s&|s$t          j        s|rt          | j        dd          st                               t$          j                  r[|rd}n%t          j        |j        |          rd}n|rd}nd}t                               d	|j        j        ||j        j                   t/                      S |j        j        d
k    r|j        j        dk    s/|j        j                            d          r|j        j        dk    rt/                      S |j        j        dk    ra|j        j        dk    rQ|j        j        rEt7          |j                            |j        j        d                             rt/                      S t<          j        j         !                                dk    rtE          j#                    }|rtH          5  ddl%m&}	  |	|j'        | j        j                  }
tQ          | j        d          s
J d            | j        )                    |
j*                  } |||| j+        |          cd d d            S # 1 swxY w Y   tH          5  tY                      5  |                     ||| j+        |d          }|cd d d            cd d d            S # 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )N)r   )r     r  Fztraced frame alreadyzin skipfileszSnon-infra torch dispatch mode present, this is not supported today in torch.compilezdynamo tracing is disabledz#skipping: %s (reason: %s, file: %s)r  __new__zcollections/__init__.py_maker   r   ddp_optimizer)DDPOptimizer)bucket_bytes_capbackend_compile_fnr  zJDDPOptimizer only supports callback fns that know how to clone themselves.r'   r   )-r  r   rK  r,   r  r  r  f_lastir  r(   #inline_torch_dispatch_torch_compiler"   r#   disabler:  r-  rP  r  r  r  rQ  r   r   r`   r  r(  r8  r$   rO  r  r   r  r  get_optimize_ddp_moder    _get_active_ddp_modulecompile_lock"torch._dynamo.backends.distributedr  r  rI  r  
compile_fnr  r!   )r   r   r  r  is_skipfilehas_started_executionshould_skip_for_dispatch_modeskip_reason
ddp_moduler  r  hijacked_callbackr   s                r   r  zCatchErrorsWrapper.__call__C	  s    &&&%%%!'EBBBw&&$)M4G4U4U$U!!$)M5H5V5V$V! 5 	,L,N,N)) @AA * "	( 	( ~		( .	(   >	5QQ	( .. ( ?"8KK &u|5AAA ?"0KK2 ?"wKK">K		9L(L,	   &''' L$
22u|7Ky7X7XL$--.GHH 8Y $// &''' L J..(1,,( --""5<#;A#>??  - &'''=4466/II0GIIJ !  OOOOOO$0L)3)D+/+I+c% % %M #68M    e   6JJ)4  &
 -,{DJ #               *  	 	133 	 	33{DJ! 4  F 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	sI   9A3K99K= K=M,!M;M,M	M,M	M,,M03M0N)r  r  r  rR   r   r   )r   r   r  r  r  r  r   r`   )r   r   r   r   r  r   r   r   r  r  =	  sB           
j j j j j jr   r  c                "    t          | |          S r   )r  )r  r  s     r   catch_errors_wrapperr  	  s     h...r   )r   r   r   r   r   )r   r   r   r   r   r   r   r   r  )r   r   r   r   r   r   )r   r   r   r   )r   r   r   r   )NF)
rT  rU  r   r   r   rV  rW  r   r   r   )r^  r   r   r   )r  r  r   r   r  )r  r~   r  r   rW  r   r  r  r  r  r  r  r   r  )r   r  r   r  )r   r  r   r   )r  r  r  r  r   r   )r  r   r   r  )"r   r  r   r  r  r  r  r  r  r  r  r~   r  r  r  r   r  r^   r  r  r  r  rW  r   r  r  r  r  r  r  r  r  r   rS   )rw  r   r   r   )r  r
   r   r  )r   r
   r   r  )r  r
   r   r  r   rG  r   r  )r  r
   r   r  r   rG  r  r  r  r   r   r  )r   r  r  r  r  r   r   r  )r  r  r   r  )r   r  r   r  r  r  r  r  r  r  r  r~   r  r   r  r`  rW  r   r  r  r  r  r  r  r  r  r   r9  rR  )&r   r   r   r  r  r  r  r  r  r  r  r~   r  r   rW  r   r  r  r  rR   r  r  r  r5   r   rV  r  r  r  r   r   r   r  r  r  r  r   r`   )
r  r~   r  rR   r  r  r  r  r   r  )r   r   r   r   r/  )r  r  r  rR   r   r  (	  rS  
__future__r   collectionsr
  rx  ru  r  r+  ri  rh  r  r   r  rr  rg  r  r  r  ru  	threadingrz  r  ro  typingunittest.mockr  r   r   pathlibr   r   r   r   r	   r
   r   r   typing_extensionsr   r   r   torch._loggingtorch._C._dynamo.guardsr   torch._dynamo.callbackr   torch._dynamo.distributedr   torch._dynamo.symbolic_convertr   r  r   r   r   r   r   torch._utils_internalr   r   r   torch.fx._lazy_graph_moduler   %torch.fx.experimental.symbolic_shapesr   r   torch.fx.graph_moduler   r   torch.monitorr   torch.nn.parallel.distributedr    torch.utils._python_dispatchr!   r"   r#   r$   torch.utils._tracebackr%   r&   r  r(   r)   r*   r+   r,   backends.registryr-   bytecode_analysisr.   r/   bytecode_transformationr0   r1   r2   r3   r4   r  r5   r6   r7   r8   r9   
eval_framer:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   graph_bytecode_inputsrN   r  rO   rP   rQ   r  rR   r2  rS   rT   pgorU   rV   rW   replay_recordrX   resume_executionrY   symbolic_convertrZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   r  rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   variables.torch_functionrz   r  numpyr{   ModuleNotFoundErrorTYPE_CHECKINGcollections.abcr|   torch.utils.weakr}   r~   r  r   repro.after_dynamor   r   r   r   variables.builderr   	getLoggerr   rP  r   getArtifactLoggerr  r  RLockr  r   r   r   r   r   r  r  r   r,  r   r   r.  #suppress_torch_distributed_warningsrS  r\  r  Counterr]  rb  ra  r  r  r  r  r  torch.utils.hooksr  r  r   r  r  r
  r  r7  r9  rU  r\  r|  rH  r  r  r  r  r  r  r  r  r  r  r  r  r  r  Protocolr  r  r  r   r   r   <module>r0     sG    . # " " " " "              



     				           				       



                    ! ! ! ! ! !       > > > > > > > > > > > > ) ) ) ) ) ) ) ) ) ) ' ' ' ' ' ' ! ! ! ! ! !      4 4 4 4 4 4 2 2 2 2 2 2 4 4 4 4 4 4 9 9 9 9 9 9 M M M M M M M M M M M M % % % % % %         
 ? > > > > >        Q P P P P P & & & & & & A A A A A A            M L L L L L L L E E E E E E E E E E E E E E 5 5 5 5 5 5 G G G G G G G G                         ' & & & & &                                               > = = = = =         
       ? ? ? ? ? ? ? ?         
 + * * * * * ; ; ; ; ; ;              " ! ! ! ! ! X X X X X X X X X X X X                                               0 J I I I I I       	BBB 
 	7((((((444444------''''''444444@@@@@@@@@@666666 g!!~//*EE.228^LL y  WT]]Yt__	 	 	 	 	 	 	 	% % % %       ( giiwyy04  4 4 4 4 *++JN    ,+    DM M M M` 1K K K 21Kb %)	* * * * * CV;CVCXCX  X X X X   H H H HV - - - - - - - -   .x x x x x x x xz %)%)"&    & $ # # # # # - - - - - - ,7;== 8 8 8 8*F '   $6 6 6 6

 
 
 
     %)?C15%)#O O O O O Od 8
 8
 8
 8
 8
 8
 8
 8
v + + + + + + + +" $3 3 3 3 3 3 3 3l    V V V V V V V Vr 
 
 
 
 
 
 
 
@.A .A .A .Ab7 7 7 7 %)% % % % %V %)$

 ,0-2$
 $
 $
 $
 $
 $
N & & & & & & & & ,0-2	5 5 5 5 5 5r   > %)?C15%)j j j j j jt %)?Cq	" %) 15+q	 q	 q	 q	 q	 q	hM$ M$ M$ M$ M$ M$ M$ M$f &*"&		 	 	 	 	? ? ? ?@? ? ? ?	! 	! 	! 	! 	!6? 	! 	! 	!p p p p p p p pf/ / / / / /s   H HH