
    ɯwg                       U 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mZ d dlmZmZmZmZ d dlmZmZmZmZmZ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+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1 d dl&m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z;m<Z< d dl=m>Z? d dl@mAZA d dlBmCZCmDZD d dlEmFZFmGZG ddlHmIZImJZJmKZK ddlLmMZMmNZN ddlOmPZPmQZQmRZRmSZSmTZT ddlUmVZVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z] ddlJm^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZg ddlhmiZimjZjmkZk ddllmmZm ddlnmoZo ddlpmqZqmrZrmsZsmtZt ddlKmuZu dd lvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZmZmZ d!ed"<   	 d dlZej                  rdd#lmZ dd$lmZ dd%lmZmZ dd&lmZ  ej,                  e      Ze%j2                  j5                  ed'      Ze%j2                  j5                  ed(      Z ej:                         Z e d)      Z e#d*      Z G d+ d,      Z G d- d.      Z e       Z e       Zdad/ed0<    ejL                  e?      	 dN	 	 	 	 	 	 	 dOd1       ZdPd2Ze]jR                  dQd3       Z	 	 dR	 	 	 	 	 	 	 	 	 dSd4Zd a ejZ                         Zd5ed6<   dTd7ZdTd8Z G d9 d:      Z	 	 	 dU	 	 	 	 	 	 	 	 	 dVd;Zd d<lmZ d d=lmZ ej                  rdd>lmZ  e       Zd?ed@<   dWdAZ	 	 dXd dB	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dYdCZ G dD dE      ZdZdFZd[dGZd\dHZ G dI dJej~                        Z G dK dL      Z	 	 	 	 	 	 d]dMZy# e$ r dZY w xY w)^    )annotationsN)Path)CodeType	FrameTypeFunctionType
ModuleType)AnyCallableDictListOptionalSetTypeVarUnion)	ParamSpec)ReferenceType)GlobalStateGuard)get_compile_pg)CompileTimeInstructionCounter)compile_contextCompileContext	CompileIdtracing)
structured)compile_time_strobelight_metajustknobs_check#maybe_upload_prof_stats_to_manifoldsignpost_event)_use_lazy_graph_module)ConstraintViolationErrorGuardOnDataDependentSymNode)_forward_from_src)DistributedDataParallel)_disable_current_modesis_in_torch_dispatch_mode)CapturedTracebackformat_traceback_short   )configexctrace_rules)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_cache_size_limitis_recompilation)always_optimize_code_objects	skip_codeTorchPatcher)
augment_exc_messageBackendCompilerFailedCacheLimitExceededformat_error_msgInternalTorchDynamoErrorSkipCodeRecursiveExceptionTorchRuntimeErrorUncapturedHigherOrderOpErrorunimplementedUnsupported)CheckFunctionManager&get_and_maybe_log_recompilation_reasonGuardedCode)Hooks)ExecutionRecord)DistributedStateInstructionTranslator
LocalStateSpeculationLog)is_numpy)CleanupManagerCompilationMetricscountersdynamo_timedformat_bytecodeframe_phase_timinggen_record_file_nameget_chromium_event_loggerincrement_frameis_namedtupleistype
LazyStringorig_code_maprecord_compilation_metricsreset_graph_break_dup_checkersetup_compile_debugtroubleshooting_urlwrite_record_to_filezOptional[ModuleType]np)
CompilerFn)WrapBackendDebug)BytecodeHook
CacheEntry)FrameStateSizeEntrybytecodegraph_breaks_T_Pc                      e Zd Zy)TODO_UNKNOWNN)__name__
__module____qualname__     `/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.pyrk   rk      s    rp   rk   c                  ,    e Zd ZddZddZddZddZy)	Trackerc                0    g | _         t               | _        y N)seensetseen_idsselfs    rq   __init__zTracker.__init__   s    35	"%%rp   c                     t        |       j                  vrQt        j                  | fd      } j                  j                  |        j                  j                         y y )Nc                :    j                   j                        S ru   )rx   remove)_idxrz   s    rq   <lambda>zTracker.add.<locals>.<lambda>   s    DMM4H4H4M rp   )idrx   weakrefrefrv   appendadd)rz   
strong_objobjr   s   `  @rq   r   zTracker.add   sR    ndmm#++j*MNCIIS!MMc" $rp   c                0    t        |      | j                  v S ru   )r   rx   )rz   items     rq   __contains__zTracker.__contains__   s    $x4==((rp   c                l    | j                   j                          | j                  j                          y ru   )rv   clearrx   ry   s    rq   r   zTracker.clear   s     		rp   N)returnNone)r   r   r   r   )r   r   r   bool)rl   rm   rn   r{   r   r   r   ro   rp   rq   rs   rs      s    (#)rp   rs   zOptional[GlobalStateGuard]initial_global_statec                J    t        | ||      }t        |j                         |S ru   )original_forward_from_srcr8   __code__)srcglobals	co_fieldsresults       rq   fx_forward_from_src_skip_resultr      s#     'sGY?FfooMrp   c                R     t        j                         d fd       } |_        |S )z
    Context manager to:
        1) Save/restore torch.is_grad_enabled() state
        2) Save/restore python random state
        3) Save/restore torch random state
        4) Monkey patch torch.fx.graph_module._forward_from_src
    c                 |   t               }t        j                         }t        j                  j	                         5  t        j
                         }t        j                         }t        j                         }t        j                         }t        j                  j                         }d }	t        j                  j                         rt        j                  j                         }	t        j                  j                         }
t        j                  j                  j                   }t"        t        j                  j                  _        t%               }t'        j(                         }|j+                  t        j                  j,                  j/                                	  | i ||j1                          |j1                          t        j                  j3                  |       t        j4                  j6                  j9                  |       t        j:                  ||       t        j<                  |       t        j                  j?                  |       |	t        j                  j?                  |	       t        j                  jA                  |
       |t        j                  j                  _        |jC                         sJ d|jE                          d       cd d d        S # |j1                          |j1                          t        j                  j3                  |       t        j4                  j6                  j9                  |       t        j:                  ||       t        j<                  |       t        j                  j?                  |       |	t        j                  j?                  |	       t        j                  jA                  |
       |t        j                  j                  _        |jC                         sJ d|jE                          d       w xY w# 1 sw Y   y xY w)N)	warn_onlyzGlobal z7state changed while dynamo tracing, please report a bug)#r   torchis_grad_enabled_C_PreserveDispatchKeyGuardis_inference_mode_enabled$are_deterministic_algorithms_enabled-is_deterministic_algorithms_warn_only_enabledrandomgetstateget_rng_statecudais_available_get_cublas_allow_tf32fxgraph_moduler"   r   r]   
contextlib	ExitStackenter_context_symbolic_trace_maybe_revert_all_patchesclose_set_grad_enabledautograd	grad_mode_enter_inference_modeuse_deterministic_algorithmssetstateset_rng_state_set_cublas_allow_tf32checkreason)argskwargsguardsprior_grad_modeprior_inference_modeprior_deterministicprior_warn_onlypy_rng_statetorch_rng_statecuda_rng_state
allow_tf32prior_fwd_from_srccleanup
exit_stackfns                 rq   _fnz"preserve_global_state.<locals>._fn   s   !#//1
 XX//1 $	f#(#B#B#D "'"L"L"N#QQSO!??,L#ll88:O!Nzz&&(!&!9!9!;88:J!&!6!6!H!H6UEHH!!3)+G#--/J$$((BBDf4*6*  "**?;((>>?ST22'? -**?;!-JJ,,^<//
;:L%%7LLNfV]]_--def"G$	f $	f*   "**?;((>>?ST22'? -**?;!-JJ,,^<//
;:L%%7LLNfV]]_--def"G$	f $	fs&   E'P2&K2-D;P22D=P//P22P;r   z_P.argsr   z	_P.kwargsr   rh   )	functoolswraps_torchdynamo_orig_callable)r   r   s   ` rq   preserve_global_stater      s2     __R+f +fZ &(C"Jrp   c                p   | j                   t        v ry| j                   j                  D ]  }|| j                  v s| j                  |   }t	        |t
              r%|j                  j                  d      s|t        u r yt        s]t        j                  sn|t        u st        |      s y i dfd| j                  j                         D ]  } |      s y t        j!                  d| j                   j"                  | j                   j$                  | j                   j&                         y)z+Check if the frame has torch.* related bitsTztorch.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                  rDt        r>t         t        j                        st         t        j                        r
d|<   |   S t         t        t        f      rt!        fd D              |<   |   S t         t"              r5t         j%                               }t!        fd|D              |<   |   S t         t&        t(        t*        t        d      t,        f      r
d|<   |   S t/               r3t1         d      r't!         fd j2                  D              |<   |   S y)z)Recursively check if the obj has a tensorFTc              3  .   K   | ]  } |        y wru   ro   .0v
has_tensors     rq   	<genexpr>z:has_tensor_in_frame.<locals>.has_tensor.<locals>.<genexpr>  s     ">Q:a=">   c              3  .   K   | ]  } |        y wru   ro   r   s     rq   r   z:has_tensor_in_frame.<locals>.has_tensor.<locals>.<genexpr>"  s     "AQ:a="Ar   N_fieldsc              3  B   K   | ]  } t        |              y wru   )getattr)r   r   r   r   s     rq   r   z:has_tensor_in_frame.<locals>.has_tensor.<locals>.<genexpr>(  s     "T1:gc1o#>"Ts   )r   
isinstancer   TensornnModulerX   type
issubclassr)   trace_numpyr`   ndarraygenericlisttupleanydictvaluesstrintfloatr   rW   hasattrr   )r   obj_idr   r   rx   s   `  rq   r   z'has_tensor_in_frame.<locals>.has_tensor  s   CXF## cELL%((//:;3*S%((//"B#HVF##RZZ(JsBJJ,G#HVF##C$'"">#">>HVF##C #**,'F""A&"AAHVF##C#sE4:t<=$HVF##3GC$;""T"TTHVF## rp   z0skipping because no torch.* %s             %s %sF)r   objectr   r   )f_coder7   co_names	f_globalsr   r   rl   
startswithr   r`   r)   r   rM   f_localsr   logdebugco_nameco_filenameco_firstlineno)framer   r   valuer   rx   s       @@rq   has_tensor_in_framer      s     ||33 <<(( 	eoo%//'*C#z*''1SE\f((cRi8C=	 !#H(V &&( e II	  ## rp   c                    d }t        | d      r)t        | |      }t        || j                         || _        t        | |       y )Nexec_recordexport)r   rT   r_   r   record_filenamer:   )ecoder   r  r  s        rq   exception_handlerr  A  s?     Oq- .q$7_amm<+&)rp   z/typing.Counter[Union[int, FrameStateSizeEntry]]FRAME_COMPILE_COUNTERc                <    t         j                  rt        |       S | S ru   )r)   cprofilecprofile_wrapper)funcs    rq   maybe_cprofiler  V  s    %%Krp   c                D     t        j                         d fd       }|S )Nc                 P   t        j                         }|sJ d       t        dj                   dt	        |      j                  dd       d      }t        j                         }|j                          t        j                         } |j                  g| i |}t        j                         |z
  }|j                          t        j                  dj                  ||       t        j                  |      }	 |j!                  |       t        j                  d|       |j'                  d	      }		 t)        j*                  d
dddddt	        |      gt(        j,                        }
t)        j.                  dddt	        |	      g|
j0                         t        j                  d|	       t?        t	        |            xr#t@        jB                  jE                  dfd       |S # t"        $ r t        j%                  d|       Y w xY w# t2        $ r t        j                  d       |j5                  t        j6                  j8                        j;                  d       |j5                  t        j6                  j<                        j;                  d       Y w xY w)NzTrace id is Nonez/tmp/r   /z.profilez7### 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)nameurlro   )manifold_links   rq   r   z;cprofile_wrapper.<locals>.profile_wrapper.<locals>.<lambda>  s    !8O rp   )#r   current_trace_idr   rl   r   replacecProfileProfileenabletimeruncalldisabler   warningr  Stats
dump_statsPermissionError	exceptionwith_suffix
subprocessPopenPIPE
check_callr  FileNotFoundError
sort_statsSortKeyTIMEprint_stats
CUMULATIVEr   r   _loggingtrace_structured)r   r   trace_idprofile_pathprofstart_tsretvalprofile_latencypssvg_pathgprof2dot_processr  r  s              @rq   profile_wrapperz)cprofile_wrapper.<locals>.profile_wrapper]  sH   !224+++xDMM?!CM$9$9#s$C#DHM
 !99;d4T4V4))+0EMM		
 \\$	>OOL) 	'6++F3	E * 0 087-% "! !!s8}5'.. KK:HE @
 
= 
 NN++O K  	>MM.=	>, ! 	EKKN MM&..--.::2>MM&..334@@D	Es&   G/ ;A9H /HHBJ%$J%r   )r   r   )r  r?  s   ` rq   r
  r
  \  s'    __T: :x rp   c                  d    e Zd Z	 	 	 d	 	 	 	 	 	 	 	 	 ddZed	d       Zdd	 	 	 	 	 	 	 	 	 	 	 d
dZy)ConvertFrameAssertNc                P    t                || _        || _        || _        || _        y ru   )r\   r   
_one_graph_export_export_constraints)rz   compiler_fn	one_graphr  export_constraintss        rq   r{   zConvertFrameAssert.__init__  s(     	&'*5'##5 rp   c                      fdS )Nc                \    t        | j                  j                  j                        S ru   )convert_frame_assertrC  rD  rE  backendrz   s    rq   r   z8ConvertFrameAssert._clone_with_backend.<locals>.<lambda>  s$    3T__dllD4L4L 
 rp   ro   ry   s   `rq   _clone_with_backendz&ConvertFrameAssert._clone_with_backend  s    
 	
rp   r   skipc               n   t                |j                  }t        ||      }t        j	                  |       |t
        v ry t        j                  j                  d      r-t        j                  j                  d      |j                  k7  ry |j                  dk(  r|j                  j                  d      ry |j                  dk(  ry |j                  dk(  rQ|j                  j                  t        j                  j                  t        j                   j"                              ry |j                  dk(  r|j                  dk(  ry |j                  dk(  r%|j                  dk(  rt%        |j&                        sy t)        |      rt+        d	       t-        |      sy t/               ad
|vrt2        |d
<   t2        dz  a|d
   }t5        |t6              sJ t8        |   }	t8        |xx   dz  cc<   t;        ||	      }
t=        dd|j                  |t?        |
      |j                  |j@                  |jB                  |jD                  d       tG        |j                  |jH                  |jJ                  |j&                  | jL                  | jN                  | jP                  | jR                  ||||||
|dz         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>	generator_idr(   dynamoz_convert_frame_assert._compile)r   frame_id
compile_idr   r   
cache_sizeaccumulated_cache_size)frame_staterY  rP  )*rV   r   r4   input_codesr   output_codesosenvirongetr   r   endswithr   pathdirnamer   optim__file__r   
f_builtinsr0   rB   r   r   r   FRAME_COUNTERr   r   r  r   r   r   r   +num_cache_entries_with_same_id_matched_objsnum_cache_entries_compiler   r   r   rC  rD  rE  )rz   r   cache_entryhooksr\  rP  r  rZ  rX  frame_compile_idrY  s              rq   __call__zConvertFrameAssert.__call__  s]    	||'{;
<JJNN78

;<L<<;&4+;+;+D+D,
 <<=( <<:%$*:*:*E*EGGOOEKK001+

 
 <<:%$*:*:j*H LLJ&  J.))* +&"5)  01 #!.KQMu%(C(((0:h'1,'x)9:
,<<$!*o#//"&"5"5(TT*4*F*F	
 LLOONN++OOLL$$#!
 	
rp   TFN)
rF  ra   rG  r   r  r   rH  Optional[typing.Never]r   r   )r   z*Callable[[CompilerFn], ConvertFrameAssert]r   r   rl  Optional[CacheEntry]rm  rG   r\  *Dict[str, Union[int, FrameStateSizeEntry]]rP  r   r   Optional[GuardedCode]rl   rm   rn   r{   propertyrN  ro  ro   rp   rq   rA  rA    s     5966 6 	6
 36 
6 
 
 l
l
 *l
 	l

 @l
 l
 
l
rp   rA  c                    t        | |||      S )z&Fully convert a frame into an FX graph)rA  )rF  rG  r  rH  s       rq   rK  rK  !  s     k9f>PQQrp   )OrderedDict)RemovableHandle)OutputGraphzDict[int, BytecodeHook]_bytecode_hooksc                J    t        t              }| t        |j                  <   |S )zRegister hooks for bytecode generated by Dynamo. The hook can do some
    logging, as well as return a new code object to be used. Please refer
    to `BytecodeHook` for the hook signature.
    )rz  r|  r   )hookhandles     rq   register_bytecode_hookr  7  s!    
 _-F!%OFIIMrp   rO  c          !        123456789:;< ddl m2m}m<m} d5d 7d ;t
        	 	 	 	 	 	 d2 467:;<fd       }	 	 	 	 	 	 	 	 	 	 d1fd}t        d      t        	 	 	 	 	 	 	 	 	 	 d4579fd              1t        t        j                        5  t        t                    5  t               9t               6t               :t               x}rt!        |t#                     4nd 4t$        j&                  j(                  j+                          d 8t-        |
      r|rt/        |	|      8t1        |
      \  }}|rxd d	}d!8fd
}t2        j5                  d|t7        t        |       |        |       t8               t        j:                  rt=        d      rt?        | d      tA        | d       t2        jC                  d jD                   jF                   jH                  dz   djK                  tM        jN                  dz         jQ                                      tS        jT                  tV              3tY               }|j[                          t$        j\                  j_                  d 3fd       ta        j`                         }d }d }d }d }t$        j&                  jb                  jd                  d   d   }d }	  | ||      }|;ri ;jf                  _4        ddl1m5}  tm        |       }!|\7Y|!tn        v rPtq        7jr                        }"tq        7jt                  jr                        }#7jw                         }$tq        7jx                  jz                        }%tq        7j|                        }&tn        |!   j                  dd       }'tn        |!   j                  dd       }(tn        |!   j                  dd       })tn        |!   j                  dd       }*7j                  D +ch c]  }+|+j                   },}+7j                  D +ch c]  }+|+j                   }-}+t$        j&                  jb                  jd                  d   d   |z
  }.nKd }"d }#d }$d }%d }&d }'d }(d })d }*t        i       },t        i       }-t               9ta        j`                         |z
  5d }.t        tm              |! jD                   jF                   jH                  |
j                  |
j                  |"|#|$|%|&||'|(|)|*|||||,|-95|d u|.      }/t        |/       t$        j&                  j(                  j                          cd d d        cd d d        S c c}+w c c}+w # t        $ r}0t        |0      j                  }tm        |0      }t        |0 |       t        j                  |0      \  }}t        |0t        t        t        t        t        t        |t        |f	      r t        t        |0      j                   dtm        |0             j                  |0j                        d d }0~0ww xY w# ;ri ;jf                  _4        ddl1m5}  tm        |       }!|h7e|!tn        v r\tq        7jr                        }"tq        7jt                  jr                        }#7jw                         }$tq        7jx                  jz                        }%tq        7j|                        }&tn        |!   j                  dd       }'tn        |!   j                  dd       }(tn        |!   j                  dd       })tn        |!   j                  dd       }*7j                  D +ch c]  }+|+j                   nc c}+w },}+7j                  D +ch c]  }+|+j                   nc c}+w }-}+t$        j&                  jb                  jd                  d   d   |z
  }.nKd }"d }#d }$d }%d }&d }'d }(d })d }*t        i       },t        i       }-t               9ta        j`                         |z
  5d }.t        tm              |! jD                   jF                   jH                  |
j                  |
j                  |"|#|$|%|&||'|(|)|*|||||,|-95|d u|.      }/t        |/       t$        j&                  j(                  j                          w xY w# 1 sw Y   nxY wd d d        y # 1 sw Y   y xY w)"Nr   )bisectBisectValidationExceptiontranslation_validation_enabledValidationExceptiong        c                   j                          t        | 
|	      	 t        j                  j                        5  j                         5  j                          d d d        d d d        j                  j                          j                  J j                  sJ j                  | d d  |j!                  j"                         t$        j&                  r.t)        |        t+        |        t-        t/        |             | d d  y y # 1 sw Y   xY w# 1 sw Y   xY w# t        j                  $ r j                           t        j                  t        j                  f$ r  t        $ r%         r j                  j                          w xY w# j                  j                          w xY w)N)r\  speculation_logdistributed_state)restartrJ   r   outputtracing_contextset_current_txrunr*   UnspecializeRestartAnalysisr   SpeculationRestartAnalysis	SkipFrame	Exception	shape_envcall_cleanup_hooksoutput_instructionsupdatecode_optionsr)   dead_code_eliminationr1   r.   r-   r,   )instructionsr  r  builtinsr  rF  r  r  rH  r\  r   localsmutated_closure_cell_contentsrG  r  r  tracerr  s     rq   	transformz_compile.<locals>.transform`  s    	!&)#+/
"	/667 9N9N9P 

  MM,,.!!!)))) 44QF//0'',\:,\:45El5STLO ()   .. 	!!#..> 	 	-/v}}../	
 MM,,.sH   D6 D*D-D*5D6 D'	#D**D3/D6 6A4F**F- -G	c                    t        dd      5  t        j                         5   | |||      cd d d        cd d d        S # 1 sw Y   nxY w	 d d d        y # 1 sw Y   y xY w)Nz_compile.compile_innerentire_frame_compile
phase_name)rQ   r   record)r  rG  rm  r  _compile_inners       rq   compile_innerz_compile.<locals>.compile_inner  su     2?UV 	I.557 I%dIuiHI I	I 	II I I	I 	I 	Is!   AA	AA	AA!r  r  c           	        t        j                          x}}	 	 	 	 	 	 	 	 	 	 	 	 dd} |d| j                  | j                  | j                  |        d }t	        j
                         D ])  }|t        j                         _        	 t        | |      } n j0                  J d       |J  |d	| j                  | j                  | j                  |       t2        j5                         D ]  }
 |
| |      }||} | t6        |<   t8        j#                  |       ||z
  J dd
}|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jC                         ry jD                  J jF                  tH        jJ                  |<   tM        |r|jN                  nd       }tQ        ||jR                        }jC                         s'|jT                  |jU                  jD                         |S # t        j                  $ r}	t        j                  dt        t        |	j                                j#                  |	j$                  xs t'        t)        |	                   t        j                          }|dkD  rt+        d       Y d }	~	d }	~	wt        j,                  $ rY}	t        j/                  d|	| j                  | j                  | j                         |rt        j/                  d       Y d }	~	 y d }	~	ww xY w)Nc           	         t         j                  t        j                        r#t         j	                  t        | ||||             y y ru   )bytecode_logisEnabledForloggingDEBUGr   rR   )prefixr  filenameline_nor  s        rq   log_bytecodez6_compile.<locals>._compile_inner.<locals>.log_bytecode  s9     ((7""#FD(GTJ 8rp   zORIGINAL BYTECODEzRestarting analysis due to %sd   z100+ RestartAnalysis() callsz.Skipping frame %s %s                     %s %sz%No graph captured with one_graph=Truez;compiler collective wasn't run before compilation completedzMODIFIED BYTECODEc                    dd l }| j                  | j                  z   t        | j                  |j
                  z        z   t        | j                  |j                  z        z   S )Nr   )inspectco_argcountco_kwonlyargcountr   co_flags
CO_VARARGSCO_VARKEYWORDS)r  r  s     rq   
count_argsz4_compile.<locals>._compile_inner.<locals>.count_args  s]       (()t}}w'9'99:; t}}w'='==>?rp   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 )r  r   r  r   r  r   r  r   r  r   r   r   r  r   r   r   )+r!  r   r   r   	itertoolscountr   ra  attemptr2   r*   RestartAnalysisr   inforY   r'   __traceback__r   restart_reasonr   r   rB   r  r   
all_statesr|  r   rZ   r^  co_varnamesco_freevarsco_cellvarsr  is_empty_graphr   cleanupsrN   instancerD   guard_fail_fnrF   check_fnguard_export_fn)r  rG  rm  r  last_attempt_start_time
start_timer  out_coder  r  r~  hook_outputr  total_argcount_oldtotal_argcount_newmsgr  guarded_coderY  r  dynamo_time_before_restartr  restart_reasonss                     rq   r  z _compile.<locals>._compile_inner  s:    04yy{:*		"	.1	<?	GO		 	LL	
  ( 	G+2N (0yA		< %):)E)E)Q	IH	IQ ###LL	
 $**, 	'DtX.K&&	'
 #'h"%<z%I"!!!	 ###'-'1*4+;+;<O=O+P*QQSTT*8+?+?@SAS+T*UVV001##$7%789	 	9 $.t/?/?.@CC.x/C/C.DEE8#7#77<<7#.t/?/?.@CC.x/C/C.DEE8#7#77<<7 ==V224}}(((,2OO)'#(Ed

 #8X->->
K$$&5+@+@+L !!&--0] && 
B35qG
  ##A$4$4$DDGE*.))+'S=!"@A== 		LL$$'' IIEFs&   KO#BM,,OAOOc                V    d| j                    d| j                   d| j                   dS )N'z' (:))r   r   r   )r  s    rq   format_func_infoz"_compile.<locals>.format_func_infoD  s0    4<<.D,<,<+=Qt?R?R>SSTUUrp   c                      sy d   S )Nz$Unable to find recompilation reasonsro   )recompile_reasonss   rq   format_guard_failuresz'_compile.<locals>.format_guard_failuresG  s    (A(,,rp   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 %s.z7pytorch/compiler:skip_code_recursive_on_cache_limit_hitz reachedzBtorchdynamo start compiling %s %s:%s, stack (elided %s frames):
%s    rO  dynamo_startc                 .   dt        t        j                  fdt        j                  t        j                  dz         j                                            j                   j                  t        j                   j                        dgz   iS )Nstackc                    | d   k7  S )Nr  ro   )fconvert_frame_interns    rq   r   z,_compile.<locals>.<lambda>.<locals>.<lambda>  s    !J-3G"G rp      rO  )liner  r  )r   r  	takewhiler   from_tracebackr&   extractsummaryr   r   intern_stringr   )r  r  rP  s   rq   r   z_compile.<locals>.<lambda>  s    ''G"11-551t8DLLN !% 3 3 $$.$<$<T=M=M$N rp   inductor)possibly_missed_reinplacing_opportunitiesr(   )
curr_framer  backend_compileinductor_compilecode_genr  z: )r  zList[Instruction]r  Dict[str, object]r   r   )
r  r   rG  r   rm  rG   r  z2Callable[[List[Instruction], Dict[str, Any]], Any]r   ru  )r  r   r   r   )r   r   )Xtorch.fx.experimental.validatorr  r  r  r  r   r   r  r   r)   use_lazy_graph_moduler   r   rw   rL   r   rI   rK   r   _dynamocallback_handlerrun_start_callbacksr6   rE   r5   r   r$  r   r^   &skip_code_recursive_on_cache_limit_hitr   r<   rB   r   r   r   r   joinr&   r  formatr   r  rf  rU   resetr4  r5  r!  utilsrP   r  local_scoper  r   rS   lenr   r  count_callsgraphnodesplaceholdersra  non_compliant_opsrn   compliant_custom_opsrO   ri  rj  r[   run_end_callbacksr  r   r  r*   get_exc_messager   rC   r@   r;   AssertionErrorr    r!   rA   r>   with_tracebackr  )=r  r   r  r  rF  rG  r  rH  rm  rl  rZ  r   r\  rY  rP  r  r  r  r  
compile_pgexceeded
limit_typer  r  chromium_event_logr  	fail_typefail_reasonfail_user_frame_filenamefail_user_frame_lineno/start_possibly_missed_reinplacing_opportunitiesr  r  	frame_keyguard_countshape_env_guard_countgraph_op_countgraph_node_countgraph_input_countentire_frame_compile_timebackend_compile_timeinductor_compile_timecode_gen_timeopr  r  r  metricsr  r  r  r  r  r  r  r  r  r  r  r  r  s=   ````````    ```                                  @@@@@@@@@@@@rq   rk  rk  A  s	   $  ),$(F.2F/U'/U7H/U	/U /U /U /UbIII I F	I
 
I #o>MMM M F	M
 
M M  ?M^ 
  < <	= b?z"@ b? %(E25%%(*')):) 0Z\ J $&&::< !J'E FU!  8
JO*V-
 KK<
 
+ &%'# <<IB )J<x)@AA H56		QLL1HGG%--1t8<CCEF	
4  *77A68  "''	
( YY[
#'	%)26 04:?--:M:M:V:V;

5;77 t	?(y%KL> ,.))JI#&!33!&--0(+F,<,<,C,C(D%!'!3!3!5#&v||'9'9#: $'(;(;$<!,>y,I,M,M*D-) (:)'D'H'H%t($ );9(E(I(I&)% !39 = A A*d S?E?W?W$XR__$X!$X.4.I.I((*BOO($ ( MM''00<C FF : #(,%!%#' $(!,0)'+$(,% $$'G!'*2w$"%%-1YY[:-E*<@9(J  ##FF,,% !)$%(&!$*D(97G: 'w/MM**<<>Eb? b? b?R %Y(s  	<Q,,Ia&K auV<?B?R?R:@<$&< %)",/'0-
  /Aw++,Bs1vh7 .1t<5	<< ,.))JI#&!33!&--0(+F,<,<,C,C(D%!'!3!3!5#&v||'9'9#: $'(;(;$<!,>y,I,M,M*D-) (:)'D'H'H%t($ );9(E(I(I&)% !39 = A A*d S?E?W?W$XR__$X$X!$X.4.I.I((*BOO( ($ ( MM''00<C FF : #(,%!%#' $(!,0)'+$(,% $$'G!'*2w$"%%-1YY[:-E*<@9(J  ##FF,,% !)$%(&!$*D(97G: 'w/MM**<<>Eb? b? b? b? b?s   #b<8Hb'U""Db'?U
b'"U
5Db'	b<
b'"	X0+C X++X00X33Db$]%$b$:^Db$$b''b0	,b<<cc                  H    e Zd ZddZedd       Z	 d	 	 	 	 	 	 	 	 	 	 	 ddZy)	ConvertFramec                D    || _         t        |d      | _        || _        y )NF)rG  )r   rK  _inner_convert_hooks)rz   rF  rm  s      rq   r{   zConvertFrame.__init__  s     *5'2;%Prp   c                      fdS )Nc                0    t        | j                        S ru   )convert_framer"  rL  s    rq   r   z2ConvertFrame._clone_with_backend.<locals>.<lambda>  s    }WdkkB rp   ro   ry   s   `rq   rN  z ConvertFrame._clone_with_backend  s	    BBrp   c                   t         d   dxx   dz  cc<   	 | j                  |||||dz         }t         d   dxx   dz  cc<   |S # t        $ r}t        |t              r t        |t
              }t        |t
              rt        j                  t        j                        rt        |d      r|t        t        |j                              5  |j                  }	dj                  t!        j"                  |	            }
t        j%                  d|
d	
       d d d        n# 1 sw Y   nxY wt&        j(                  s|s t+        |dd       }|j,                  }t/        ||||      }|rt0        j3                  |d	
       nt0        j5                  |d	
       t        |t6              r3t8        j:                  j<                  j>                  j@                  cY d }~S Y d }~y d }~ww xY w)Nframestotalr(   rO  okrY  r  z(Graph break: skip: from user code at:
%sT)exc_infor  )!rP   r!  r  r   rA   rC   graph_break_logr  r  r  r   r   r   rY  
real_stackr  	tracebackformat_listr   r)   suppress_errorsr   r   r=   r   r  r$  r?   r   r   r  
eval_frameskip_code_recursive_flag)rz   r   rl  rm  r\  rP  r   r  	soft_fail
user_stackuser_stack_formattedr  r  	error_msgs                 rq   ro  zConvertFrame.__call__  s    	7#q(#C	L(({E;TAX ) F Xt$)$M =	L !9:"1k2I ![)o.J.J/ 1l+()EF 	%&\\
/1ww%11*=0, (--G0%) . 	 	 	 ))) &a):DAO<<D(D/5IIT2I5 !78xx''22KKK 9 =	Ls8   .A 
G#A>GA	D	GD(	$B/GG#G#N)rF  ra   rm  rG   r   r   )r   z*Callable[[WrapBackendDebug], ConvertFrame])r   )r   r   rl  rs  rm  rG   r\  rt  rP  r   r   zOOptional[Union[GuardedCode, torch._C._dynamo.eval_frame.SkipCodeRecursiveFlag]]rv  ro   rp   rq   r  r    si    
 C C PP *P 	P
 @P P
Prp   r  c                    t        | |      S )zHTry to convert a frame into an FX graph, if error leave frame unmodified)r  )rF  rm  s     rq   r%  r%  o  s    U++rp   c                H   ddl m} t        j                  }dt        _        t	        | d      5 }t        j                  |      }d d d        t        t        j                  j                  j                         t               j                                     |_
        	 t        |j                  |j                  |j                  |j                  |ddd t!               t#        dd      d d i t%        dd             |t        _        y # 1 sw Y   xY w# |t        _        w xY w)	Nr(   )eagerFrbr   *   i  )
rF  rG  r  rH  rm  rZ  rl  r   r\  rY  )backends.debuggingr8  r)   replay_record_enabledopenrH   loadr   r  chainr   itemsrk  r  r  r  rG   r3   r   )r  r8  original_replay_valin_filer  s        rq   replayrC  u  s    ) 66#(F 	h	 / %%g./)//&..*>*>*@')//BSTUFN;KKNNMMOO#'0A6 S)	
" (;$-/ /, (;$s   DAD DD!c                    t         j                  dk  ryt        j                  |       D ]"  }|j                  dk(  s|j
                  dz  c S  t        d      )N)      r   RESUMEr  z$RESUME instruction not found in code)sysversion_infodisget_instructionsopnameoffsetRuntimeError)r  insts     rq   first_real_inst_idxrP    sV    
'!$$T* $;;(";;!##$ =
>>rp   c                  0    e Zd Zdd	 	 	 	 	 	 	 	 	 	 	 ddZy)ConvertFrameProtocolr   rO  c                    y ru   ro   )rz   r   rl  rm  r\  rP  s         rq   ro  zConvertFrameProtocol.__call__  s     	rp   Nrr  )rl   rm   rn   ro  ro   rp   rq   rR  rR    sG     		 *	 		
 @	 	 
	rp   rR  c                  ,    e Zd ZddZ	 	 	 	 	 	 	 	 ddZy)CatchErrorsWrapperc                V     t        j                  |      |        || _        || _        y ru   )r   r   r   rm  )rz   callbackrm  s      rq   r{   zCatchErrorsWrapper.__init__  s$    !	!$'*2'
rp   c           	        |J t        j                  |j                        }t        j                  dk\  r#|j
                  t        |j                        kD  }n"|j
                  t        |j                        k\  }|s5|s3t        j                  s#t        d      rt        | j                  dd      st        j                  t        j                        rt!        |j
                  t        |j                               |rd}n3t        j                  |j                        rd}nt        d      rd}nd}t        j#                  d	|j                  j$                  ||j                  j&                         y |j                  j&                  d
k(  r|j                  j$                  dk(  ry t        j(                         dk(  rt+        j,                         }|rt.        5  ddlm}  ||j4                  | j                  j                        }	t7        | j                  d      sJ d       | j                  j9                  |	j:                        }
 |
||| j<                  |      cd d d        S t.        5  t?               5  | j                  ||| j<                  |d      cd d d        cd d d        S # 1 sw Y   MxY w# 1 sw Y   nxY wd d d        y # 1 sw Y   y xY w)N)rE     F)include_infra_modesrD  z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)rT  __new__ddp_optimizerr   )DDPOptimizer)bucket_bytes_capbackend_compile_fnrN  zJDDPOptimizer only supports callback fns that know how to clone themselves.r(   rO  ) r+   r   r   rH  rI  f_lastirP  r)   r#  r%   r   r   r   r  r  r  printr   r   r   _get_optimize_ddp_moder#   _get_active_ddp_modulecompile_lock"torch._dynamo.backends.distributedr]  r^  r   rN  
compile_fnrm  r$   )rz   r   rl  r\  is_skipfilehas_started_executionskip_reason
ddp_moduler]  r\  hijacked_callbacks              rq   ro  zCatchErrorsWrapper.__call__  sk    &&&!''5w&$)MM4G4U$U!$)MM5H5V$V! "~~)eD ? ?ER .emm%8%FG("8K &&u||4"0K.5I"wK">K		9LL((LL,,	 <<##z1ell6J6Ji6W((*o=0GGIJ! O$0)3)D)D+/+J+J+e+e%M #779N dcd  77KK)44 &
 -{DJJ &  	13 	22{DJJ! 3 	 	 	' &	 	 	 	 	s1   BJ13K> J=	K1J:=K	KKN)rW  rR  rm  rG   r   r   )r   r   rl  rs  r\  rt  r   ru  )rl   rm   rn   r{   ro  ro   rp   rq   rU  rU    s8    
HH *H @	H
 
Hrp   rU  c                    t        | |      S ru   )rU  )rW  rm  s     rq   catch_errors_wrapperrm    s     h..rp   ru   )r   r   r   zDict[str, Any]r   zOptional[Dict[str, str]]r   r   )r   Callable[_P, _T]r   rn  )r   r   r   r   )NF)
r  r  r  r   r   Optional[FrameType]r  r   r   r   )r  rn  r   rn  rp  )
rF  ra   rG  r   r  r   rH  rq  r   rA  )r~  rc   r   rz  )NN) r  r   r   r  r  r  r  r  rF  ra   rG  r   r  r   rH  rq  rm  rG   rl  rs  rZ  r3   r   ro  r\  z4Optional[Dict[str, Union[int, FrameStateSizeEntry]]]rY  r   rP  r   r   ru  )rF  ra   rm  rG   r   r  )r  r   r   r   r  )rW  rR  rm  rG   r   rU  )
__future__r   collectionsr   r  rJ  r   r  r  r_  r  r   r*  rH  	threadingr!  r-  typingr   pathlibr   typesr   r   r   r   r	   r
   r   r   r   r   r   r   typing_extensionsr   r   r   torch._loggingtorch._C._dynamo.guardsr   torch._dynamo.distributedr   torch._dynamo.utilsr   torch._guardsr   r   r   r   r   torch._utils_internalr   r   r   r   torch.fx._lazy_graph_moduler   %torch.fx.experimental.symbolic_shapesr    r!   torch.fx.graph_moduler"   r   torch.nn.parallel.distributedr#   torch.utils._python_dispatchr$   r%   torch.utils._tracebackr&   r'   r  r)   r*   r+   bytecode_analysisr,   r-   bytecode_transformationr.   r/   r0   r1   r2   rZ  r3   r4   r5   r6   r0  r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   r   rD   rE   rF   rm  rG   replay_recordrH   symbolic_convertrI   rJ   rK   rL   rM   r  rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   __annotations__numpyr`   ModuleNotFoundErrorTYPE_CHECKINGbackends.registryra   repro.after_dynamorb   rc   rd   variables.builderre   	getLoggerrl   r   r4  getArtifactLoggerr  r+  RLockrd  rh   ri   rk   rs   r]  r^  r   r   r   r   #suppress_torch_distributed_warningsr   r  rh  Counterr  r  r
  rA  rK  ry  torch.utils.hooksrz  output_graphr{  r|  r  rk  r  r%  rC  rP  ProtocolrR  rU  rm  ro   rp   rq   <module>r     s<   "    
    	    
       ? ? K K K ' !   4 4 = M M %  ? Q A M & & G   N M   
  *  "    ,  
 
-4/6 g!~~//*E..228^L y T]t_	 	 ( iy37 0 7 *+MQ	%2J ,8v 11K 2Kb "&	**
* * 	*
 
*  K   
>BA
 A
L 15	RRR R /	R
 R $ - 
) ,7=( 8, "&HLN?  !N?
N?N? N?  	N?
 N? N? N? /N? N? &N? *N? N? FN? N?  !N?" #N?bZ Zz,;<?
6?? 
N Nb/"/+0//E$  	Bs   M) )M43M4