
    '}h?                       U 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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 d dlm Z  d dlm!Z! d dlm"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 	 d dl5Z6	 d dl8Z9d dl:m;Z< d d	l=m>Z> d d
l8m?Z? ddl@mAZA e6re6e6j                  e6j                  e6j                  fZEe/ej                  df   eGd<   e6e<e6j                  e<j                  e6j                  e<j                  e6j                  e<j                  iZHn	 eI       ZEi ZHd dlJmKZKmLZLmMZM d dlOZOd dl9Z9d dlPZ9d dlQZ9d dl9mRZR d dlSmTZT d dlUmVZV d dlWmXZX d dlYmZZZ  ej                  ejL                        Z\e'e]e&e]   f   eGd<   i Z^e)e]e"f   eGd<   dZ_dZ`de` dZa ej                  ec      Zdi Zee)e]e,ef   f   eGd<   i Zge)e]e)e]eff   f   eGd<    ej                         aid Zjd Zkd Zld amd  Znd! Zod apd" Zqd# Zrdd$Zsdd'Zte j                  d(        Zve9j                  e9j                  e9j                  fe9j                  e9j                  e9j                  fe9j                  e9j                  e9j                  fe9j                  e9j                   fe9j                  e9j                  fe9j                  e9j                  fe9j
                  e9j                  e9j                  fe9j                  e9j                  e9j                  fe9j                  e9j                  e9j                  fe9j                  e9j                  fi
Z G d) d*      Z e       Zd+ Zd, Zd- Zd. Zd/ Zd0 Zd1eRj2                  fd2Zd3 Zd4 Zd5 Z G d6 d7      Zd8 Zd9 Zd: Zd; Zd< Zd= Zd> Zd? Zd@ ZdA ZdB Z e	j:                  dC      dD        ZddEZdF ZejZ                   G dG dH             ZdIZ ej`                  eJ      ae(e   eGdK<   dLefdMZdNedOdfdPZddQZdOe,e   fdRZejZ                   G dS dT             Z G dU dVe      Z e       e_        dW ZddXdYZdZ Zd[e9jx                  fd\Zed]        Zd^ Zdd_Zd` Zda Zdb Z e	j:                  d      dc        Zdd ZddeZdf Z edg      dh        Zeefeee]e ed      e̐j                  ej                  e9j                  e9j                  e9j                  e9j                  hZdi Zdj Zdk Zdl Zdm Zdn Z e eګ       j                               Ze0e+e"      eGdo<    e eګ       j                               Ze0e2e"      eGdp<    e ej                         j                               Ze0e2e"      eGdq<    e e eI                   Ze0e*e"      eGdr<   ej                  Zej                  Zds Zdt Zdu ZeZdv Zdw Zdx Zdy ZddzZd{ Zd| ZdOe]fd}ZdOe]fd~ZdZd dlmZ d Zd Zd Zdd&dd&dd&d&edj                  fdZd Zej8                  d        Z e       Z  ej                  e      Ze'e"e,e"   f   eGd<    e       Ze,d   eGd<    e       Z G d d      Z e	j:                  d      d        Zd ZddZd Z	d Z
ddZ ej                         Zd Zed        Zd Zd Zd Zde"fdZd Zdej                  fdZde"fdZde"fdZ G d dej0                        ZdefdZde1e9jx                  e"f   dedddOe/ee-e   f   fdZddZd Zd Zd ZddgZ ddgZ!g dZ"e e!z   e"z   Z#	 	 	 ddZ$	 	 	 ddZ%d Z&d Z' G d d      Z(d Z) G d d      Z* G d d      Z+d Z,d Z-d Z.d Z/d%e]dedOefdÄZ0ejZ                   G dĄ dū             Z1de]dOe-e1   fdǄZ2dej                  dejf                  dOe]fdʄZ4d˄ Z5d̄ Z6d̈́ Z7d΄ Z8dddOefdфZ9d҄ Z:dӄ Z;ej8                  dԄ        Z<dՄ Z=dք Z>y# e7$ r dZ6Y w xY w# eN$ r Y Ow xY w)    N)contextmanager)	lru_cachewraps)Path)MethodWrapperType)AnyCallablecastClassVarCounterDefaultDictDequeDictIteratorKeysViewListOptionalSetTupleTypeUnion
ValuesView   )RemovableHandle)detect_fake_mode
LazyString   )config.NP_SUPPORTED_MODULES)
FakeTensoris_fakemaybe_get_fake_mode)fx)enable_python_dispatcher)log_compilation_event)LazyModuleMixin)tree_map_onlycountersoptimus_scuba_logz<https://pytorch.org/docs/master/compile/troubleshooting.htmlz6https://pytorch.org/docs/master/compile/nn-module.htmlzSee z& for more information and limitations.compilation_time_metricsframe_phase_timingc                     	 dd l }|j                  | |      S # t        $ r0 dj                  d t        j                  |g|       D              cY S w xY w)Nr   headers
c              3   Z   K   | ]#  }d j                  t        t        |             % yw), N)joinmapstr).0rows     R/var/www/html/test/engine/venv/lib/python3.12/site-packages/torch/_dynamo/utils.py	<genexpr>ztabulate.<locals>.<genexpr>}   s$      
),DIIc#sm$
s   )+)tabulateImportErrorr3   	itertoolschain)rowsr/   r:   s      r8   r:   r:   w   sZ    
  w 77 
yy 
09	40P
 
 	

s    6AAc                 <    t         j                  rt        |       S | S N)r   cprofilecprofile_wrapper)funcs    r8   maybe_cprofilerD      s    %%K    c                 .     t                fd       }|S )Nc                      t        t              }t        j                  | dz         }t	        j
                         }|j                          t        j                         } |j                  g| i |}t        j                         |z
  }|j                          t        dj                   d| d|dd       t        j                  |      }|j                  |       |j                  d      }		 t        j                   dd	d
dddt#        |      gt        j$                        }
t        j&                  dddt#        |	      g|
j(                         t        dt#        |	              |S # t*        $ r t        d       |j-                  t        j.                  j0                        j3                  d       |j-                  t        j.                  j4                        j3                  d       Y |S w xY w)Nz.profilez### Cprofile for z iter z took z.3fz seconds ###z.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 zxFailed to generate SVG from profile -- dumping stats instead.Try installing gprof2dot and dot for a better visualization   )nexttimer_counterr   __name__cProfileProfileenabletimeruncalldisableprintrI   Stats
dump_statswith_suffix
subprocessPopenr5   PIPE
check_callrJ   FileNotFoundError
sort_statsSortKeyTIMEprint_stats
CUMULATIVE)argskwargsprofile_cntprofile_pathprofstart_tsretvalprofile_latencypssvg_pathgprof2dot_processrC   s              r8   profile_wrapperz)cprofile_wrapper.<locals>.profile_wrapper   s    =)DMM{m8,DDE!99;d4T4V4))+0f[MX[G\\hi	
 \\$%++F3	E * 0 087-% "! !!s8}5'.. 23x=/BC  ! 	EN MM&..--.::2>MM&..334@@D	Es   9A:E5 5BG=<G=)r   )rC   rp   s   ` r8   rB   rB      s"    
4[) )V rE   c                      t         dz   a y Nr   )
curr_frame rE   r8   increment_frameru      s    aJrE   c                  X    t         j                          t        j                          day Nr   )r,   clearr+   rs   rt   rE   r8   reset_frame_country      s    ""$JrE   c                     t         | z  a y r@   )op_count)cnts    r8   increment_op_countr}      s    OHrE   c            	         d} i }t         j                         D ]6  }|j                         D ]!  \  }}| |z  } ||vr|||<   ||xx   |z  cc<   # 8 d}|j                         D ]  \  }}| d| dt        |d       } t	        |       y )Ng        zTIMING: :   )r,   valuesitemsroundrW   )totaltotal_by_keytimingskeytimingoutvalues          r8   print_time_reportr      s    EL%,,. ,"==? 	,KCVOE,&$*S!S!V+!	,, C"((* /
UQse1U5!_-./ 
#JrE   c                 &    fd}| r ||       S |S )Nc                 V     t         j                  r S t                fd       }|S )Nc                     j                   }|t        vr	g t        |<   t        j                  j	                  | d      5  t        j
                         } | i |}t        j
                         |z
  }d d d        t        |   j                         rMt        t              }|t        vr	i t        |<   t        |   vr|t        |   <   S t        |   xx   |z  cc<   S # 1 sw Y   rxY w)Nz (dynamo_timed))
__qualname__r+   torchprofilerrecord_functionrT   appendr5   rs   r,   )	re   rf   r   t0r
time_spent	frame_keyrC   
phase_names	          r8   time_wrapperz>dynamo_timed.<locals>.dynamo_timed_inner.<locals>.time_wrapper   s    ##C2202(-//3%0GH .YY[$)&)!YY[2-
. %S)00<
O	$6646&y1%7	%BB@J&y1*= H 'y1*=K=H. .s   4C&&C/)r   rA   r   )rC   r   r   s   ` r8   dynamo_timed_innerz(dynamo_timed.<locals>.dynamo_timed_inner   s-    ??K	t	 
	& rE   rt   )original_functionr   r   s    ` r8   dynamo_timedr      s    4 !"344rE   r5   Fc                 F   d ffd	}| dk(  r9t         D cg c]  }| |t         |   d       f }}d}|t        |d      z  }|S | d	k(  rKt         j                         D cg c]  } ||d
        }}t        t         j	                               }||fS yc c}w c c}w )a  
    Get metrics about torchdynamo frontend/backend compilation times.

    Accumulates information from functions tagged with `@dynamo_timed`.

    repr='str' returns a printable string for user interaction, and 'csv'
    returns headers, rows which can be logged for output

    aggregate causes values from multiple compilations (e.g. split graphs)
    to be accumulated into one value.  If false, expect more than one value
    per metric.
    c                     | S r@   rt   xs    r8   <lambda>zcompile_times.<locals>.<lambda>(  s     rE   c                 `    r |t        |             S dj                  t        ||             S )Nr2   )sumr3   r4   )r   item_fn	aggregates     r8   fmt_fnzcompile_times.<locals>.fmt_fn(  s+    3v;''yyWf-..rE   r5   c                 
    | dS )Nz.4frt   r   s    r8   r   zcompile_times.<locals>.<lambda>/  s
    3 rE   )r   z!TorchDynamo compilation metrics:
)FunctionzRuntimes (s)r.   csvc                 
    | dS )Nz.6frt   r   s    r8   r   zcompile_times.<locals>.<lambda>7  s
    1S' rE   N)r+   r:   r   listkeys)	reprr   r   kr>   r   vr   r/   s	    `       r8   compile_timesr     s      + /
 u} .
 /2<PQR
 
 3x&BCC
	 .446
 123
 
 /4467 


s   B#Bc                  D    t         j                  t        dd             y )Nr5   T)r   r   )loginfor   rt   rE   r8   dump_compile_timesr   >  s    HH]67rE   c                        e Zd ZddZd Zd Zy)DuplicateWarningCheckerc                 2    || _         | j                          y r@   )maxsizereset)selfr   s     r8   __init__z DuplicateWarningChecker.__init__R  s    

rE   c                 6    t        j                         | _        y r@   )collectionsOrderedDictsetr   s    r8   r   zDuplicateWarningChecker.resetV  s    **,rE   c                 ^   || j                   v r/| j                   j                  |d       t        j                  syyd | j                   |<   t	        | j                         | j
                  kD  r?| j                   j                  d       t	        | j                         | j
                  kD  r?y)NT)lastF)r   move_to_endr   verboselenr   popitemr   r   s     r8   addzDuplicateWarningChecker.addY  s    $((?HH  4 0>>
  !DHHSMdhh-$,,.  e , dhh-$,,.rE   N)   )rP   
__module__r   r   r   r   rt   rE   r8   r   r   Q  s    -	rE   r   c                  "   t         j                  j                  dd      dk(  } | rWt        j                  j                  t        j                  t        j                  t        j                  d       t               S t        j                         S )NTORCH_COMPILE_DEBUG01T)dynamoaotinductoroutput_code)osenvirongetr   _loggingset_logsloggingDEBUGadd_file_handler
contextlib	ExitStack)compile_debugs    r8   setup_compile_debugr   h  sh    JJNN#8#>#EM==]]	 	  	
  !!!!rE   c                  ,    t         j                          y r@   )graph_break_dup_warning_checkerr   rt   rE   r8   reset_graph_break_dup_checkerr   w  s    #))+rE   c                     t         j                  j                  t               d      } t        j                  | d       t        j                  t         j                  j                  | d            t        j                  d      j                         t        j                         }|j                  fd       |S )NtorchdynamoTexist_okz	debug.logztorch._dynamoc                  &    j                         S r@   removeHandlerlog_file_handlerloggers   r8   r   z"add_file_handler.<locals>.<lambda>  s    v334DE rE   )r   pathr3   get_debug_dirmakedirsr   FileHandler	getLogger
addHandlerr   r   callback)log_path	exitstackr   r   s     @@r8   r   r   {  s    ww||MO];HKK4(**277<<++NO/F
&'$$&IEFrE   c                  B   t        j                         } t        j                  xt	        j
                  t        j                        t        j                  j                  j                         D ](  j                         | j                  fd       * | S | S )Nc                  &    j                         S r@   r   r   s   r8   r   z setup_log_file.<locals>.<lambda>  s    v';';<L'M rE   )r   r   r   log_file_namer   r   r   r   	_internalget_loggersr   r   )r   r   r   s    @@r8   setup_log_filer     s    $$&I'"..v/C/CDnn..::< 	OF./MN	O rE   c                 |    t                d|j                   dt        |       j                   d|j                   dS )Nz/error_recordings/_z.rec)r   co_nametyperP   co_firstlineno)exccodes     r8   gen_record_file_namer    sB    o aS	""#1T%8%8$9? ?rE   c                    	 t         j                  j                  |       rt        j	                  d|        y t        j
                  t         j                  j                  |       d       t        | d      5 }|j                  |       d d d        y # 1 sw Y   y xY w# t        $ r t        j                  d|        Y y w xY w)Nz9Unable to write execution record %s; file already exists.Tr   wbz#Unable to write execution record %s)r   r   existsr   warningr   dirnameopendump	Exception	exception)filenameexec_recordfs      r8   write_record_to_filer    s    
G77>>(#KKKX KK1DAh% $  #$ $ $ G;XFGs5   5B A B 8B
B BB B C Cgc                 T    d}| j                   D ]  }d|j                  v s|dz  } |S )Nr   callr   )nodesop)r  cns      r8   count_callsr    s5    	AWW QTT>FA HrE   c                     | S r@   rt   r   s    r8   identityr    s    HrE   c                 N    	 t        |        y# t        $ r Y yt        $ r Y yw xY w)NTF)hash	TypeError
ValueErrorr   s    r8   hashabler    s.    Q  s    	$$$c                       y r@   rt   re   rf   s     r8   nothingr"    s    rE   c                   <    e Zd ZdZd Zd Zd
dZd Zd Zd Z	d	 Z
y)ExactWeakKeyDictionaryz\Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equalityc                 @    t               | _        t               | _        y r@   )dictr   refsr   s    r8   r   zExactWeakKeyDictionary.__init__  s    fF	rE   c                 2    | j                   t        |         S r@   )r   idr   s     r8   __getitem__z"ExactWeakKeyDictionary.__getitem__  s    {{2c7##rE   Nc                 L    | j                   j                  t        |      |      S r@   )r   r   r)  )r   r   defaults      r8   r   zExactWeakKeyDictionary.get  s    {{r#w00rE   c                 0    t        |      | j                  v S r@   )r)  r   r   s     r8   __contains__z#ExactWeakKeyDictionary.__contains__  s    #w$++%%rE   c                      t        |       j                  vr't        j                  | fd       j                  <   | j                  <   y )Nc                 &    j                        S r@   )
_remove_id)refidxr   s    r8   r   z4ExactWeakKeyDictionary.__setitem__.<locals>.<lambda>  s    $//#:N rE   )r)  r'  weakrefr2  r   )r   r   r   r3  s   `  @r8   __setitem__z"ExactWeakKeyDictionary.__setitem__  s?    gdii$[[.NODIIcN CrE   c                 r    || j                   v r| j                   |= || j                  v r| j                  |= y y r@   )r   r'  )r   r3  s     r8   r1  z!ExactWeakKeyDictionary._remove_id  s6    $++C $))		# rE   c                 l    | j                   j                          | j                  j                          y r@   )r'  rx   r   r   s    r8   rx   zExactWeakKeyDictionary.clear  s     		rE   r@   )rP   r   r   __doc__r   r*  r   r.  r5  r1  rx   rt   rE   r8   r$  r$    s(    f$1&!rE   r$  c                 l    t        |t        t        t        f      rt	        |       |v S t	        |       |u S )zisinstance() without subclasses)
isinstancetupler   r   r   )objallowed_typess     r8   istyper>    s1    -%s!34CyM))9%%rE   c                 ^    t        | t        j                        xs | t        j                  u S r@   )r:  typing_FinalGenericr   s    r8   	is_typingrD    s#     eV]]+Fu/FFrE   c                    t         syt        | t         j                  t         j                  t         j                  t         j
                  t         j                  t         j                  t         j                  t         j                  f      S NF)
npr>  int8int16int32int64uint8uint16uint32uint64rC  s    r8   is_numpy_int_typerP    sU    GGHHHHHHHHIIIIII		
 rE   c                     t         syt        | t         j                  t         j                  t         j                  f      S rF  )rG  r>  float16float32float64rC  s    r8   is_numpy_float_typerU  	  s2    JJJJJJ	
 rE   c                    t        |       xs{ t        | t        j                        xr t        t	        j
                  | d            xs> t        | t        j                  j                  t        j                  j                  f      S )N__wrapped__)
is_functionr:  	functools_lru_cache_wrapperinspectgetattr_staticr   _opsOpOverloadPacket
OpOverloadrC  s    r8   is_function_or_wrapperr`    sk    E 	SeY99: F..umDE	S eejj995::;P;PQR	rE   c                     t        | t        j                  t        j                  t        j                  t        j
                  t        j                  j                  f      S r@   )	r:  typesFunctionTypeBuiltinFunctionTypeMethodDescriptorTypeWrapperDescriptorTyper   jitScriptFunctionrC  s    r8   rX  rX     sH    %%&&''II$$	
	 	rE   c                     t        |       d   S rw   ) unwrap_with_attr_name_if_wrapper)fns    r8   unwrap_if_wrapperrl  -  s    +B/22rE   c                 v   t        | t        j                        rt        j                  | d      } d}| |fS t        |       r4t        j                  | dd      rt        j                  | d|       } d}| |fS t        |       r4t        j                  | dd      rt        j                  | d|       } d}| |fS d }| |fS )NrW  _torchdynamo_inlineF__script_if_tracing_wrapper__original_fn)r:  rY  rZ  r[  r\  rX  )rk  	attr_names     r8   rj  rj  1  s    "i223##B6!	 y= 
RW33B8MuU##B(=rB)	 y= 
RW33
)5 ##B<#	 y= 	y=rE   c                 D    t         syt        | t         j                        S rF  )rG  r>  ndarrayrC  s    r8   is_numpy_ndarrayrt  E  s    %$$rE   c                     t         j                  t         j                  j                  gt        j
                  }|t         j                  j                  fz   }t        | |      S )zCheck of obj is a tensor)	r   Tensornn	Parameterr   traceable_tensor_subclasses_subclassesr!   r>  )r<  tensor_lists     r8   istensorr|  L  sW     	 
	+	+K
 !2!2!=!= ??K#{##rE   c                 "    t        | t              S r@   )r:  r'   )mods    r8   is_lazy_moduler  W  s    c?++rE   r   c                      t        |   y r@   )rW   )re   s    r8   
print_oncer  [  s	    	4LrE   c                 |    | fd}|j                   t        |j                         dk(  sJ |j                   d   S )zNSome black magic to create a cell object that usually only exists in a closurec                       S r@   rt   r   s   r8   r  zmake_cell.<locals>.fd  s    rE   r   r   )__closure__r   )valr  r   s     @r8   	make_cellr  `  s>    A ==$Q]]);q)@@@==rE   c                 0   	 t        d | D              }|j                         D ci c]  \  }}||j                          }}}||fS c c}}w # t        $ r=}ddlm} ddlm}  |d ||   d |t        |j                                       |d }~ww xY w)Nc              3   <   K   | ]  }|j                           y wr@   )as_proxyr6   args     r8   r9   z$proxy_args_kwargs.<locals>.<genexpr>m  s     :c3<<>:   r   unimplemented)typestrzcall_function args: r   )
r;  r   r  NotImplementedErrorr  r  variables.baser  r   r   )	re   rf   
proxy_argsr   r  proxy_kwargser  r  s	            r8   proxy_args_kwargsr  k  s    
:T::
<BLLNKSS\\^+KK<'' L &+"7D>"2!GT&--/=R4S3TU
		s(   %A A	A 	A 	B8BBc                   D   e Zd ZU eed<   eed<   eed<   eed<   eed<   eed<   ee   ed<   ee   ed<   ee   ed	<   ee   ed
<   ee   ed<   eed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   y)CompilationMetricsr   r   co_filenamer   
cache_sizeaccumulated_cache_sizeguard_countshape_env_guard_countgraph_op_countgraph_node_countgraph_input_count
start_timeentire_frame_compile_time_sbackend_compile_time_sinductor_compile_time_scode_gen_time_s	fail_typefail_reasonfail_user_frame_filenamefail_user_frame_linenonon_compliant_opscompliant_custom_opsN)	rP   r   r   r5   __annotations__intr   floatr   rt   rE   r8   r  r  y  s    NLO##C=(SM!sm#}$!)%0$UO+%e_,e_$}#&sm+$SM)3xc("rE   r  @   maxlen_compilation_metricscompilation_metricsc                 f    t         j                  |        t        j                  rt	        |        y y r@   )r  r   r   log_compilation_metricsr&   )r  s    r8   record_compilation_metricsr    s(     34%%12 &rE   new_sizereturnc                     t        t              | kD  r't        j                          t        t              | kD  r't        j                  t        |       }|ay )Nr  )r   r  popleftr   deque)r  	new_deques     r8   set_compilation_metrics_limitr    sE    
"
#h
.$$& "
#h
.!!"6xHI$rE   c                  ,    t         j                          y r@   )r  rx   rt   rE   r8   clear_compilation_metricsr    s     rE   c                       t        t              S r@   )r   r  rt   rE   r8   get_compilation_metricsr    s    $%%rE   c                   F    e Zd ZU dZeeef   ed<   eed<   d Ze	d        Z
y)CleanupHookz,Remove a global variable when hook is calledscopenamec                 d    t         xj                  dz  c_        | j                  | j                  = y rr   )CleanupManagercountr  r  )r   re   s     r8   __call__zCleanupHook.__call__  s#    !JJtyy!rE   c                 b    || vsJ t         xj                  dz  c_        || |<   t        | |      S rr   )r  r  r  )r  r  r  s      r8   createzCleanupHook.create  s7    5   !d5$''rE   N)rP   r   r   r8  r   r5   r   r  r  staticmethodr  rt   rE   r8   r  r    s1    6S>
I" ( (rE   r  c                   4     e Zd ZU dZed    ed<    fdZ xZS )r  r   instancec                 Z    | j                   |   D ]	  } |         t        | 	  |       y r@   )r   superr1  )r   r3  hook	__class__s      r8   r1  zCleanupManager._remove_id  s-    KK$ 	DF	3rE   )rP   r   r   r  r   r  r1  __classcell__)r  s   @r8   r  r    s    E'((   rE   r  c                     | j                         j                  | j                        }| j                  r+| j                  | j                  j                         |_        |S )z!Clone the tensor and its gradient)clonerequires_grad_requires_gradis_leafgrad)r   ys     r8   clone_tensorr    sB    		  1AyyQVV'HrE   dtypec          	      L   t        |       r| S fd}t        j                         5  | j                  j                  dk(  r ||       cddd       S t        d t        | j                         | j                               D              }| j                  rt        j                  |dz   f|       }n3t        j                  |dz   xs | j                  | j                        }| j                         |j                         z
  dz  | j                         z  }|j                  | j                         | j                         |       	 |j!                  | j#                                | j$                  r|j'                  | j(                         | j$                  r(| j*                  t-        | j*                        |_        t1        | d      r| j2                  j5                         |_        |cddd       S # t.        $ r  ||       cY cddd       S w xY w# 1 sw Y   yxY w)	zcopy while preserving stridesc                 >   t        j                  |       }| j                  r|j                  | j                         | j                  r(| j
                  t        | j
                        |_        t        | d      r| j                  j                         |_        |S )Nr  _dynamo_dynamic_indices)
r   r  r  r  r  r  clone_inputhasattrr  copy)r   r  r  s     r8   torch_clonez clone_input.<locals>.torch_clone  sr    KKN99Q__-99+ u5AF1/0()(A(A(F(F(HA%rE   xlaNc              3   2   K   | ]  \  }}|d z
  |z    yw)r   Nrt   )r6   shapestrides      r8   r9   zclone_input.<locals>.<genexpr>  s"      
%2UFUQY& 
       )r  devicer  r  )r"   r   no_gradr  r   r   zipsizer  is_quantizedempty_quantizedemptyr  data_ptrelement_sizeas_strided_copy_r  r  r  r  r  r  RuntimeErrorr  r  r  )r   r  r  needed_sizeresultcache_line_offsets    `    r8   r  r    s    qz 
 88==E!q> 
  
69!&&(AHHJ6O
 
 >>**K",<+>BF[[b (8F ZZ\FOO--3^^ 	1668QXXZ1BC
	"LL#yy%%aoo6yyQVV/)!&&> 1/0-.-F-F-K-K-MF*? 0  	" q>!9 0	"1 s7   !HC6H
A:G:,H:HHHHH#c                    t        |       t        u r|t        |       }|j                         D ]\  \  }}t        |t              rt        |      ||<   %t        |t        j                        sJ t        |             t        |      ||<   ^ |S t        |       }t        t        |            D ]1  }t        ||   t        j                        s!t        ||         ||<   3 |S r@   )r   r&  r   r:  r;  clone_inputsr   rv  r  r   ranger   )example_inputsresr   r   is        r8   r  r    s    Nt#>"))+ 	.JC%''.C!%6CUC6&u-C	. 

~
C3s8_ )c!fell+ Q(CF) JrE   r  c                     	 | j                          y # t        $ r7}ddlm} t	        j
                  ddt        |             } |d|       |d }~ww xY w)Nr   )	SkipFramez\(.* z(torch.compile cannot be run in context: )r  r  r  r   resubr   )r  r  r   functorch_subclass_names       r8   skip_frame_if_in_functorch_moder  !  sX    	 " #%&&"d3i"@67N6OP
	s    	A2AAc               #     K   t         j                  j                  } t         j                  j                  j
                  } |       5   |        5  t        j                  t         j                  j                               }t        |       t         j                  j                         r1t        j                  t         j                  j                               }d d d        d d d        	 d  t         j                  j                  j                         5  t         j                  j                         t         j                  j                         rt         j                  j                         d d d        y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w# t         j                  j                  j                         5  t         j                  j                         t         j                  j                         rt         j                  j                         d d d        w # 1 sw Y   w xY wxY wwr@   )r   _C_DisableFuncTorchutils_python_dispatch_disable_current_modesr  randomget_rng_stater  cudais_availableset_rng_state)disable_functorchdisable_current_modes	rng_statecuda_rng_states       r8   preserve_rng_stater  .  s    22!KK88OO		  E"3"5 EKK : : <=	'	2::""$"[[)A)A)CDN	E E
9[[))@@B 	9LL&&y1zz&&(

((8	9 	9E E E E	9 	9U[[))@@B 	9LL&&y1zz&&(

((8	9 	9 	9s   AIFBE?F$I-F# 1(IAF6	I?F	FFIF I#)H>AH2)	H>2H;7H>>Ic                 
   t        | t        j                  j                  j                  t        j                  j
                  j                  t        j                  j                  t        j                  j                  f      S r@   )	r:  r   rg  _traceTopLevelTracedModule_scriptRecursiveScriptModulerh  ScriptModule)model0s    r8   is_jit_modelr  @  sW    II11II33II$$II""		
 rE   c                 6   t        |       r| S 	 t        j                  j                  | |      S # t        $ r` 	 t        j                  j                  |       cY S # t        $ r1 |rt        j                  d       nt        j                  d       Y Y y w xY ww xY w)Nz	jit errorz0Both torch.jit.trace and torch.jit.script failed)	r  r   rg  tracer  scriptr   r  error)modelr  r   s      r8   torchscriptr#  L  s    E	Nyyun55 N	N99##E** 	Nk*		LM	NNs,   / 	BAB6BBBBc                 X    	 t        j                  |       S # t        t        f$ r Y y w xY wr@   )r[  getfiler  OSErrorr<  s    r8   r%  r%  ^  s-    s##w s    ))c                 *    t        t        |             S )LTest if an object is a namedtuple or a torch.return_types.* quasi-namedtuple)is_namedtuple_clsr   r'  s    r8   is_namedtupler+  e  s    T#Y''rE   c                     	 t        | t              rMt        | dg       xs dg}t        | dd      }|dk(  xs' |d   t        u xr t        | d      xr t        | d      S 	 y# t        $ r Y yw xY w)	r)  	__bases__Nr   torch.return_typesr   _make_fieldsF)
issubclassr;  getattrr  r  )clsbasesmodules      r8   r*  r*  j  s    c5!Cb1;dVES,5F11 aE!Wgc7&;WY@W "   s   AA! !	A-,A-c                    | t         u rg dS t        | t              sJ t        | d      r| j                  S t
        j                   G d d             }| j                  dk(  sJ  | t        |t        | j                                    }dg| j                  z  }t        |      D ];  }|d   dk7  st        t        ||      |      s#||t        ||      j                  <   = |S )	zIGet the fields of a namedtuple or a torch.return_types.* quasi-namedtuple)startstopstepr0  c                       e Zd ZU eed<   y)!namedtuple_fields.<locals>.MarkerindexNrP   r   r   r  r  rt   rE   r8   Markerr;    s    
rE   r>  r.  Nr   r   )slicer1  r;  r  r0  dataclasses	dataclassr   r4   r  n_fieldsdirr:  r2  r<  )r3  r>  r<  fieldsr  s        r8   namedtuple_fieldsrE  x  s     e|((c5!!!sI{{   >>1111
c&%-.
/C#'&3<<"7FC 47c>jd);VD/3F73%++,4 MrE   c           	      B   t        j                         5  t        j                  t         j                  j	                               t         j
                  j                         r1t        j                  t         j
                  j	                               g t        j                  | j                         | j                               D ]3  }j                  ||j                  t        j                  |      f       5 	 d d d        fd}|S # 1 sw Y   xY w)Nc                  j   t        j                         5  t         j                  j                         t         j                  j                         rt         j                  j                         D ]'  \  } }}| j                  |k7  s| j                  |       ) 	 d d d        y # 1 sw Y   y xY wr@   )r   r  r  r  r  r  _versionr  )paramversionoriginal_valuer  r  saved_states      r8   restorez"checkpoint_params.<locals>.restore  s    ]]_ 	0LL&&y1zz&&(

((82= 0.w>>W,KK/0		0 	0 	0s   A5B)B))B2)r   r  r  r  r  r  r  r<   r=   
parametersbuffersr   rH  )gmrI  rM  r  r  rL  s      @@@r8   checkpoint_paramsrQ    s    	 LKK : : <=	::""$"[[)A)A)CDN__R]]_bjjlC 	LEu~~u{{57IJK	LL0 N#L Ls   C+DDc                 v   t         j                  j                         rt         j                  j                  }nt        } |        t        j                          t        j                  d       t        j                         }t        |      D ]  } | | } |         t        j                         }||z
  fS )Ni9  )r   r  r  synchronizer"  gccollectmanual_seedrT   perf_counterr  )r"  r  timesrS  r   r   r  t1s           r8   timedrZ    s    zz jj,,MJJL	d				B5\ ' 
			B27?rE   c           	      l    t        d t        j                  || j                  d            D              S )Nc              3   4   K   | ]  }|j                     y wr@   )is_cudar6   r   s     r8   r9   z check_is_cuda.<locals>.<genexpr>  s     WQqyyWs   T)allr<   r=   rN  )rP  r  s     r8   check_is_cudar`    s(    W)//."--PTBU"VWWWrE   r  c                     | dkD  sJ t        |       D cg c]  }d| 	 }}t        |dd  |d d z         }t        ddj                  |       ddj                  |       d      }d|  d	|_        |S c c}w )
Nr   r   zlambda ,z: ()rot__helper)r  reversedevalr3   rP   )r  r  varsrotatedrk  s        r8   rot_n_helperrk    s    q5L5"1X&asG&D&tBCy49,-G	's388G+<*=Q?	@B7#BKI	 's   A4c                     t        | t        t        f      rt        t	        t
        |             S t        | t        j                  t        f      xs t        | t        t        hz        S r@   )r>  r;  	frozensetr_  r4   is_safe_constantr:  enumEnumr   common_constant_typesr?  )r   s    r8   rn  rn    sU    a%#$3'+,,a$))T*+ v	'0 rE   c                 l    ddl m}m} t        | |      r|j	                  | j                               S | S )Nr   )ConstantVariableSymNodeVariable)	variablesrs  rt  r:  r  evaluate_expr)r  rs  rt  s      r8   specialize_symnoderw    s0    < #'&&s'8'8':;;JrE   c                 `    ddl m} t        |       } t        | |      r| j	                         S | S )Nr   rs  )ru  rs  rw  r:  as_python_constant)r  rs  s     r8   guard_if_dynr{    s.    +
S
!C#'(%%''JrE   c                 j    t        d t        j                  | |j                               D              S )Nc              3   <   K   | ]  }|j                           y wr@   )is_python_constantr^  s     r8   r9   z&check_constant_args.<locals>.<genexpr>  s     V!q##%Vr  )r_  r<   r=   r   r!  s     r8   check_constant_argsr    s$    VytV]]_/UVVVrE   c                     ddl m} ddlm} d}t	        j
                  | |j                               D ]$  }t        ||      r|dz  }t        |||f      s y& |dkD  S )Nr   ry  )UnspecializedPythonVariabler   F)variables.constantrs  variables.tensorr  r<   r=   r   r:  )re   rf   rs  r  unspec_countr   s         r8   check_unspec_python_argsr    sf    4=L__T6==?3 a45ALA ;=MNO !rE   c                 |    ddl m t        fdt        j                  | |j                               D              S )Nr   )NumpyNdarrayVariablec              3   6   K   | ]  }t        |        y wr@   )r:  )r6   r   r  s     r8   r9   z+check_numpy_ndarray_args.<locals>.<genexpr>  s!       	1*+s   )r  r  anyr<   r=   r   )re   rf   r  s     @r8   check_numpy_ndarray_argsr    s1    6 v}}7  rE   	dict_keysdict_valuesodict_valuestuple_iteratorc                 n    t        |       }t        j                  j                  j	                  |       |S r@   )
object_newr   rw  Moduler   )r3  r<  s     r8   nn_module_newr    s&    
S/C	HHOOS!JrE   c                 L    t        j                  t        j                  | d      S rr   )rY  reduceoperatormul)its    r8   productr    s    HLL"a00rE   c                 >    | j                         \  }\  }}|||z      S r@   )
__reduce__)r  r<  r   r<  r7  s        r8   tuple_iterator_getitemr  #  s%    }}Avuuu}rE   c                 $    | j                  |      S r@   )as_subclass)tr3  s     r8   to_subclassr  +  s    ==rE   c                 Z    t        t        j                  t        |       ||dz               S rr   )rN   r<   isliceiter)dr  s     r8   dict_keys_getitemr  /  s$    	  a!QU344rE   c                 j    | j                   j                  }| j                  }|rdnd}| d| d| }|S )NLGz["z"].)r  rP   r  )r   localr  r  r  
local_names         r8   	enum_reprr  3  sA     ??##D
**CCcE7"TF#cU+JrE   c                     | j                         j                  j                  j                  d      }t	        |      sddlm}  |d       |S )Nexample_valuer   r  z:Cannot check Tensor object identity without its fake value)r  nodemetar   r"   r  r  )vtfake_tensorr  s      r8   _get_fake_tensorr  =  s>    ++-$$))--o>K;&RSrE   c                 
   ddl m}m}m}m} j                         r%t        fd| D              }|j                  |      S d}	|rt        |      rd}	t              d }
| D ]  }|	r.t        ||      st        |      u s |j                  d      c S  |t        j                        j                  ||gi       }|
|}
a |t        j                        j                  |||
gi       }
 |
|j                  d      }
|
S )Nr   )BuiltinVariablers  TensorVariableVariableTrackerc              3      K   | ]7  }|j                         xr! |j                         j                         k(   9 y wr@   )r~  rz  )r6   r   searchs     r8   r9   z iter_contains.<locals>.<genexpr>O  sJ      
    " F$$&&*C*C*EEF
   =A FT)ru  r  rs  r  r  r~  r  r  r:  r  r  eqcall_functionor_)r   r  txcheck_tensor_identityr  rs  r  r  found_constmust_check_tensor_idfoundr   checks    `           r8   iter_containsr  F  s       " 
 
 

  &&{33 FN!C#!&)'+E !^,-a00+22488#HKK0>>rAv;PRSE}'5CC } ''.LrE   c                 t    t        | t        j                  t        j                  j                  t
        f      S )z4Returns whether it indexes dictionaries using its id)r:  r   rv  rw  r  r   )r   s    r8   	key_is_idr  o  s#    a%,,9JKLLrE   c                 t    | j                         D cg c]  }t        |      rt        |      n| c}S c c}w r@   )r   r  r)  )r   r   s     r8   	key_to_idr  t  s+    27**,?QYq\BqEq(???s   5c                   ddl m} t        | t        t        f      r\dj                  fd| D              }t        | t              rd| dS t        | t              sJ t        |       dk(  rd| dS d| d	S t        | t        j                        rt        | 
      j                  dd      S  ||       r| j                  S t        | t              rd } ||       S | S )Nr   )is_builtin_callablerc  c              3   8   K   | ]  }t        |         ywr  N
const_reprr6   sr  s     r8   r9   zconst_repr.<locals>.<genexpr>|  s     DQj%88D   [](z,)rd  r  'r  c                 x    | j                   }|j                  }|dk(  r|j                  S |dz   |j                  z   S )Nbuiltins.)r  r   r   )oklassr5  s      r8   fullnamezconst_repr.<locals>.fullname  s?    KKE%%F#)))C<%"4"444rE   )trace_rulesr  r:  r   r;  r3   r   ro  rp  r  replacerP   r   )r   r  r  
elems_reprr  s    `   r8   r  r  x  s    0!dE]#XXD!DD
azl!$$a'''1v{:,b)):,a((	Atyy	! %(00b99	Q	zz	At		5 {rE   c                H    dj                  fd| D              }d|z   dz   S )Nrc  c              3   8   K   | ]  }t        |         ywr  r  r  s     r8   r9   z!dict_keys_repr.<locals>.<genexpr>  s     Gq
1E22Gr  r  r  )r3   )
const_keysr  keys_strs    ` r8   dict_keys_reprr    s&    xxGJGGH>CrE   
__dict_key)UnsupportedFakeTensorExceptionc                     	  |        S # t         $ r9}ddlm} d|j                   d}t        j                  |        ||      |d }~ww xY w)Nr   r  zUnsupported: z with fake tensor propagation.)r  r  r  reasonr   r  )rk  r  r  msgs       r8   wrap_fake_exceptionr    sM    (t) (&ahhZ'EFCC a'(s   	 	A4AAc                      t         j                  j                  j                  |      5  t	         fd      cd d d        S # 1 sw Y   y xY w)Nc                  .    t        j                         S r@   )r  deepcopyr'  s   r8   r   z)deepcopy_to_fake_tensor.<locals>.<lambda>  s    4==+= rE   )r   rz  r  FakeCopyModer  )r<  	fake_modes   ` r8   deepcopy_to_fake_tensorr    s;    				&	&	3	3I	> ?"#=>? ? ?s   AAc                 ~    t        j                  t        j                  t        j                  | |z
                    S )z+
    Calculate root mean squared error
    )r   sqrtmeansquare)r2  r  s     r8   rmser    s)     ::ejjcCi!89::rE   g-C6?Tc
                    	  t         t        t        t        j                  j
                  t        j                  f      rt        t        t        f      sJ dt                dt                      t               t              k7  r	 	d       yt               t              k(  xr% t        	fdt               D              S t         t              rt        t              sJ t         j                               t        j                               k(  s;J dt         j                                dt        j                                       t         j                               D ]+  }
t         |
   |
   |
   		
      r" 	d
|
        y yt         t        j                   t"        f      rt         t        j$                  j&                        rJ t        t        j$                  j&                        rJ d fd fD        \    j(                  r.j(                  sJ  j+                          j+                         t        t        j                         sJ dt                dt                      r j,                  j,                  k7  r 	d j,                  j,                         y j,                  t        j.                  k(  reryt        j0                   j3                  t        j4                        j3                  t        j4                              }|s 	d       |S r j7                         j3                  t        j8                         j7                         j3                  t        j8                        t        j0                   d      ryt        j                  j:                  j=                   dd      }|dk  r@t>        jA                  d|jC                         jE                         jG                                |dk\  S s j3                  j,                         t        j0                         ryj,                  t        jH                  k(  rtK               jG                         }tM        jN                  |      rt>        jA                  d       tK              jG                         }j,                  t        jP                  k(  rdnd}jS                         dk  s; jT                  dk(  r' jV                  d    jV                  d   cxk(  rdk(  sn dk\  rd}|||z  d z  z   k  }|s 	d!||jY                                |S ry 	d"       yt         tZ        t\        t        d      t.        t        j^                  f      r ry k(  }|s 	d#t                       |S ta               stc               rSr&ta              stc              s jG                          t               t              u xr  k(  }|s
 	d$        |S te               rSt               t              u xr; t        t        jf                         t        jf                        		
      S t               jh                  d%v rMt               t              u sJ t        	 f
d& jj                  j                         D              S tm        d't               jh                         )(z-Check correctness to see if ref and res matchNztype mismatch r   zLength mismatchFc              3   P   K   | ]  \  }}}t        |||
	 
        yw))	log_errorN)same)r6   aibi	fp64_reficos_similarity	equal_nanexact_dtypeignore_non_fpr  relax_numpy_equalitytols       r8   r9   zsame.<locals>.<genexpr>  sI      ,
 "B	 $# ,
s   #&zkeys mismatch z == r  r   r  r  r  r  r  zAccuracy failed for key name %sTc                 d    t        | t        j                        r| S t        j                  |       S r@   )r:  r   rv  tensorr  s    r8   	to_tensorzsame.<locals>.to_tensor  s"    "1ell31HaHrE   c              3   .   K   | ]  } |        y wr@   rt   )r6   r  r  s     r8   r9   zsame.<locals>.<genexpr>  s     MinMs   zdtype mismatch %s, %sr  )atolrtolr  z+Accuracy failed: uint8 tensor did not matchr   gư>)dimepsgGz?zSimilarity score=%sz=Found nan in reference. Consider running in higher precision.g      @g       @i     rb  r   g{Gz?g      $@z4RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%sz+Accuracy failed: allclose not within tol=%szAccuracy failed (%s): %s != %sz!Accuracy failed (numpy): %s != %s)MaskedLMOutputSeq2SeqLMOutput!CausalLMOutputWithCrossAttentionsLongformerMaskedLMOutput	InstancesSquashedNormalBoxesNormalTanhTransformFooVariablec              3      
K   | ]7  }t        t        |      t        
|      t        |      	 
       9 yw)r  N)r  r2  )r6   r   r  r  r  fp64_refr  r  r2  r  r  r   s     r8   r9   zsame.<locals>.<genexpr>  sX      
  S!S!#&-#'%9+# 
r  zunsupported type: )7r:  r   r;  r   rw  ParameterListSizer   r   r_  r  r&  r   r   sortedr  rv  r  rz  r!   	is_sparseto_denser  boolallclosetorL  flattenrS  
functionalcosine_similarityr   r  cpudetachitemrT  r  mathisnanbfloat16numelndimr  r  r5   r  r  rP  rU  rt  	as_tensorrP   __dict__r  )r2  r  r  r  r   r  r  r  r  r  r   r   score	ref_error	res_error
multiplierpasses_testr  s   ``````````       @r8   r  r    sD    #eUXX%;%;UZZHI#e}-WS	{!DQTI;/WW-s8s3x'(3x3s8# 
 ,
 ,
 &)c8%<,
 )
 	
 
C	#t$$$388:#HHJ#
 
 	CC
O,DSXXZ0AB	C 
 
# 	AFFQK#1' +)="/' ;Q?!	" 	C%,,.	/c5#4#4#?#?@@@c5#4#4#?#?@@@	I Nc88LMS(==== =,,.C,,.C#u||,VtCyk4PS9+.VV,yyCII%1399ciiHyyEJJ& NNFFF-FFF-' KL++-""5==1C++-""5==1C~~c3SsdK HH''99#st9TEt|1599;3E3E3G3L3L3NOD= ffSYY' ~~c3SsiP ~~. 3/446	::i(KKW !3/446	 %(II$?SS
 NN$t+A#))B-399R=*MA*Mh
 "%J'J,BS4Z,OP"N!!
	 #"CSI	C#sDJellC	D3J6S	3L	3	#6s#;c"&9#&>((*C#Y$s)#5#*93D	#	S	T#Y& 
DOOC OOC )#!5'-
 	
 
c		   
 CyDI%%% 
 
 ||((*
 
 	
  /S	0B0B/CDEErE   c                 ~    | j                   j                  d      d   }d| j                   d| d| j                   dS )N/rb  r  z' (r   rd  )r  splitr   r   )r  short_filenames     r8   format_func_infor8    sD    %%++C04Nt||nC/q1D1D0EQGGrE   c               #     K   t         j                  } t        j                  t         _        t         j                  }t        j                  t         _        	 d  | t         _        |t         _        y # | t         _        |t         _        w xY wwr@   )r   cache_size_limitsysr   accumulated_cache_size_limit)priorprior_acc_limits     r8   disable_cache_limitr?    s_     ##E!kkF99O*-++F'>"'.=+ #(.=+s   ABA1 B1B		Bguard_failuresz-torch._dynamo.output_graph.GraphCompileReasongraph_break_reasonsc                   b    e Zd ZdZd Zdej                  j                  fdZd Z	d Z
d Zd Zy	)
CompileProfilerzUtility for profiling how and what dynamo would compile.

    Can be used for
     * diagnosing recompilation issues
     * determining an appropriate compile cache limit
     * (TODO)confirming which functions got compiled/skipped
    c                 6    d| _         d| _        t        | _        y rw   )frame_countr{   r?  backend_ctx_ctorr   s    r8   r   zCompileProfiler.__init__  s     3rE   rP  c                     | xj                   dz  c_         |j                  j                  D ]&  }d|j                  v s| xj                  dz  c_        ( |j
                  S )Nr   r  )rE  graphr  r  r{   forward)r   rP  r  r  s       r8   r  zCompileProfiler.__call__  sP    AHHNN 	#D "	# zzrE   c                     | S r@   rt   r   s    r8   	__enter__zCompileProfiler.__enter__  s    rE   c                      y r@   rt   )r   typr  	tracebacks       r8   __exit__zCompileProfiler.__exit__  s    rE   c                     dt         iS )Nr@  )r@  r   s    r8   get_metricszCompileProfiler.get_metrics  s     .11rE   c                 J  	 | j                         }|d   fdfd}D cg c]  }t        |       |       ||      g c}	d }	fd}t        j                  d      }| |       xs dz  }|t        j                  d      z  }| |       xs d	z  }|S c c}w )
Nr@  c                      t        |          S r@   r   )r  gfs    r8   num_recompilesz.CompileProfiler.report.<locals>.num_recompiles  s    r$x= rE   c                 d    dj                  |    D cg c]  }t        |       c}      S c c}w )Nr0   )r3   r5   )r  r   rU  s     r8   recompile_reasonsz1CompileProfiler.report.<locals>.recompile_reasons  s(    99bh7c!f7887s   -c                  t    dt         v r+t         d   } t        | D cg c]	  }|| |   g c}ddg      S y c c}w )Ngraph_breakzGraph Break ReasonCountr.   )r)   r:   )graph_breaksr  s     r8   graph_break_reportz2CompileProfiler.report.<locals>.graph_break_report  sL    ('69EF#c<,-F17;  ) Gs   5c                      t              rJt        D  cg c]
  }  |        c}       }t        g d      }|t        j                  d| d      z   S y c c} w )N)r   
RecompileszRecompile Reasonsr.   zC

                    Set torch._dynamo.config.cache_size_limit to z/ to avoid being cache limited.
                )r   maxr:   textwrapdedent)r  max_recompilesrecomp_tablerU  rV  summarized_gfs      r8   recompilation_reportz4CompileProfiler.report.<locals>.recompilation_report  sm    2w!$r%JtnT&:%J!K'!K  $hooBBPAQ R'   %Js   Aa  
            Torchdynamo Profiler Report
            ===========================

            Graph Breaks
            ------------
            Graph breaks happen when torchdynamo encounters code it can't safely trace.
            If you want to find out why breaks are happening, check below for each break reason
            You may gain additional insight by passing `fullgraph=True` to torch.compile,
            to stop at the first break.

        zNo graph breaks detected.a+  

            Recompilation
            -------------
            These subgraphs were recompiled more than once due to guard failures
            Guard failures indicate some condition assumed to be static by the tracer changed,
            making it unsafe to reuse the compiled program.

        zNo recompilation detected.
)rQ  r8  ra  rb  )
r   metricsrX  r  r]  rf  reportrU  rV  re  s
          @@@r8   rh  zCompileProfiler.report  s    ""$%&	!	9
 
 d#^D%9;LT;RS

		 
 	$&E*EE(//

 
	
 	&(J,JJm
s   !B N)rP   r   r   r8  r   r   r$   GraphModuler  rK  rO  rQ  rh  rt   rE   r8   rC  rC    s7    4
588// 2@rE   rC  c                     dt         j                   j                         j                  d      z   dz   t        t	        j
                               z   }t        j                  j                  | |      S )Nrun_z%Y_%m_%d_%H_%M_%S_%fz-pid_)datetimenowstrftimer5   r   getpidr   r3   )root_dirdir_names     r8   _get_debug_dirrr    sf     	





!
*
*+A
B	C 	 biik
		  77<<(++rE   c                  8    t         j                  } t        |       S r@   )r   debug_dir_rootrr  )
debug_roots    r8   r   r   $  s    &&J*%%rE   c                     d| j                   v r't        | j                   d         r| j                   d   S |rddlm}  |d       y y )Nr  r   r  z9`FakeTensor` example value was required but not available)r  r"   torch._dynamo.excr  )r  requiredr  s      r8   extract_fake_example_valuery  )  s?    $))#		/0J(Kyy))	3QRrE   c                 8    t        |       |j                  u sJ | S r@   )r#   r  )r  r  s     r8   ensure_graph_faker{  4  s    q!R\\111HrE   c                      dt         j                  j                  f fd}t         j                  j                  j	                  ||      S )Nr  c                     | j                   dk(  rd| j                  vrt        |       S | j                  d   }s&t        |t        j
                        rt        |      S |S )Nr  r  )r  r  get_fake_valuer:  r   rv  r{  )r  r   allow_non_graph_faker  s     r8   visitz)get_fake_values_from_nodes.<locals>.visit:  s\    44?"aff'D "!R)=>>ff_%#
3(E$S"--
rE   )r   r$   Noder  map_arg)r  r  r  r  s   ` ` r8   get_fake_values_from_nodesr  9  s4    	 	 88==  ..rE   c           	      $    ddl m} ddlm}m}m}m}m}  j                  }	d j                  v r't         j                  d         r j                  d   S t         j                   j                  f|      \  d|	dk(  r^t              dkD  rPt        d   t         j"                  j$                        r)t'        d   j(                        ft+        dd       z   |	dk(  rbj,                  j.                   j0                     t3              rt5        d	      rj7                         t'        j(                        	 j(                  5  t9               5  t;         fd
      }
ddd       ddd       |s4tk        t         jl                  to        jp                  tr              
      }
S # 1 sw Y   IxY w# 1 sw Y   MxY w# |$ r  t<        $ r(}|}|j>                  |j>                  }t        |t         j@                  jB                  jD                        r |d|jF                   d       nt        |t         j@                  jB                  jH                        r |d|jF                   d       nRt        |t         j@                  jB                  jJ                        r|jF                  }	d}t        |	t         jL                  jN                        r[t         jP                  jS                  |	jT                  jV                  |	jT                  jX                        }||\  }}d| d| d| d} |d|jF                   d| d       n}t        |t         jZ                  j\                  j^                  j`                        r ||jb                  d| d      t        ||      r! ||jb                  |j                  d         | |te        |            jg                  |jh                        dd}~ww xY w)az  
    Run the computation represented by `node` using fake tensors and return the result.

    allow_non_graph_fake: whether to allow the return result to be:
        1. non-fake or 2. fake that is not created by this instance of Dynamo.
        If `True`, you must be prepared to deal with such return values, ideally
        by further wrapping them as this graph's fakes.
    r   )ValueRangeErrorr   )TorchRuntimeErrorr  Unsupported	UserErrorUserErrorTyper  Ncall_methodcall_module_initialize_hookc                  6    t        j                         S r@   )run_nodeoutput)re   rf   nnmoduler  r  s   r8   r   z get_fake_value.<locals>.<lambda>y  s    D$I rE   zdata dependent operator: zC; to enable, set torch._dynamo.config.capture_scalar_outputs = Truezdynamic shape operator: zM; to enable, set torch._dynamo.config.capture_dynamic_output_shape_ops = Truer  z:It's possible that the support was implemented in module `z` and you may need to `import z`(z), otherwise zunsupported operator: z (z~see https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0 for how to fix)a  Tried to use data-dependent value in the subsequent computation. This can happen when we encounter unbounded dynamic value that is unknown during tracing time.  You will need to explicitly give hint to the compiler. Please take a look at constrain_as_value OR constrain_as_size APIs.  constrain_as_size_example)	case_name)r  ):torch.utils._sympy.value_rangesr  r  r  r  r  r  r  r  r  r"   r  re   rf   r   r:  r   rw  r  r  r  r;  r  
nn_modulestargetr  r  _infer_parametersr%   r  r  	__cause__rz  r  DataDependentOutputExceptionrC   DynamicOutputShapeExceptionUnsupportedOperatorExceptionr]  r_  r  _dispatch_pystub_schemar  overload_namer$   experimentalsymbolic_shapesGuardOnDataDependentSymNodeCONSTRAINT_VIOLATIONr5   with_traceback__traceback__r(   rv  rY  partialr{  )r  r  r  r  r  r  r  r  r  r  ret_valr  causeimport_suggestionmaybe_pystubr5  ctxr   re   rf   r  s   ``                @@@r8   r~  r~  H  s    @  
B $))#		/0J(Kyy))-
TYY$&:LD& H	]s4y1}DGUXX__1U'Q>@5ab?R	]99''4(#:L(M
 &&x6 +8R\\B<R\\ 	35 	)IG	 	z  LL)++,="Ew
 NC	 	 	 	   5R ;;"KKE5$$00MM
 +EJJ< 8T T 5$$00LL
 *5::, 7^ ^ 5$$00MM
 B ""ejj334$xx88JJOORZZ%=%=   +".KFC##)(*H Q5/ &
 (B7H6I J# #
 588((88TT
 22B CHJ 6  /M>>q	JPQQA'66qGTQk5RsI   G G%G 8G G  G		GGG P'H#P

Pc                  $    t        t        dd       S )Nr   )r2  _current_nodert   rE   r8   get_current_noder    s    ='400rE   c              #   v   K   t               }| t        _        	 d  |t        _        y # |t        _        w xY wwr@   )r  r  r   )r  olds     r8   set_current_noder    s.     

CM"!cs   9) 969c                    j                   t              5  fd}	 dk(  r j                  i cddd       S dk(  r+ t        d   j                        dd i cddd       S dk(  r|J  |i cddd       S dk(  r$| j	                  j                        cddd       S d	k(  r(d
j
                  v sJ j
                  d
   cddd       S 	 ddd       t              # t        t        f$ r}ddlm	}  | ||            |d}~wt        $ r0}t         ||            j                  |j                        |d}~ww xY w# 1 sw Y   t              xY w)a  
    Runs a given node, with the given args and kwargs.

    Behavior is dictated by a node's op.

    run_node is useful for extracting real values out of nodes.
    See get_real_value for more info on common usage.

    Note: The tracer arg is only used for 'get_attr' ops
    Note: The nnmodule arg is only used for 'call_module' ops

    Nodes that are not call_function, call_method, call_module, or get_attr will
    raise an AssertionError.
    c           	      N    d dj                    d d d	t        |       z   S )NzFailed running r   z(*z, **z):
)r  r5   )r  re   rf   r  r  s    r8   make_error_messagez$run_node.<locals>.make_error_message  s4    $RD$++bd6($ORUVWRXXXrE   r  Nr  r   r   r  get_attrplaceholderr  r  )r  r  r  r2  get_submoduler  r  r  r  r  r  r  r  r  AssertionError)	tracerr  re   rf   r  r  r  r  r  s	    ```    @r8   r  r    s    
B	$	 	Y	_$"t{{D3F3  }$4wtAw4d12hI&I  }$+++00  z!++DKK8  }$&$))333yy1#  %: 
 $%CD 	>* 21 56A= 	1!45DD	1: 
sL   	EC:&C:6C:C:9#C::E	DE*+EEEE0c                 ,   ddl m} j                  }| |v r||    S | j                  }t        j
                  j                  j                  | j                  | j                  ffd      \  }}|dk(  rMj                  j                  | j                     }t        |      st        j                  |      }n ||i | nd}	 t!        | |||      }||| <   |S # t"        $ r0}	 |t%        |	            j'                  |	j(                        dd}	~	ww xY w)z
    Run the actual computation represented by `node` and return the result.
    This will execute any dependent nodes in the graph as well.
    r   )r  c                     t        |       S r@   )get_real_value)r  r  s    r8   r   z get_real_value.<locals>.<lambda>  s    .F+ rE   r  N)r  r  real_value_cacher  r   r$   r  r  re   rf   output_graphr  r  r  r  r  r  r  r5   r  r  )
r  r  r  cacher  re   rf   	nn_module
real_valuer  s
    `        r8   r  r    s   
 '##Eu}T{	B88==((	DKK +LD&
 
]''224;;?	i(i0I t&v&	RfdD&)D
 d   RA'66qGTQRs   C 	D#+DDc                 X   ddl m fd}| j                         D ]<  \  }}t        |t        j
                  j                        s+J d| d ||               | j                         D ]<  \  }}t        |t        j
                  j                        s+J d| d ||               y )Nr   )FakeTensorConfigc                 b    j                   r"dd l}d|j                  | j                         S y)Nr   z"FAKE TENSOR CREATION TRACEBACK: 
 zNEnable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors.)debugrN  format_list_debug_trace)r  rN  r  s     r8   stack_or_hintz7assert_no_fake_params_or_buffers.<locals>.stack_or_hint$  s/    !!89N9Nq~~9^8_``crE   zUnexpected fake buffer r   zUnexpected fake param )torch._subclasses.fake_tensorr  named_buffersr:  r   rz  r!   named_parameters)rP  r  r  bufferrI  r  s        @r8    assert_no_fake_params_or_buffersr  !  s    >d ((* DfE%%00
 	D$TF!M&,A+BC	D 
D **, Be5$$//
 	B#D6=+?*@A	B 
BrE   r<  c                 8    | j                    d| j                   S )z9
    Returns the fully qualified name of the object.
    r  )r   r   r'  s    r8   fqnr  6  s!     nnQs//011rE   c                 R    t         j                  j                  j                  r| S |S r@   )r   _dynamor   assume_static_by_default)count1count2s     r8   ifdynstaticdefaultr  =  s    }}44rE   r~  c           
      8   t        t        j                  t        j                  j	                  t        t        | j                                          D ]D  }|j                  d      s|d   dk7  st        j                  | j                   d|dd         F y)z@
    Ensure all the files in a given submodule are imported
    z.pyr   r   r  N)r  r   listdirr   r  r
   r5   __file__endswith	importlibimport_modulerP   )r~  r  s     r8   import_submoduler  D  sw     2::bggood36M&NOP GU#s(:##s||nAhsm_$EFGrE   r   c                     	 t        t        j                  t        |       d      t        j
                        ry	 y# t        $ r Y yw xY w)N__getattribute__TF)r:  r[  r\  r   rb  rc  AttributeErrorrC  s    r8   object_has_getattributer  M  sS    ""4;0BC
 	
   s   7< 	AAc                     	 t        j                  t        |       d      }|t        j
                  j                  j                  u rd }|S # t        $ r d }Y 7w xY w)N__getattr__)r[  r\  r   r  r   rw  r  r  )r   
getattr_fns     r8   get_custom_getattrr  Y  sV    ++DKG
 UXX__000
  
s   A AAc                       e Zd ZdZdZdZy)TensorStaticReasonr   r  r   N)rP   r   r   	PARAMETER
NOT_TENSORNN_MODULE_PROPERTYrt   rE   r8   r  r  d  s    IJrE   r  r  c                     | t         j                  k(  ry| t         j                  k(  ry| t         j                  k(  ryt	        d|        )Nz>mark_dynamic on parameter, parameters are always static today.z2mark_dynamic on a non tensor, how did this happen?z4tensor is static because it is nn module associated.zIllegal reason )r  r  r  r  r  )r  s    r8   tensor_static_reason_to_messager  j  sJ    #---O#...C#666E
?6(3
44rE   r  	is_tensorguard_sourceztorch._guards.GuardSourcec                    |j                         r"t        j                  rdt        j                  fS t        |       t        j                  j                  u r"t        j                  rdt        j                  fS |sdt        j                  fS y)a@  
    Given a tensor, source, and is_tensor flag, determine if a shape should be static.

    Args:
    tensor - the real tensor to evaluate, parameters force a static shape.
    is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable,
    tensors not in a TensorVariable for whatever reason are forced static.

    Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape.
    The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed.
    T)FN)is_nn_moduler   &force_nn_module_property_static_shapesr  r  r   r   rw  rx  force_parameter_static_shapesr  r  )r  r  r  s      r8   tensor_always_has_static_shaper  t  sr        "v'T'T'::::F|uxx)))f.R.R'1111'2222rE   c                 4      fdt        fd      S )Nc                        d  S S )Nr   rt   )maybe_idr  s   r8   format_namez+lazy_format_graph_code.<locals>.format_name  s    V1XJ''KrE   c                      t        d          dj                  j                  j                  j	                  d            S )Nz===== z =====
F)print_output)_format_graph_coderI  __code__r  print_readable)r  rP  s   r8   r   z(lazy_format_graph_code.<locals>.<lambda>  s?    "[]O8,JJ++51
 rE   r   )r  rP  r  r  s   ```@r8   lazy_format_graph_coder    s     	
 rE   c                     d|  d| d| dS )NzTRACED GRAPH
 r   r0   rt   )r  r  	graph_strs      r8   r  r    s    TF!H:Qyk<<rE   c                 (      fd}t        |      S )Nc                     	 ddl m }  j                  j
                  D cg c];  }|j                  |j                  |j                  |j                  |j                  g= }} | |g d      }t        j                  j                  j                  |      S # t        $ r dt        t                    z   cY S w xY wc c}w )Nr   )r:   zkTabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:
)opcoder  r  re   rf   r.   )r:   r;   r5   r  rH  r  r  r  r  re   rf   r  rI  r  r  )r:   r  
node_specsr  fn_namerP  s       r8   innerz(lazy_format_graph_tabular.<locals>.inner  s    	) AC
;<QTT166188QVVQXX6

 
  N
	 "'2::+>+>+J+JIVV  	~,Wb9:;	
s   B A C!B>=B>r   )r  rP  r  s   `` r8   lazy_format_graph_tabularr    s    W" erE   c                 f    |  d| d| d| dt        j                  |      j                          d
S )Nr   z line z 
r0   )disBytecode)prefixr  r  line_nor  s        r8   format_bytecoder
    s;    XQtfAhZvgYc#,,t:L:P:P:R9SSUVVrE   _forward_pre_hooks_forward_hooks_backward_pre_hooks_backward_hooks)_state_dict_pre_hooks_state_dict_hooks_load_state_dict_pre_hooks_load_state_dict_post_hooksc                 z   t         j                  j                  j                  j                  }	 g }| xr | xr | }|s|r|j                  t               |s|r|j                  t               |r|j                  t               g }|D ],  }t        | |g       }	|	D ]  }
|	|
   }|j                  |        . |S r@   )r   r  r  
eval_frame
reset_codeextendforward_hook_namesbackward_hook_namesstate_dict_hook_namesr2  r   )r~  check_forward_hookscheck_backward_hookscheck_state_dict_hooksr  hook_dicts_to_checkcheck_all_hooks	all_hookshook_dict_namehooks	hook_namer  s               r8   nn_module_get_all_hooksr#    s     !!,,77J  	'$$	'&& 
 o""#56""#67""#89I- #^R0 	#I#DT"	## rE   c                 6    t        | |||      }t        |      S )zL
    Helper function to check if a module has any hooks attached to it.
    )r  r  r  )r#  r  )r~  r  r  r  r!  s        r8   nnmodule_has_hooksr%    s&     $/15	E ;rE   c                 2   t        |       r| S t        | t        j                        rt	        | j
                        S t        | t        j                        r| j                  d      S t        | t        t        f      r t        |       d | D              S | S )z0Convert tensor and tnp.ndarray to numpy.ndarray.T)forcec              3   2   K   | ]  }t        |        y wr@   )to_numpy_helperr6   r<  s     r8   r9   z"to_numpy_helper.<locals>.<genexpr>       AC?3/Ar  )r"   r:  tnprs  r)  r  r   rv  numpyr;  r   r   rC  s    r8   r)  r)    st    u~%%u||,,	E5<<	({{{&&	EE4=	)tE{A5AAArE   c                    t         J t        | t         j                        rt        j                  |       S t        | t
        j                        r| j                  S t        | t        t        f      r t        |       d | D              S | S )zeConvert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert.c              3   2   K   | ]  }t        |        y wr@   )numpy_to_tensorr*  s     r8   r9   z"numpy_to_tensor.<locals>.<genexpr>  r+  r  )
rG  r:  rs  r   r-  r,  r  r;  r   r   rC  s    r8   r0  r0    sk    >>%$u%%%%||	EE4=	)tE{A5AAArE   c                       e Zd Zd Zd Zd Zy)numpy_to_tensor_wrapperc                 N    || _         d| j                   j                  z   | _        y Nwrapped_r  rP   )r   r  s     r8   r   z numpy_to_tensor_wrapper.__init__  s    "TVV__4rE   c                 6    d| j                   j                   dS )Nz<Wrapped function <original >>r6  r   s    r8   __repr__z numpy_to_tensor_wrapper.__repr__  s    -dffoo->bAArE   c                 <     | j                   |i |}t        |      S r@   )r  r0  r   re   rf   r   s       r8   r  z numpy_to_tensor_wrapper.__call__  s"    dffd%f%s##rE   N)rP   r   r   r   r9  r  rt   rE   r8   r2  r2    s    5B$rE   r2  c                     t        | t        j                        rt        | |      }t	        |      S t        | t
        j                        r*t        t        j                  |       |      }t	        |      S y r@   )r:  r,  rs  r2  r0  r   rv  )r<  r  r   s      r8   numpy_attr_wrapperr=  !  sZ    #s{{#c4 s##	C	&ckk#&-s## 
'rE   c                   (    e Zd ZdZdefdZd Zd Zy)numpy_method_wrapperzgConvert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor.methodc                 :    || _         d| j                   z   | _        y r4  )r@  rP   )r   r@  s     r8   r   znumpy_method_wrapper.__init__-  s    "T[[0rE   c                 "    d| j                    dS )Nz<Wrapped method <original r8  )r@  r   s    r8   r9  znumpy_method_wrapper.__repr__1  s    +DKK=;;rE   c                     |d   }t        |t        j                        rt        j                  |      }t        || j                        } ||dd  i |}t        |      S Nr   r   )r:  r   rv  r,  rs  r2  r@  r0  )r   re   rf   r<  method_callabler   s         r8   r  znumpy_method_wrapper.__call__4  sW    1gc5<<(++c"C!#t{{3tABx262s##rE   N)rP   r   r   r8  r5   r   r9  r  rt   rE   r8   r?  r?  *  s    q1s 1<$rE   r?  c                   2    e Zd ZdZdedef   fdZd Zd Zy)numpy_operator_wrapperzQImplements dunder methods for tnp.ndarray via functions from the operator libraryr  .c                 :    || _         d|j                   | _        y r4  )r  rP   )r   r  s     r8   r   znumpy_operator_wrapper.__init__@  s    "2;;-0rE   c                 "    d| j                    dS )Nz<Wrapped operator <original r8  )rP   r   s    r8   r9  znumpy_operator_wrapper.__repr__D  s    -dmm_B??rE   c                 P    |rJ d |D        } | j                   | }t        |      S )Nc              3   ~   K   | ]5  }t        |t        j                        rt        j                  |      n| 7 y wr@   )r:  r   rv  r,  rs  r  s     r8   r9   z2numpy_operator_wrapper.__call__.<locals>.<genexpr>J  s0      
KN
3 =CKK3F
s   ;=)r  r0  r;  s       r8   r  znumpy_operator_wrapper.__call__G  s5    z
RV
 dggtns##rE   N)	rP   r   r   r8  r	   r   r   r9  r  rt   rE   r8   rG  rG  =  s%    [18CH- 1@$rE   rG  c                 B   t        | t              s| S | j                  rg }| j                         D ]v  }t        |t        j
                        rI|j                  |j                  j                  j                  |j                  j                               f|j                  |       x g }| j                         D ]v  }t        |t        j
                        rI|j                  |j                  j                  j                  |j                  j                               f|j                  |       x n | j                         }| j                         }t	        j                  ||| j                  | j                  | j                        }|j!                          |S )N)r  r  r  )r:  r!   _has_symbolic_sizes_stridesr  r   SymIntr   r  	shape_env	size_hintexprr  empty_stridedr  r  r  zero_)r   r  r  r  r  s        r8   defakerT  Q  s*   a$ 	$$ 	A!U\\*AFF,,66qvv{{CDA		
  	!A!U\\*aff..88EFa 		! vvxggxxoo	A GGIHrE   c                 N    dd l }| |j                  j                  j                  u S rw   )torch.utils.checkpointr	  
checkpoint)r<  r   s     r8   is_utils_checkpointrX  q  s     !%++((3333rE   c                      dd l mc m} ddlm} |j
                  }t        j                  j                  j                  r|j                  } |j                  |fi | S )Nr   r   ) TorchHigherOrderOperatorVariable)torch._higher_order_ops.wrap_higher_order_opswrapvariables.higher_order_opsrZ  tag_activation_checkpointr   
_functorchr   functionalize_rng_opswrap_activation_checkpointmake)optionshigher_order_opsrZ  activation_checkpoint_ops       r8   build_checkpoint_variablerg  x  s_    ;;L
 	22  44#3#N#N 0+00 
 rE   c                 `    ddl m}  |       }| dk(  r	 |S | dk(  r|rddlm}  |       }|S d}|S )Nr   )is_dynamo_supportedr%  r  r   )
has_tritonF)r  ri  torch.utils._tritonrj  )device_typeri  compile_supportedrj  s       r8   is_compile_supportedrn    sO    /+-e  
	#42&L  "rE   offsetc                 b    | j                  d      }t        |d| j                  dd            S )z
    Convert byte offset `offset` of `str` into character offset.
    Byte offset is used for 3.11+ instruction column data.
    Takes things like unicode characters into consideration.

    Unchanged from CPython implementation.
    zutf-8Nr  )errors)encoder   decode)r5   ro  as_utf8s      r8   _fix_offsetru    s4     jj!Gww&&wy&ABBrE   c                   6    e Zd ZU eed<   eed<   eed<   eed<   y)_Anchorsleft_end_linenoleft_end_offsetright_start_linenoright_start_offsetNr=  rt   rE   r8   rw  rw    s     rE   rw  segmentc                    t         j                  dk\  sJ ddl}	 |j                  d| z   dz         }t        |j                        dk7  ry| j                  d      fd}fd	fd
}fd}|j                  d   }t        ||j                        r|j                  }t        ||j                        rt        t        |j                  j                        dz
  } |||j                  j                         }	 ||	      \  }}	|   |	   x}
j#                         s|
dv r;|
dv r |||	      \  }}	n |||	      \  }}	|   |	   x}
j#                         r6|
dv r;|	dz   }|t        |         k  r!|   |   x}
j#                         s	|
dvr|dz  }t%        ||	||      S t        ||j&                        rt        t        |j                  j                        dz
  } |||j                  j                         } ||      \  }}|   |   dk7  r |||      \  }}|   |   dk7  rt        t        |j                        dz
  } |||j                         }t%        ||||      S t        ||j(                        rt        t        |j*                  j                        dz
  } |||j*                  j                         } ||      \  }}|   |   dk7  r |||      \  }}|   |   dk7  rt        t        |j                        dz
  } |||j                         }t%        ||||      S y# t        $ r Y yw xY w)a  
    Given source code `segment` corresponding to a bytecode
    instruction, determine:
        - for binary ops, the location of the binary op
        - for indexing, the location of the brackets.
    `segment` is expected to be a valid Python expression
    )      r   Nz(
z
)r   r0   c                 "    t        |    |      S r@   )ru  )linenoro  liness     r8   	normalizez-_extract_anchors_from_expr.<locals>.normalize  s    5=&11rE   c                     | t              k  r8|t        |          k\  r'd}| dz  } | t              k  r|t        |          k\  r'| t              k  r|t        |          k  sJ | |fS rD  rT  )r  colr  s     r8   next_valid_charz3_extract_anchors_from_expr.<locals>.next_valid_char  sy    s5z!cSv-?&?CaKF s5z!cSv-?&? E
"sSv-?'???s{rE   c                 p    |dz  } | |      \  } }| t              k  r|t        |          k  sJ | |fS rr   rT  r  r  r  r  s     r8   	incrementz-_extract_anchors_from_expr.<locals>.increment  sH    q%fc2E
"sSv-?'???s{rE   c                 t    d}| dz  }  | |      \  } }| t              k  r|t        |          k  sJ | |fS rD  rT  r  s     r8   nextlinez,_extract_anchors_from_expr.<locals>.nextline  sM    !%fc2E
"sSv-?'???s{rE   r   z)\#z\#r  r  )r;  version_infoastparseSyntaxErrorr   bodyr6  r:  Exprr   BinOpr
   r  left
end_linenoend_col_offsetisspacerw  	SubscriptCallrC   )r|  r  treer  r  r  	statementrQ  
cur_linenocur_colch	right_colleft_linenoleft_colright_linenor  r  s                  @@r8   _extract_anchors_from_exprr    sQ    w&&& yy501 499~MM$E2
 		!I)SXX&dCII& c499#7#781<J
DII,D,DEG"1*g"FJ z*7332<<>",;*2:w*G'J*3J*H'J	 z*7332<<>",  !ICj 122$Z0;;DDFeOQ	 JYGGcmm, sDJJ$9$9:Q>K djj.G.GHH$3K$J!K$X.#5(1+x(H%X $X.#5  T__59L!,0C0CDIK<KKchh'
 sDII$8$89A=K dii.F.FGH$3K$J!K$X.#5(1+x(H%X $X.#5  T__59L!,0C0CDIK<KKK  s   L7 7	MMr  instc                 	   |j                   J |j                   j                  yt        j                  | j                  |j                   j                        j                         }|j                   j                  |S |j                   j                  |j                   j                  |S t        ||j                   j                        }d}d}g }|j                   j                  |j                   j                  k(  rDt        ||j                   j                        }||| }|j                  d|z  d||z
  z  z          n||d dz   }|j                  d|z  dt        |      |z
  z  z          t        j                  | j                  |j                   j                        j                         }t        ||j                   j                        }t        |j                   j                  dz   |j                   j                        D ]  }t        j                  | j                  |      j                         }	||	dz   z  }t        |	      t        |	j                               z
  }
|j                  d|
z  dt        |	      |
z
  z  z           ||d| z  }t        |      t        |j                               z
  }
|j                  d|
z  d||
z
  z  z          d}	 t        |      }|!|D cg c]  }|j!                  dd       }}n%|D cg c]  }t#        |       }}|j$                  dk(  r|xj&                  |z  c_        |j(                  dk(  r|xj*                  |z  c_        t        t        |            D ]  }t        t        ||               D ]t  }||j$                  k  r||j$                  k(  r||j&                  k  r2||j(                  k(  r||j*                  k\  rQ||j(                  kD  ra||   |   dk(  smd||   |<   v  |D cg c]  }dj-                  |       }}d}t        t        |            D ]X  }|t        j                  | j                  |j                   j                  |z         j                         dz   z  }|||   dz   z  }Z |S # t        $ r Y w xY wc c}w c c}w c c}w )	a  
    Python 3.11+ only. Returns lines of source code (from code object `code`)
    corresponding to `inst`'s location data, and underlines relevant code to `inst`.

    Example: CALL on `g`:
    f(g(
      ^^
        h(x)))
        ^^^^^

    We need our own implementation since `format_frame_summary` in
    Python's `traceback` module doesn't handle multi-line expressions
    (and their anchor extraction code is not completely correct).
    Nr  r   ~r0   r   ^r   )	positionsr  	linecachegetliner  rstripr  
col_offsetr  ru  r   r   r  lstripr  r  r  r   rx  ry  rz  r{  r3   )r  r  
first_linestart_offset
end_offsetr|  markers	last_liner  line
num_spacesanchorsmarkermutable_markersr  r  r  s                    r8   get_instruction_source_311r  ,	  s    >>%%%~~$ ""4#3#3T^^5J5JKRRTJ~~  (~~  (DNN,I,I,Q z4>>+D+DEL JGG ~~  DNN$9$99 T^^-J-JK
\*5s\)C:3L,MMN\]+d2s\)C3z?\3Q,RRS%%dnn77

&( 	 !DNN,I,IJ
DNN11A5t~~7P7PQ 	NF$$T%5%5v>EEGDtd{"GTS%77JNN3+cSY5K.LLM	N 	9[j))^c)*:*:*<&==
sZ'#j1H*IIJ"&G,W5
 :AB6>>#s+BB HO+OVDL+O+O ""a'##|3#%%*&&,6& CL) 	7FS!89: 7G333W444w?V?V9Vg888w999G666"6*3/3636OF+C07	7" 2AAv2776?AAF3w<  $d..0E0E0IJQQS	
 	'!*t##$ MW  
 C ,P4 Bs$   R% 0R5R:R?%	R21R2c                 R    t        | t        j                        rt        | dd       S y )N_dynamo_static_input_type)r:  r   rv  r2  r  s    r8   get_static_address_typer  	  s#    !U\\"q5t<<rE   c                    t         j                  j                  j                  t         j                  j                  t         j
                  t         j                  j
                  f}t         j                  j                  j                  t         j                  j                  t         j                  t         j                  j                  f}| g ||v S r@   )	r   r  	Generator	get_statedefault_generatorr  r  	set_stater  )r   getterssetterss      r8   is_rng_state_getter_or_setterr  	  s     	$$))

  G 	$$))

  	G (g((((rE   c                     t        | t        j                        xrA | j                  dk(  xr0 | j                  j
                  t        j                  j                  u S )N__get__)	r:  rb  r   rP   __self____objclass__r   r  _TensorBaserC  s    r8   is_tensor_base_attr_getterr  	  sK    5%112 	@NNi'	@NN''588+?+??rE   c                     t        | d      S )N__torch_function__)r  rC  s    r8   is_torch_function_objectr  	  s    5.//rE   r  z,torch._dynamo.variables.base.VariableTrackerc                 ~    ddl m} ddlm} t	        | |      xs$ t	        | |      xr t        | j                  d      S )Nr   )UserDefinedObjectVariable)TensorWithTFOverrideVariabler  )torch._dynamo.variablesr  &torch._dynamo.variables.torch_functionr  r:  r  r   )r  r  r  s      r8   has_torch_functionr  	  s<    ASb67 201 	4BHH23rE   c                     d }d }t         j                  j                  j                         x}r)| |j                  v r|j                  |    }|j
                  }|j                  | d||      S )NF)static_shapessymbolic_contextsource)r   _guardsTracingContexttry_gettensor_to_contexttensor_sourcefrom_tensor)r  r  r  r  tracing_contexts        r8   to_fake_tensorr  	  sw    F--66>>@@@111.@@C%33F  	1A& !  rE   c                 d    |D ]  }t        | |      st        | |      c S  t        |  d|       )zX
    Return the first available attribute or throw an exception if none is present.
    z% does not has any of the attributes: )r  r2  r  )r<  attrsattrs      r8   get_first_attrr  	  sC      &33%%& C5 EeWM
NNrE   c              #      K   d }| r7t         j                  j                  j                  |      5 }| d d d        y d  y # 1 sw Y   y xY ww)Nc                 :    d }t        j                  | |dd      S )Nc                     t         j                  j                  j                  d   dxx   dz  cc<   t         j                  j                  | |      S )Ncompiled_autogradcompilesr   )r   r  r	  r)   	_inductorcompile)gm_example_inputs_s     r8   inner_compilerzKmaybe_enable_compiled_autograd.<locals>.compiler_fn.<locals>.inner_compiler	  s?    MM(()<=jIQNI??**3@@rE   T)backend	fullgraphdynamic)r   r  )rP  r  s     r8   compiler_fnz3maybe_enable_compiled_autograd.<locals>.compiler_fn	  s     	A }}R4QUVVrE   )r   r  r  rS   )should_enabler  r  s      r8   maybe_enable_compiled_autogradr  	  sN     W ]],,33K@ 	CI	 	 		 	s   /AAAA	Ac                  @     G d dt               } t         |              S )Nc                       e Zd Zy)*invalid_removeable_handle.<locals>.InvalidN)rP   r   r   rt   rE   r8   Invalidr  	  s    rE   r  )r&  r   )r  s    r8   invalid_removeable_handler  	  s    $  79%%rE   c                 
   t        | t        j                  j                        s| S t        | t        j                  j
                        r| S | j                  j                  | j                        }| j                  |_        |S r@   )	r:  r   rw  r  r$   ri  r  __new__r.  )r~  proxys     r8   nn_module_proxyr  	  sZ    c588??+
#uxx++,
MM!!#--0E\\ENLrE   )NN)r5   Fr@   )r  N)F)r   )T)FFF(?  atexitr   r   r  rQ   r@  rl  r  ro  rY  rT  r[  r<   r  r   r(  r  r   rI   r  r[   r;  ra  	threadingrT   rb  r@  r4  r   r   r   pathlibr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   utils.hooksr   r-  rG  ModuleNotFoundErrortorch._loggingr   torch._numpy_numpyr,  torch._guardsr   r   r  r   fftlinalgr  r    
ModuleTyper  NP_TO_TNP_MODULEr;  r  r!   r"   r#   r;   r  torch._functorch.config%torch.fx.experimental.symbolic_shapesr$   torch._dispatch.pythonr%   torch._utils_internalr&   torch.nn.modules.lazyr'   torch.utils._pytreer(   defaultdictr)   r5   r*   troubleshooting_urlnnmodule_doc_urlnnmodule_doc_url_msgr   rP   r   r+   r  r,   r  rO   r:   rD   rB   rs   ru   ry   r{   r}   r   r   r   registerr   FloatTensorrS  DoubleTensorrT  double
HalfTensorrR  halfBFloat16Tensorr*  
ByteTensorrL  
CharTensorrH  
LongTensorrK  long	IntTensorrJ  r  ShortTensorrI  short
BoolTensorr  tensortype_to_dtyper   r   r   r   r   r   r  r  Graphr  r  r  r"  r$  r>  rD  rP  rU  r`  rX  rl  rj  rt  r|  r  r  r  r  rA  r  !DEFAULT_COMPILATION_METRICS_LIMITr  r  r  r  r  r  r  r  r  r  r  r  rv  r  r  r  r#  r%  r+  r*  rE  rQ  rZ  r`  rk  complexbytesr   Ellipsisr  CodeTyper  r  memory_formatlayoutrq  rn  rw  r{  r  r  r  r&  r   r  r   r  r   r  r  r  __length_hint__tuple_iterator_lenobjectr  r  r  r  r  rN   	iter_nextr  r  r  r  r  r  r  r  r  GLOBAL_KEY_PREFIXtorch._subclassesr  r  r  r  r!  r  r8  r?  orig_code_mapr   r@  rA  seen_code_maprC  rr  r   ry  r{  r  r~  r  r  r  r  r  r  r  r  r  r  r  r  rp  r  r  r  r  r  r  r
  r  r  r  all_hook_namesr#  r%  r)  r0  r2  r=  r?  rG  rT  rX  rg  rn  ru  rw  r  Instructionr  r  r  r  r  r  r  r  r  r  r  rt   rE   r8   <module>r4     s:
          
   	       	  	  
       % &  #    ( *	.) 
FFIIII	>
eE$4$4c$9: 	
 FFCGGIIszzIIszz	
  %wVV    ,  ; 7 1 - ,C;+B+B;CVCV+W+c73<'
( W$& 4S> &T K .//UV g! 46 $sDK/0 5 35 Dd3:../ 4	!
-` 
  H@!H 8 8
 
u{{3	5	u}}ejj1	5>>+	u{{n	uzzm	u{{EJJ/	OOekk599-	U[[1	uzzm  ( #:"; ",
	?
G288 	 B&	G&
3(%$, T  # # #2 %' ! 3D+2C2C,3 e./ 
34F 3%C %D %!
&&8!9 & ( ( ($ +   )*  ! 0f&
 
 9 9"	$(
 Q 0*"X 2  		J	NN	LL	KK		LL "W  "&dfkkm!4	4 4%)$&--/%:T*S/" :&*+B;+B+B+D+K+K+M&Nd:c?# N&*4=&9Xc]# 9#33 ^^
1
 	5&RM
@s B C  
 !  =(?
; iiVFrH
 
> 
> '( /Fk.E.Ed.KCcN+ K NRV TIJ S '(_ _F T, ,&

/pf  	!1 " ".b!HB*2S 2G%** G	3 	c  5,> 5%,,#$ . 4,--.	2 =*W +,<= ,.?@   $&99<QQ
  	H  	$

$ 
$$$ $&$ $(@4$&	CS 	C# 	C# 	C   v v0B vriU^^ i3?? is iX)"0I d 
O  &EN  	B<  		s%   9b' >B0b5 'b21b25b>=b>