U
    zha                    @   s~  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mZ d dlmZ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+m,Z,m-Z-m.Z. ddl/m0Z0 zd dl1Z2W n e3k
rx   dZ2Y nX zd dl4Z5d dl6m7Z8 d dl9m:Z: d d	l4m;Z; d
dl<m=Z= e2r e2e2j>e2j?e2j@fZAe+ejBdf eCd< e2e8e2j>e8j>e2j?e8j?e2j@e8j@iZDn
eE ZAi ZDd dlFmGZGmHZHmIZI W n eJk
r6   Y nX d dlKZKd dl5Z5d dlLZ5d dlMZ5d dlNmO  mPZQ d dl5mRZR d dlSmTZT d dl9mUZU d dlVmWZW d dlXmYZY d dlZm[Z[m\Z\ d dl]m^Z^ d dl_m`Z`maZa ebej"Zce#ede"ed f eCd< i Zee%edef eCd< dZfdZgdeg dZheiejZki Zle%ede(em f eCd< ebdd Zne%ede%edemf f eCd < eo Zpd!d" Zqd ard#d$ Zsd%d& Ztd aud'd( Zvd)d* Zwd+d, Zxd-d. Zydgd0d1Zzdhd4d5Z{e j|d6d7 Z}e5j~e5je5jmfe5je5je5jfe5je5je5jfe5je5jfe5je5jfe5je5jfe5je5je5jfe5je5je5jfe5je5je5jfe5je5jfi
ZG d8d9 d9Ze Zd:d; Zd<d= Zd>d? Zd@dA ZdBdC ZdDdE ZeRjdFdGdHZdIdJ ZdKdL ZdMdN ZG dOdP dPZdQdR ZejdSkrejejejejejejfZdTdU ZdVdW ZdXdY ZdZd[ Zd\d] Zd^d_ Zd`da Zdbdc Zddde Zdfdg Zedhdidj ZdidkdlZdmdn ZejG dodp dpZejG dqdr drZdsZejedtae$e-eef  eCdu< e-eef dvdwdxZeddydzd{Zdd|d}d~Ze(e-eef  d|ddZejG dd dZG dd deZeǃ e_dd ZddddZdd Ze5jdddZedd Zdd ZϐdjddZdd Zdd Zdd Zed
dd Zdd ZՐdkddZdd Zeddd Zeemeeedeedejeje5je5je5je5jhZea r&d dlZeejj dd Zdd Zdd Zdd Zdd Zdd Zdd Zee  Ze,e'e  eCd< ee  Ze,e.e  eCd< ee  Ze,e.e  eCd< eeeE Ze,e&e  eCd< ejZejZdd Zdd Zdd ZeZ dd Zdd ZddÄ Zddń ZddǄ ZdlddɄZdd˄ Zdd̈́ Zedd|ddτZ	edd|ddфZ
dҐZd dӐlmZ ddՄ Zddׄ Zddل Zdd3dd3d/d3d3ekjfdd܄Zddބ Zejdd Ze ZebeZe#ee(e f eCd< e Ze(d eCd< e ZG dd dZeddd Zdd ZdmddZdd Zdd ZdnddZ e! Z"dd Z#edd Z$dd Z%dd Z&dd Z'edddZ(dd  Z)ejBdddZ*edddZ+edddZ,G d	d
 d
ej-Z.e.dddZ/e-e5jef ede+ee)e. f dddZ0dd Z1dd Z2ddgZ3ddgZ4ddddgZ5e3e4 e5 Z6dd Z7dod d!Z8dpd"d#Z9d$d% Z:d&d' Z;G d(d) d)Z<d*d+ Z=G d,d- d-Z>G d.d/ d/Z?d0d1 Z@d2d3 ZAd4d5 ZBd6d7 ZCedeed8d9d:ZDejG d;d< d<ZEede)eE d=d>d?ZFejejGedd@dAdBZHdCdD ZIdEdF ZJdGdH ZKdIdJ ZLdKedLdMdNZMdOdP ZNdQdR ZOejdSdT ZPdUdV ZQdWdX ZRG dYdZ dZe5jSjTZUe5jRjVd[d\d]ZWd^d_ ZXd`da ZYG dbdc dcZZe[ Z\e*ed eCdd< dqdedfZ]dS (r      N)contextmanager)	lru_cachewraps)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)TracingContext)is_sparse_compressed)log_compilation_event)_format_graph_codelazy_format_graph_code)LazyModuleMixin)
has_tritonhas_triton_packagecountersoptimus_scuba_logzAhttps://pytorch.org/docs/main/torch.compiler_troubleshooting.htmlz;https://pytorch.org/docs/main/torch.compiler_nn_module.htmlzSee z& for more information and limitations.compilation_time_metricsc                   C   s
   t tS N)collectionsdefaultdictfloat r3   r3   E/var/www/html/venv/lib/python3.8/site-packages/torch/_dynamo/utils.py<lambda>w       r5   frame_phase_timingc              
   C   sP   zdd l }|j | |dW S  tk
rJ   ddd t|g| D  Y S X d S )Nr   headers
c                 s   s   | ]}d  tt|V  qdS ), N)joinmapstr).0rowr3   r3   r4   	<genexpr>   s    ztabulate.<locals>.<genexpr>)tabulateImportErrorr<   	itertoolschain)rowsr9   rB   r3   r3   r4   rB   }   s    
rB   c                   C   s   t d a d S Nr   )
curr_framer3   r3   r3   r4   increment_frame   s    rI   c                   C   s   t   t  dad S Nr   )r7   clearr.   rH   r3   r3   r3   r4   reset_frame_count   s    rL   c                 C   s   t | 7 a d S r/   )op_count)Zcntr3   r3   r4   increment_op_count   s    rN   c                  C   sV   d} i }t  D ]@}| D ]2\}}| |7 } ||kr>|||< q||  |7  < qq|S )Ng        )r7   valuesitems)totaltotal_by_keyZtimingskeyZtimingr3   r3   r4   calculate_time_spent   s    
rT   c                  C   sB   t  } d}|  D ]"\}}| d| dt|d }qt| d S )NzTIMING: :   )rT   rP   roundprint)rR   outrS   valuer3   r3   r4   print_time_report   s
    r\   c                 C   s   t |  |  |7  < d S r/   )r7   )rS   
phase_name
time_spentr3   r3   r4   _add_time_spent   s    r_   Tc                    s    fdd}| r|| S |S )Nc                    s   t   fdd}|S )Nc                     s   j }|tkrg t|< d }d }td}zzNtj| d$ t } | |}t | }W 5 Q R X t| | W n8 tk
r } ztt|}t|} W 5 d }~X Y nX W 5 rtt}r|d krt|| ntjj	 d k	rttjj
 j}d|ksd|kr,|d kr,t|| nd|krttjj }|d kr\t|| dkr|d krt| 
dd }	t| 
dd }
nd }	d }
t||	|
||}t| X |S )Nz-infforwardZ	inferenceZbackwardZinductor_compileZcode_genz (dynamo_timed))__qualname__r.   r2   r>   rH   r_   torch_guardsr$   try_getgetaot_graph_nameZCompileContextZcurrent_compile_idr7   BwdCompilationMetricsrecord_compilation_metricsZprofilerZrecord_functiontimeappend	Exceptiontype)argskwargsrS   	fail_typefail_reasonr^   	frame_keyrf   
compile_idZinductor_compile_timeZcode_gen_timemetricst0re)funcfwd_onlyr]   r3   r4   time_wrapper   s|    





  
z>dynamo_timed.<locals>.dynamo_timed_inner.<locals>.time_wrapper)r   )rw   ry   rx   r]   )rw   r4   dynamo_timed_inner   s    Fz(dynamo_timed.<locals>.dynamo_timed_innerr3   )Zoriginal_functionr]   rx   r{   r3   rz   r4   dynamo_timed   s    Jr|   r>   Fc                    s|   dd f fdd	| dkrFfddt D }d}|t|d	d
7 }|S | dkrxfddt  D }tt  }||fS dS )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   s   | S r/   r3   xr3   r3   r4   r5   7  r6   zcompile_times.<locals>.<lambda>c                    s     r|t | S dt|| S )Nr;   )sumr<   r=   )rO   item_fn)	aggregater3   r4   fmt_fn7  s    zcompile_times.<locals>.fmt_fnr>   c                    s$   g | ]}| t | d d dfqS )c                 S   s   | dS )Nz.4fr3   r}   r3   r3   r4   r5   >  r6   *compile_times.<locals>.<listcomp>.<lambda>r   )r.   r?   kr   r3   r4   
<listcomp>=  s   z!compile_times.<locals>.<listcomp>z!TorchDynamo compilation metrics:
)FunctionzRuntimes (s)r8   csvc                    s   g | ]} |d d dqS )c                 S   s   | dS )Nz.6fr3   r}   r3   r3   r4   r5   F  r6   r   r   r3   )r?   vr   r3   r4   r   E  s   N)r.   rB   rO   listkeys)reprr   rF   rZ   rO   r9   r3   )r   r   r4   compile_times)  s    

r   c                   C   s   t tddd d S )Nr>   T)r   r   )loginfor   r3   r3   r3   r4   dump_compile_timesM  s    r   c                   @   s&   e Zd Zd	ddZdd Zdd ZdS )
DuplicateWarningChecker   c                 C   s   || _ |   d S r/   )maxsizereset)selfr   r3   r3   r4   __init__a  s    z DuplicateWarningChecker.__init__c                 C   s   t  | _d S r/   )r0   OrderedDictsetr   r3   r3   r4   r   e  s    zDuplicateWarningChecker.resetc                 C   sT   || j kr&| j j|dd tjsPdS n*d | j |< t| j | jkrP| j jdd q0dS )NT)lastF)r   move_to_endr   verboselenr   popitemr   rS   r3   r3   r4   addh  s    

zDuplicateWarningChecker.addN)r   )__name__
__module__ra   r   r   r   r3   r3   r3   r4   r   `  s   
r   c                  C   s$   t jdddk} | rt S t S )NZTORCH_COMPILE_DEBUG01)osenvironre   add_file_handler
contextlib	ExitStack)Zcompile_debugr3   r3   r4   setup_compile_debugw  s    r   c                   C   s   t   d S r/   )graph_break_dup_warning_checkerr   r3   r3   r3   r4   reset_graph_break_dup_checker  s    r   c                     sf   t jt d} t j| dd tt j| d td  t	
 }| fdd |S )NZtorchdynamoTexist_okz	debug.logztorch._dynamoc                      s
     S r/   removeHandlerr3   Zlog_file_handlerloggerr3   r4   r5     r6   z"add_file_handler.<locals>.<lambda>)r   pathr<   get_debug_dirmakedirsloggingFileHandler	getLogger
addHandlerr   r   callback)log_path	exitstackr3   r   r4   r     s    

r   c                     sV   t  } tjd k	rRttj tjj	 D ]"
  |  fdd q*| S | S )Nc                      s
     S r/   r   r3   r   r3   r4   r5     r6   z setup_log_file.<locals>.<lambda>)r   r   r   Zlog_file_namer   r   rb   _logging	_internalZget_loggersr   r   )r   r3   r   r4   setup_log_file  s    

r   c                 C   s(   t   d|j dt| j d|j dS )Nz/error_recordings/_z.rec)r   co_namerl   r   co_firstlineno)exccoder3   r3   r4   gen_record_file_name  s    r   c              	   C   sz   zTt j| rtd|  n6t jt j| dd t| d}|| W 5 Q R X W n  t	k
rt   t
d|  Y nX d S )Nz9Unable to write execution record %s; file already exists.Tr   wbz#Unable to write execution record %s)r   r   existsr   warningr   dirnameopendumprk   	exception)filenameZexec_recordfr3   r3   r4   write_record_to_file  s     r   )gc                 C   s&   d}| j D ]}d|jkr
|d7 }q
|S )Nr   callr   )nodesop)r   cnr3   r3   r4   count_calls  s
    


r   c                 C   s   | S r/   r3   r}   r3   r3   r4   identity  s    r   c                 C   s>   zt |  W dS  tk
r$   Y dS  tk
r8   Y dS X d S )NTF)hash	TypeError
ValueErrorr}   r3   r3   r4   hashable  s    r   c                  O   s   d S r/   r3   rm   rn   r3   r3   r4   nothing  s    r   c                   @   sJ   e Zd ZdZdd Zdd ZdddZd	d
 Zdd Zdd Z	dd Z
dS )ExactWeakKeyDictionaryz\Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equalityc                 C   s   t  | _t  | _d S r/   )dictrO   refsr   r3   r3   r4   r     s    zExactWeakKeyDictionary.__init__c                 C   s   | j t| S r/   )rO   idr   r3   r3   r4   __getitem__  s    z"ExactWeakKeyDictionary.__getitem__Nc                 C   s   | j t||S r/   )rO   re   r   )r   rS   defaultr3   r3   r4   re     s    zExactWeakKeyDictionary.getc                 C   s   t || jkS r/   )r   rO   r   r3   r3   r4   __contains__  s    z#ExactWeakKeyDictionary.__contains__c                    s<   t |  jkr.t| fddj < |j < d S )Nc                    s
     S r/   )
_remove_id)refidxr   r3   r4   r5     r6   z4ExactWeakKeyDictionary.__setitem__.<locals>.<lambda>)r   r   weakrefr   rO   )r   rS   r[   r3   r   r4   __setitem__  s    
z"ExactWeakKeyDictionary.__setitem__c                 C   s(   || j kr| j |= || jkr$| j|= d S r/   )rO   r   )r   r   r3   r3   r4   r     s    

z!ExactWeakKeyDictionary._remove_idc                 C   s   | j   | j  d S r/   )r   rK   rO   r   r3   r3   r4   rK     s    
zExactWeakKeyDictionary.clear)N)r   r   ra   __doc__r   r   re   r   r   r   rK   r3   r3   r3   r4   r     s   
r   c                 C   s(   t |tttfrt| |kS t| |kS )zisinstance() without subclasses)
isinstancetupler   r   rl   )objZallowed_typesr3   r3   r4   istype  s    r         c                 C   s.   t jdkrt| trdS t| tjp,| tjkS )Nr   T)sysversion_infor   _builtin_final_typing_classestyping_FinalGenericr[   r3   r3   r4   	is_typing   s    	r   c              
   C   s2   t sdS 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uint8Zuint16Zuint32Zuint64r   r3   r3   r4   is_numpy_int_type  s    r  c                 C   s   t sdS t| t jt jt jfS r   )r   r   float16float32float64r   r3   r3   r4   is_numpy_float_type!  s    r  c                 C   s:   t | p8t| tjr$t t| dp8t| tjjtjj	fS )N__wrapped__)
is_functionr   	functools_lru_cache_wrapperinspectgetattr_staticrb   _opsZOpOverloadPacket
OpOverloadr   r3   r3   r4   is_function_or_wrapper/  s    r  c                 C   s    t | tjtjtjtjtjjfS r/   )	r   typesFunctionTypeBuiltinFunctionTypeMethodDescriptorTypeWrapperDescriptorTyperb   jitScriptFunctionr   r3   r3   r4   r
  8  s    r
  c                 C   s   t | d S rJ   ) unwrap_with_attr_name_if_wrapper)fnr3   r3   r4   unwrap_if_wrapperE  s    r  c                 C   s~   t | tjrt| d} d}nXt| rHt| ddrHt| d| } d}n.t| rrt| ddrrt| d| } d}nd }| |fS )Nr	  Z_torchdynamo_inlineFZ__script_if_tracing_wrapperZ__original_fn)r   r  r  r  r  r
  )r  	attr_namer3   r3   r4   r  I  s      r  c                 C   s   t sdS t| t jS r   )r   r   ndarrayr   r3   r3   r4   is_numpy_ndarray]  s    r  c                 C   s,   t jt jjftj}|t jjf }t| |S )zCheck of obj is a tensor)	rb   Tensornn	Parameterr   Ztraceable_tensor_subclasses_subclassesr   r   )r   Ztensor_listr3   r3   r4   istensord  s    r#  c                 C   s
   t | tS r/   )r   r)   modr3   r3   r4   is_lazy_moduleo  s    r&  r   c                  G   s   t |   d S r/   )rY   )rm   r3   r3   r4   
print_onces  s    r'  c                    s6   |   fdd}|j dk	r(t|j dks,t|j d S )zNSome black magic to create a cell object that usually only exists in a closurec                      s    S r/   r3   r3   r}   r3   r4   r   |  s    zmake_cell.<locals>.fNr   r   )__closure__r   AssertionError)valr   r3   r}   r4   	make_cellx  s    r+  c                 C   s   z.t dd | D }dd | D }||fW S  tk
r } zDddlm} ddlm} |d||   d	|t|   |d
 W 5 d }~X Y nX d S )Nc                 s   s   | ]}|  V  qd S r/   as_proxyr?   argr3   r3   r4   rA     s     z$proxy_args_kwargs.<locals>.<genexpr>c                 S   s   i | ]\}}||  qS r3   r,  )r?   rS   r/  r3   r3   r4   
<dictcomp>  s      z%proxy_args_kwargs.<locals>.<dictcomp>r   unimplemented)typestrzcall_function args: rU   Zfrom_exc)	r   rP   NotImplementedErrorr   r2  Zvariables.baser3  r   rO   )rm   rn   Z
proxy_argsproxy_kwargsrv   r2  r3  r3   r3   r4   proxy_args_kwargs  s    
r7  c                   @   s  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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< ee ed< eed< e	ed< dS )CompilationMetricsrr   rq   r   co_filenamer   Z
cache_sizeZaccumulated_cache_sizeZguard_countZshape_env_guard_countZgraph_op_countZgraph_node_countZgraph_input_count
start_timeZentire_frame_compile_time_sZbackend_compile_time_sinductor_compile_time_scode_gen_time_sro   rp   Zfail_user_frame_filenameZfail_user_frame_linenoZnon_compliant_opsZcompliant_custom_opsZrestart_reasonsZdynamo_time_before_restart_sZhas_guarded_codeN)
r   r   ra   r>   __annotations__intr   r2   r   boolr3   r3   r3   r4   r8    s4   
r8  c                   @   sF   e Zd ZU eed< ee ed< ee ed< ee ed< ee ed< dS )rg   rr   r;  r<  ro   rp   N)r   r   ra   r>   r=  r   r2   r3   r3   r3   r4   rg     s
   
rg   @   maxlen_compilation_metricscompilation_metricsc                    sP   t   t trd}nd}t trLtj| fdd tjrLt	  d S )NrE  Zbwd_compilation_metricsc                      s   dd t   D S )Nc                 S   s(   i | ] \}}|t |tr t|n|qS r3   )r   r   r   )r?   r   r   r3   r3   r4   r0    s    z@record_compilation_metrics.<locals>.<lambda>.<locals>.<dictcomp>)dataclassesasdictrP   r3   rD  r3   r4   r5     s   z,record_compilation_metrics.<locals>.<lambda>)
rC  rj   r   r8  rb   r   Ztrace_structuredr   Zlog_compilation_metricsr&   )rE  namer3   rD  r4   rh     s    



rh   )new_sizereturnc                 C   s,   t t| krt  q tjt| d}|ad S )NrA  )r   rC  popleftr0   deque)rI  Z	new_dequer3   r3   r4   set_compilation_metrics_limit  s    
rM  )rJ  c                   C   s   t   d S r/   )rC  rK   r3   r3   r3   r4   clear_compilation_metrics  s    rN  c                   C   s   t tS r/   )r   rC  r3   r3   r3   r4   get_compilation_metrics  s    rO  c                   @   s>   e Zd ZU dZeeef ed< eed< dd Ze	dd Z
dS )	CleanupHookz,Remove a global variable when hook is calledscoperH  c                 G   s$   t d k	rt  jd8  _| j| j= d S rG   )CleanupManagercountrQ  rH  r   rm   r3   r3   r4   __call__  s    zCleanupHook.__call__c                 C   s,   || kst t jd7  _|| |< t| |S rG   )r)  rR  rS  rP  )rQ  rH  r*  r3   r3   r4   create  s    zCleanupHook.createN)r   r   ra   r   r   r>   r   r=  rU  staticmethodrV  r3   r3   r3   r4   rP    s   
rP  c                       s.   e Zd ZU dZed  ed<  fddZ  ZS )rR  r   instancec                    s&   | j | D ]
}|  q
t | d S r/   )rO   superr   )r   r   hook	__class__r3   r4   r     s    zCleanupManager._remove_id)r   r   ra   rS  r	   r=  r   __classcell__r3   r3   r[  r4   rR    s   
rR  c                 C   s0   |   | j}| jr,| jdk	r,| j  |_|S )z!Clone the tensor and its gradientN)clonerequires_grad_requires_gradis_leafgradr~   yr3   r3   r4   clone_tensor  s    re  dtypec             
      s(  t | r| S  fdd}t  | jjdkrD|| W  5 Q R  S | jtjkrtj||  || 	 | j
|  dW  5 Q R  S t| r| jtjtjhkr|  }|  }n|  }|  }tj||||||  | j
| jdW  5 Q R  S tdd t|  |  D }| jr0t|d f| }ntj|d  pD| j| jd	}|  |  d |   }||  |  | zJ| | !  | j"r|#| j$ | j"r| j%d
k	rt&| j% d|_%W n* t'k
r   ||  Y W  5 Q R  S X t(| dr| j)* |_)|W  5 Q R  S Q R X d
S )zcopy while preserving stridesc                    sV   t | }| jr|| j | jr<| jd k	r<t| j d|_t| drR| j	 |_|S )Nrf  _dynamo_dynamic_indices)
rb   r^  ra  r_  r`  rb  clone_inputhasattrrh  copyrc  rf  r3   r4   torch_clone  s    

z clone_input.<locals>.torch_cloneZxla)is_coalesced)layoutc                 s   s   | ]\}}|d  | V  qdS )r   Nr3   )r?   shapestrider3   r3   r4   rA   C  s    zclone_input.<locals>.<genexpr>    )rg  deviceNrf  rh  )+r    rb   no_gradrr  rl   rn  Z
sparse_cooZsparse_coo_tensorZ_indicesZ_valuesro  rm  r%   Z
sparse_csrZ
sparse_bsrZcrow_indicesZcol_indicesZccol_indicesZrow_indicesZsparse_compressed_tensorrO   r   zipsizerp  Zis_quantizedZempty_quantizedemptyrg  data_ptrZelement_sizeZas_strided_copy_r^  ra  r_  r`  rb  ri  RuntimeErrorrj  rh  rk  )r~   rg  rl  Zcompressed_indicesZplain_indicesZneeded_sizeresultZcache_line_offsetr3   rf  r4   ri    sf    




 
 ri  c                 C   s   t | tkrft| }| D ]D\}}t|tr<t|||< qt|tjsTtt |t	|||< q|S t
| }tt|D ]$}t|| tjrzt	|| ||< qz|S r/   )rl   r   rP   r   r   clone_inputsrb   r  r)  ri  r   ranger   )example_inputsresrS   r[   ir3   r3   r4   r{  `  s    
r{  )r*  c              
   C   sb   z|    W nP tk
r\ } z2ddlm} tddt| }|d| |W 5 d }~X Y nX d S )Nr   )	SkipFramez\(.* z(torch.compile cannot be run in context: )rw  ry  r   r  resubr   )r*  rv   r  Zfunctorch_subclass_namer3   r3   r4   skip_frame_if_in_functorch_modes  s    r  c                  c   s   t jj} t jjj}| J |  8 t t j }t	| t j
 rTt t j
 }W 5 Q R X W 5 Q R X z
d V  W 5 t jj ( t j| t j
 rt j
| W 5 Q R X X d S r/   )rb   _CZ_DisableFuncTorchutilsZ_python_dispatchZ_disable_current_modesr^  randomget_rng_stater  cudais_availableset_rng_state)Zdisable_functorchZdisable_current_modes	rng_statecuda_rng_stater3   r3   r4   preserve_rng_state  s    

$

r  c                 C   s&   t | tjjjtjjjtjjtjjfS r/   )	r   rb   r  Z_traceZTopLevelTracedModule_scriptZRecursiveScriptModuler  ZScriptModule)Zmodel0r3   r3   r4   is_jit_model  s    r  c                 C   sx   t | r| S ztj| |W S  tk
rr   ztj| W  Y S  tk
rl   |r^td n
td Y nX Y nX d S )Nz	jit errorz0Both torch.jit.trace and torch.jit.script failed)	r  rb   r  tracerk   scriptr   r   error)modelr}  r   r3   r3   r4   torchscript  s    r  c              	   C   s,   zt | W S  ttfk
r&   Y d S X d S r/   )r  getfiler   OSErrorr   r3   r3   r4   r    s    r  c                 C   s   t t| S )zLTest if an object is a namedtuple or a torch.return_types.* quasi-namedtuple)is_namedtuple_clsrl   r  r3   r3   r4   is_namedtuple  s    r  c                 C   sp   zVt | trTt| dg pdg}t| dd}|dkpP|d tkoPt| doPt| dW S W n tk
rj   Y nX dS )	zhTest if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuple	__bases__Nr   )torch.return_typesztorch.autograd.forward_adr   _make_fieldsF)
issubclassr   getattrrj  r   )clsbasesmoduler3   r3   r4   r    s    
r  c                 C   s   | t krdddgS t| ts tt| dr0| jS tjG dd d}| jdksRt| t	|t
| j}dg| j }t|D ]0}|d	 d
krztt|||rz||t||j< qz|S )zIGet the fields of a namedtuple or a torch.return_types.* quasi-namedtuplestartstopstepr  c                   @   s   e Zd ZU eed< dS )z!namedtuple_fields.<locals>.MarkerindexNr   r   ra   r>  r=  r3   r3   r3   r4   Marker  s   
r  r  Nr   r   )slicer  r   r)  rj  r  rF  	dataclassr   r=   r|  n_fieldsdirr   r  r  )r  r  r   fieldsrH  r3   r3   r4   namedtuple_fields  s    

r  c              	      s   t  f t t j t j r4t t j  g t| 	 | 
 D ]}||jt |f qLW 5 Q R X  fdd}|S )Nc               	      s^   t  L t j t j r,t j  D ]\} }}| j|kr0| | q0W 5 Q R X d S r/   )rb   rs  r  r  r  r  _versionrx  )paramversionoriginal_valuer  r  saved_stater3   r4   restore  s    


z"checkpoint_params.<locals>.restore)rb   rs  r^  r  r  r  r  rD   rE   
parametersbuffersrj   r  )gmr  r  r3   r  r4   checkpoint_params  s    

$	r  c                 C   sh   t j rt jj}nt}|  t  t d t	 }t
|D ]}| | }|  q@t	 }||| fS )Ni9  )rb   r  r  synchronizer   gcZcollectZmanual_seedri   perf_counterr|  )r  r}  timesr  rt   r   rz  t1r3   r3   r4   timed  s    


r  c                 C   s    t dd t|| dD S )Nc                 s   s   | ]}|j V  qd S r/   )Zis_cudar?   r~   r3   r3   r4   rA   
  s     z check_is_cuda.<locals>.<genexpr>T)allrD   rE   r  )r  r}  r3   r3   r4   check_is_cuda	  s    r  rq  c                 C   sn   | dkst dd t| D }t|dd  |d d  }tdd| dd| d}d	|  d
|_|S )Nr   c                 S   s   g | ]}d | qS r   r3   )r?   r  r3   r3   r4   r     s     z rot_n_helper.<locals>.<listcomp>zlambda ,z: ()Zrot_Z_helper)r)  r|  reversedevalr<   r   )r   varsZrotatedr  r3   r3   r4   rot_n_helper  s    "r  c                 C   s<   t | ttfrttt| S t| tjt	fp:t | t
thB S r/   )r   r   	frozensetr  r=   is_safe_constantr   enumEnumrl   common_constant_typesr  r  r3   r3   r4   r  -  s    r  c                 C   s,   ddl m}m} t| |r(||  S | S )Nr   )ConstantVariableSymNodeVariable)	variablesr  r  r   rV  Zevaluate_expr)r/  r  r  r3   r3   r4   specialize_symnode6  s    
r  c                 C   s*   ddl m} t| } t| |r&|  S | S )Nr   r  )r  r  r  r   as_python_constant)r/  r  r3   r3   r4   guard_if_dyn@  s
    
r  c                 C   s   t dd t| | D S )Nc                 s   s   | ]}|  V  qd S r/   )is_python_constantr  r3   r3   r4   rA   L  s     z&check_constant_args.<locals>.<genexpr>)r  rD   rE   rO   r   r3   r3   r4   check_constant_argsK  s    r  c                 C   s^   ddl m} ddlm} d}t| | D ](}t||rD|d7 }q,t||s, dS q,|dkS )Nr   r  UnspecializedPythonVariabler   F)Zvariables.constantr  variables.tensorr  rD   rE   rO   r   )rm   rn   r  r  Zunspec_countr~   r3   r3   r4   check_unspec_python_argsO  s    


r  c                 C   s>   ddl m} t| | D ]}| st||s dS qdS )Nr   r  FT)r  r  rD   rE   rO   r  r   )rm   rn   r  r~   r3   r3   r4   check_unspec_or_constant_args\  s
    r  c                    s.   ddl m  t fddt| | D S )Nr   NumpyNdarrayVariablec                 3   s   | ]}t | V  qd S r/   )r   r  r  r3   r4   rA   j  s   z+check_numpy_ndarray_args.<locals>.<genexpr>)r  r  anyrD   rE   rO   r   r3   r  r4   check_numpy_ndarray_argsg  s    r  	dict_keysdict_valuesodict_valuestuple_iteratorc                 C   s   t | }tjj| |S r/   )
object_newrb   r   Moduler   )r  r   r3   r3   r4   nn_module_newx  s    r  c                 C   s   t tj| dS rG   )r  reduceoperatormul)itr3   r3   r4   product~  s    r  c                 C   s   |   \}\}}|||  S r/   )
__reduce__)r  r  r   r   r  r3   r3   r4   tuple_iterator_getitem  s    r  c                 C   s
   |  |S r/   )Zas_subclass)tr  r3   r3   r4   to_subclass  s    r  c                 C   s   t tt| ||d S rG   )nextrD   isliceiter)dr   r3   r3   r4   dict_keys_getitem  s    r  c                 C   s2   | j j}| j}|rdnd}| d| d| }|S )NLGz["z"].)r\  r   rH  )r[   localrH  r*  rQ  Z
local_namer3   r3   r4   	enum_repr  s
    r  c                 C   s:   || j d< t jj}tjjj	|| }r6|| j d< d S )Nexample_valueZunbacked_bindings)
metar$   re   	fake_mode	shape_envrb   r"   experimentalsymbolic_shapesZcompute_unbacked_bindings)noder  r  Zsymbol_to_pathr3   r3   r4   set_example_value  s    

 r  c                 C   s2   |   jjd}t|s.ddlm} |d |S )Nr  r   r1  z:Cannot check Tensor object identity without its fake value)r-  r  r  re   r    r   r2  )vtfake_tensorr2  r3   r3   r4   _get_fake_tensor  s
    r  c                    s   ddl m}m}m}m}   r@t fdd| D }||S d}	|r^t |r^d}	t	  d }
| D ]l}|	rt||r҈ t	|kr|d  S qf|t
j|| gi }|
d kr|}
qf|t
j|||
gi }
qf|
d kr|d}
|
S )Nr   )BuiltinVariabler  TensorVariableVariableTrackerc                 3   s&   | ]}|  o|   kV  qd S r/   )r  r  r  searchr3   r4   rA     s   z iter_contains.<locals>.<genexpr>FT)r  r  r  r  r	  r  r  rV  r   r  r  eqcall_functionor_)rP   r  txZcheck_tensor_identityr  r  r  r	  Zfound_constZmust_check_tensor_idfoundr~   checkr3   r
  r4   iter_contains  s6    


  
r  c                 C   s   t | tjtjjtfS )z4Returns whether it indexes dictionaries using its id)r   rb   r  r   r  r   )r   r3   r3   r4   	key_is_id  s    r  c                 C   s   dd |   D S )Nc                 S   s    g | ]}t |rt|n|qS r3   )r  r   r   r3   r3   r4   r     s     zkey_to_id.<locals>.<listcomp>)r   r   r3   r3   r4   	key_to_id  s    r  c                   s   ddl m} t| ttfr|d fdd| D }t| trHd| dS t| tsVtt| dkrnd| d	S d| d
S nNt| tj	rt
|  dddS || r| jS t| trdd }|| S | S d S )Nr   )is_builtin_callabler  c                 3   s   | ]}t | d V  qdS r  N
const_reprr?   sr  r3   r4   rA     s     zconst_repr.<locals>.<genexpr>[](z,)r  r  'r  c                 S   s(   | j }|j}|dkr|jS |d |j S )Nbuiltins.)r\  r   ra   )oklassr  r3   r3   r4   fullname  s
    zconst_repr.<locals>.fullname)Ztrace_rulesr  r   r   r   r<   r)  r   r  r  r  replacer   rl   )r~   r  r  Z
elems_reprr$  r3   r  r4   r    s"    

r  c                   s$   d  fdd| D }d| d S )Nr  c                 3   s   | ]}t | d V  qdS r  r  r  r  r3   r4   rA     s     z!dict_keys_repr.<locals>.<genexpr>r  r  r<   )Z
const_keysr  Zkeys_strr3   r  r4   dict_keys_repr  s    r'  Z
__dict_key)UnsupportedFakeTensorExceptionc              
   C   s`   z|  W S  t k
rZ } z4ddlm} d|j d}t| |||d W 5 d }~X Y nX d S )Nr   r1  zUnsupported: z with fake tensor propagation.r4  )r(  r   r2  reasonr   r   )r  rv   r2  msgr3   r3   r4   wrap_fake_exception  s    
r+  c              
      s6   t jj| t fddW  5 Q R  S Q R X d S )Nc                      s
   t  S r/   )rk  deepcopyr3   r  r3   r4   r5     r6   z)deepcopy_to_fake_tensor.<locals>.<lambda>)rb   r"  r  ZFakeCopyModer+  )r   r  r3   r  r4   deepcopy_to_fake_tensor  s    r-  c                 C   s   t t t | | S )z+
    Calculate root mean squared error
    )rb   sqrtZmeanZsquare)r   r~  r3   r3   r4   rmse"  s    r/  g-C6?c
                    s  dkrt tttjjtjfrt ttfsNtdt dt t	t	krjd dS t	t	kot
 
fddtD S tjdkrtjjj 
d	
S t tr~t tstt t ks,td
t  dt  t D ]@}
t|
 |
 |
  
d
s8d|
  dS q8dS t tjtfrJt tjjrtt tjjrtdd 		fddfD \jrjst  t tjs,tdt dt rjjkrTdjj dS jtjkrrldS tjjtjdjtjd

d}|sd |S  r& tj tjtj

ddrdS tjj j!ddd}|dk rt"#d|$ % &  |dkS s8jtj

drRdS jtj'kr.t(& }t)*|rt"#d t(& }jtj+krdnd}, dk sj-dkrj.d  j.d!   krd"ksn 
d#krd}||| 
d$  k}|s*d%||/ j|
 |S r8dS d&
 dS n\t t0t1tdttj2frrpdS k}|sd't |S t3st4rrt3st4sʈ& ttkok}|sd( |S t5r>ttko<tt6t6 
d
S tjd)krttksdtt
 
f
d*dj7 D S t8d+tj dS ),z-Check correctness to see if ref and res matchNztype mismatch rU   zLength mismatchFc                 3   s0   | ](\}}}t ||| d 
V  qdS )	log_errorN)same)r?   ZaiZbiZ	fp64_refi)cos_similarity	equal_nanexact_dtypeignore_non_fpr1  relax_numpy_equalitytolr3   r4   rA   =  s   zsame.<locals>.<genexpr>ZQuestionAnsweringModelOutputr0  zkeys mismatch z == r3  r8  r4  r5  r7  r6  r1  zAccuracy failed for key name %sTc                 S   s   t | tjr| S t| S r/   )r   rb   r  tensorr  r3   r3   r4   	to_tensorw  s    zsame.<locals>.to_tensorc                 3   s   | ]} |V  qd S r/   r3   )r?   r*  )r<  r3   r4   rA   z  s     zdtype mismatch %s, %srf  )ZatolZrtolr4  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     r  r   g{Gz?g      $@z\RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s. res.dtype: %s, multiplier: %f, tol: %fz+Accuracy failed: allclose not within tol=%szAccuracy failed (%s): %s != %sz!Accuracy failed (numpy): %s != %s)ZMaskedLMOutputZSeq2SeqLMOutputZ!CausalLMOutputWithCrossAttentionsZLongformerMaskedLMOutputZ	InstancesZSquashedNormalZBoxesZNormalZTanhTransformZFooVariablec                 3   s<   | ]4}t t|t|t| 	d 
V  qdS )r9  N)r2  r  )r?   rS   )
r3  r4  r5  fp64_refr6  r1  r   r7  r~  r8  r3   r4   rA     s   zunsupported type: )9r   r   r   rb   r   ZParameterListSizer)  rl   r   r  rt  r   r2  Zlossr   r   r   sortedr  r2   r"  r   Z	is_sparseZto_denserg  r?  Zallclosetor  flattenr  Z
functionalZcosine_similarityr   r   cpudetachitemr  r/  mathisnanbfloat16Znumelndimro  ru  r>   r>  rr  r  r  r  	as_tensor__dict__ry  )r   r~  rB  r3  r8  r4  r5  r7  r6  r1  r   ru   ZscoreZ	ref_errorZ	res_errorZ
multiplierZpasses_testr3   )r3  r4  r5  rB  r6  r1  r   r7  r~  r<  r8  r4   r2  )  s@   *(



*

 

	


r2  c                 C   s,   | j dd }d| j d| d| j dS )N/r  r  z' (rV   r  )r9  splitr   r   )r   Zshort_filenamer3   r3   r4   format_func_info  s    rR  c                  c   s:   t j} tjt _t j}tjt _z
d V  W 5 | t _|t _X d S r/   )r   Zcache_size_limitr   r   Zaccumulated_cache_size_limit)ZpriorZprior_acc_limitr3   r3   r4   disable_cache_limit  s    
rS  guard_failuresz-torch._dynamo.output_graph.GraphCompileReasongraph_break_reasonsc                   @   sJ   e Zd ZdZdd ZejjdddZdd Z	d	d
 Z
dd Zdd ZdS )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                 C   s   d| _ d| _t| _d S rJ   )frame_countrM   rS  Zbackend_ctx_ctorr   r3   r3   r4   r   ?  s    zCompileProfiler.__init__r  c                 C   s:   |  j d7  _ |jjD ]}d|jkr|  jd7  _q|jS )Nr   r   )rW  graphr   r   rM   r`   )r   r  r}  r  r3   r3   r4   rU  D  s
    
zCompileProfiler.__call__c                 C   s   | S r/   r3   r   r3   r3   r4   	__enter__L  s    zCompileProfiler.__enter__c                 C   s   d S r/   r3   )r   typr*  	tracebackr3   r3   r4   __exit__O  s    zCompileProfiler.__exit__c                 C   s   dt iS )NrT  )rT  r   r3   r3   r4   get_metricsR  s    zCompileProfiler.get_metricsc                    s   |   }|d   fdd fddfdd D dd	 } fd
d}td}|| phd7 }|td7 }|| pd7 }|S )NrT  c                    s   t  |  S r/   )r   r   gfr3   r4   num_recompilesY  s    z.CompileProfiler.report.<locals>.num_recompilesc                    s   d dd  |  D S )Nr:   c                 S   s   g | ]}t |qS r3   )r>   r  r3   r3   r4   r   ]  s     zECompileProfiler.report.<locals>.recompile_reasons.<locals>.<listcomp>r&  r_  r`  r3   r4   recompile_reasons\  s    z1CompileProfiler.report.<locals>.recompile_reasonsc                    s"   g | ]}t | ||gqS r3   )rR  r?   r   )rb  rc  r3   r4   r   _  s   z*CompileProfiler.report.<locals>.<listcomp>c                      s2   dt kr.t d  t fdd D ddgdS d S )NZgraph_breakc                    s   g | ]}| | gqS r3   r3   )r?   r*  Zgraph_breaksr3   r4   r   h  s     zFCompileProfiler.report.<locals>.graph_break_report.<locals>.<listcomp>zGraph Break ReasonZCountr8   )r,   rB   r3   r3   re  r4   graph_break_reportd  s    z2CompileProfiler.report.<locals>.graph_break_reportc                     sJ   t  rFtfdd D } tdddgd}|td|  d S d S )	Nc                 3   s   | ]} |V  qd S r/   r3   rd  )rb  r3   r4   rA   n  s     zGCompileProfiler.report.<locals>.recompilation_report.<locals>.<genexpr>r   Z
RecompileszRecompile Reasonsr8   zC

                    Set torch._dynamo.config.cache_size_limit to z/ to avoid being cache limited.
                )r   maxrB   textwrapdedent)Zmax_recompilesZrecomp_table)ra  rb  summarized_gfr3   r4   recompilation_reportl  s    z4CompileProfiler.report.<locals>.recompilation_reporta  
            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.
)r^  rh  ri  )r   rs   rf  rk  reportr3   )ra  rb  rc  rj  r4   rl  U  s$    zCompileProfiler.reportN)r   r   ra   r   r   rb   r"   GraphModulerU  rZ  r]  r^  rl  r3   r3   r3   r4   rV  6  s   rV  c                 C   s2   dt j  d d tt  }tj| |S )NZrun_z%Y_%m_%d_%H_%M_%S_%fz-pid_)datetimenowstrftimer>   r   getpidr   r<   )root_dirdir_namer3   r3   r4   _get_debug_dir  s    
rt  c                  C   s   t j} t| S r/   )r   Zdebug_dir_rootrt  )Z
debug_rootr3   r3   r4   r     s    r   c                 C   sD   d| j kr"t| j d r"| j d S |r<ddlm} |d nd S d S )Nr  r   r1  z9`FakeTensor` example value was required but not available)r  r    Ztorch._dynamo.excr2  )r  requiredr2  r3   r3   r4   extract_fake_example_value  s    

rv  c                 C   s   t | |jkst| S r/   )r!   r  r)  )rv   r  r3   r3   r4   ensure_graph_fake  s    rw  c                    s(   t jjd fdd}t jj||S )Nr   c                    sH   | j dkr d| jkr t|  S | jd } sDt|tjrDt|S |S )Nr  r  )r   r  get_fake_valuer   rb   r  rw  )r   rZ   allow_non_graph_faker  r3   r4   visit  s    

z)get_fake_values_from_nodes.<locals>.visit)rb   r"   Noder  map_arg)r  r   r{  r|  r3   rz  r4   get_fake_values_from_nodes  s    r  c              
      s:  ddl m} ddlm}m}m}m}m} j}	dj	krPt
j	d rPj	d S tjjf|\ d|	dkrt dkrt d tjjrt d jft dd   |	dkrjjj trtd	r  tjzBj0 t  t fd
d}
W 5 Q R X W 5 Q R X W n |k
rP    Y n tk
r } z|}|jdk	rz|j}t|tj j!j"r|d|j# d nLt|tj j!j$rtj%j&j's|d|j# d n|d|j# d nt|tj j!j(rp|j#}	d}t|	tj)j*rVtj+,|	j-j.|	j-j/}|dk	rV|\}}d| d| d| d}|d|j# d| d n~t|tj0j1j2j3r||j4d| ddnRt||r||j4|jd |n0t|t5rdt6|kr|dj d|  |t6|7|j8dW 5 d}~X Y nX |s6t9:tj;t<j=t>d|
}|
S ) 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   )TorchRuntimeErrorr2  Unsupported	UserErrorUserErrorTyper  Ncall_methodcall_moduleZ_initialize_hookc                      s   t j S r/   )run_nodeoutputr3   rm   rn   nnmoduler  r  r3   r4   r5     r6   z get_fake_value.<locals>.<lambda>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 = Truezm; Operator does not have a meta kernel that supports dynamic output shapes, please report an issue to PyTorchr  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 torch._check OR torch._check_is_size APIs.  Zconstrain_as_size_example)Z	case_nameargumentz
TypeError z: )r  )?Ztorch.utils._sympy.value_rangesr  r   r  r2  r  r  r  r   r  r    r  rm   rn   r   r   rb   r   r  r-  r  r   r  
nn_modulestargetr&  rj  Z_infer_parametersr#   r+  ry  	__cause__r"  r  ZDataDependentOutputExceptionrw   ZDynamicOutputShapeException_dynamor   Z capture_dynamic_output_shape_opsZUnsupportedOperatorExceptionr  r  r  Z_dispatch_pystubZ_schemarH  Zoverload_namer"   r   r  ZGuardOnDataDependentSymNodeZCONSTRAINT_VIOLATIONr   r>   with_traceback__traceback__pytreeZtree_map_onlyr  r  partialrw  )r  r  r{  r  r  r2  r  r  r  r   Zret_valrv   causeZimport_suggestionZmaybe_pystubr  ctxr   r3   r  r4   ry    s    	
 
 &"    
 
(  ry  c                   C   s   t tdd S )Nr[   )r  _current_noder3   r3   r3   r4   get_current_nodeI  s    r  c                 c   s$   t  }| t_z
d V  W 5 |t_X d S r/   )r  r  r[   )r  oldr3   r3   r4   set_current_nodeM  s
    
r  c                    s  j tp  fdd}zڈdkrHj W W  5 Q R  S dkr|t d j dd W W  5 Q R  S dkr|dk	st| W W  5 Q R  S d	kr| jjW W  5 Q R  S d
k rdjkstjd W W  5 Q R  S W n| tt	fk
rB } z ddl
m} ||||d W 5 d}~X Y n: tk
rz } zt|||j|W 5 d}~X Y nX W 5 Q R X tdS )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              	      s(   d dj  d  d d	t|  S )NzFailed running rU   z(*z, **z):
)r  r>   )rv   rm   rn   r  r   r3   r4   make_error_messagej  s    z$run_node.<locals>.make_error_messager  r  r   r   Nr  Zget_attrplaceholderr  r1  r4  )r   r  r  r  r)  output_graphZget_submoduler  r5  r(  r   r2  rk   ry  r  r  )tracerr  rm   rn   r  r  rv   r2  r3   r  r4   r  W  s4    ,
 r  c           
   
      s   ddl m}  j}| |kr"||  S | j}tjj| j| j	f fdd\}}|dkrjd| j
krj| j
d jS |dkr jj| j }t|st|}q||| nd}zt | |||}||| < W n8 tk
r }	 z|t|	|	jdW 5 d}	~	X Y nX |S )	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                    s
   t |  S r/   )get_real_valuerx  r  r3   r4   r5     r6   z get_real_value.<locals>.<lambda>r  Zgraphargr  N)r   r  Zreal_value_cacher   rb   r"   r  r~  rm   rn   r  exampler  r  r  r&  rk  r,  r  ry  r>   r  r  )
r  r  r  cacher   rm   rn   Z	nn_module
real_valuerv   r3   r  r4   r    s.    

(r  c                    s   ddl m m}  fdd}|  D ](\}}||r$td| d|| q$|  D ](\}}||rVtd| d|| qVd S )Nr   )FakeTensorConfigr    c                    s(    j r dd l}d|| j S dS d S )Nr   z"FAKE TENSOR CREATION TRACEBACK: 
 zNEnable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors.)debugr\  format_listZ_debug_trace)r  r\  r  r3   r4   stack_or_hint  s    z7assert_no_fake_params_or_buffers.<locals>.stack_or_hintzUnexpected fake buffer rU   zUnexpected fake param )torch._subclasses.fake_tensorr  r    Znamed_buffersr)  Znamed_parameters)r  r    r  rH  bufferr  r3   r  r4    assert_no_fake_params_or_buffers  s    r  r  c                 C   s   | j  d| j S )z9
    Returns the fully qualified name of the object.
    r!  )r   ra   r  r3   r3   r4   fqn  s    r  c                 C   s   t jjjr| S |S d S r/   )rb   r  r   Zassume_static_by_default)Zcount1Zcount2r3   r3   r4   ifdynstaticdefault  s    
r  r$  c                 C   s\   t ttjtt| jD ]8}|dr|d dkrt	
| j d|dd   qdS )z@
    Ensure all the files in a given submodule are imported
    z.pyr   r   r!  N)rD  r   listdirr   r   r   r>   __file__endswith	importlibimport_moduler   )r%  r   r3   r3   r4   import_submodule  s    "r  r   c                 C   s<   z"t tt| dtjr W dS W n tk
r6   Y nX dS )N__getattribute__TF)r   r  r  rl   r  r  AttributeErrorr   r3   r3   r4   object_has_getattribute  s    
r  c                 C   sD   zt t| d}W n tk
r,   d }Y nX |tjjjkr@d }|S )N__getattr__)r  r  rl   r  rb   r   r  r  )r[   Z
getattr_fnr3   r3   r4   get_custom_getattr  s    
r  c                   @   s   e Zd ZdZdZdZdS )TensorStaticReasonr   r?  rW   N)r   r   ra   	PARAMETER
NOT_TENSORNN_MODULE_PROPERTYr3   r3   r3   r4   r    s   r  r)  c                 C   s<   | t jkrdS | t jkrdS | t jkr*dS td|  d S )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  r3   r3   r4   tensor_static_reason_to_message  s    


r  ztorch._guards.GuardSource)r:  	is_tensorguard_sourcerJ  c                 C   sJ   |  rtjrdtjfS t| tjjkr8tj	r8dtj
fS |sFdtjfS dS )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)Zis_nn_moduler   Z&force_nn_module_property_static_shapesr  r  rl   rb   r   r!  Zforce_parameter_static_shapesr  r  )r:  r  r  r3   r3   r4   tensor_always_has_static_shape  s    


r  c                    s    fdd}t |S )Nc                     sr   zddl m }  W n& tk
r6   dtt   Y S X dd jjD }| |dddd	d
gd}t jjj	|S )Nr   )rB   zkTabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:
c                 S   s$   g | ]}|j |j|j|j|jgqS r3   )r   rH  r  rm   rn   )r?   r   r3   r3   r4   r   %  s    z<lazy_format_graph_tabular.<locals>.inner.<locals>.<listcomp>opcoderH  r  rm   rn   r8   )
rB   rC   r>   r(   rY  r   r'   r`   __code__r9  )rB   Z
node_specsZ	graph_strfn_namer  r3   r4   inner  s     z(lazy_format_graph_tabular.<locals>.innerr   )r  r  r  r3   r  r4   lazy_format_graph_tabular  s    r  c                 C   s,   |  d| d| d| dt |   d
S )NrU   z line z 
r:   )disBytecode)prefixrH  r   line_nor   r3   r3   r4   format_bytecode0  s    r  Z_forward_pre_hooksZ_forward_hooksZ_backward_pre_hooksZ_backward_hooksZ_state_dict_pre_hooksZ_state_dict_hooksZ_load_state_dict_pre_hooksZ_load_state_dict_post_hooksc                   C   s    t tjjjjpt tjjjjS r/   )r   rb   r   modulesr  Z_global_backward_hooksZ_global_backward_pre_hooksr3   r3   r3   r4   nn_module_has_global_hooks?  s    
r  c                 C   s   t jjjj}g }| o | o | }|s*|r4|t |s<|rF|t |rT|t g }|D ],}t	| |g }	|	D ]}
|	|
 }|
| qpq\|S r/   )rb   r  r  
eval_frame
reset_codeextendforward_hook_namesbackward_hook_namesstate_dict_hook_namesr  rj   )r%  check_forward_hookscheck_backward_hookscheck_state_dict_hooksr  Zhook_dicts_to_checkZcheck_all_hooksZ	all_hooksZhook_dict_namehooks	hook_namerZ  r3   r3   r4   nn_module_get_all_hooksG  s(    


r  c                 C   s   t | |||d}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  r3   r3   r4   nnmodule_has_hooksi  s    	r  c                 C   sf   t | r| S t| tjr"t| jS t| tjr:| jddS t| t	t
fr^t| dd | D S | S dS )z0Convert tensor and tnp.ndarray to numpy.ndarray.T)forcec                 s   s   | ]}t |V  qd S r/   )to_numpy_helperr?   r   r3   r3   r4   rA     s     z"to_numpy_helper.<locals>.<genexpr>N)r    r   tnpr  r  r:  rb   r  numpyr   r   rl   r   r3   r3   r4   r  {  s    
r  c                 C   s`   t dk	stt| t jr"t| S t| tjr4| jS t| tt	frXt
| dd | D S | S dS )zeConvert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert.Nc                 s   s   | ]}t |V  qd S r/   )numpy_to_tensorr  r3   r3   r4   rA     s     z"numpy_to_tensor.<locals>.<genexpr>)r   r)  r   r  rb   rN  r  r:  r   r   rl   r   r3   r3   r4   r    s    
r  c                   @   s$   e Zd Zdd Zdd Zdd ZdS )numpy_to_tensor_wrapperc                 C   s   || _ d| j j | _d S NZwrapped_r   r   )r   r   r3   r3   r4   r     s    z numpy_to_tensor_wrapper.__init__c                 C   s   d| j j dS )Nz<Wrapped function <original >>r  r   r3   r3   r4   __repr__  s    z numpy_to_tensor_wrapper.__repr__c                 O   s   | j ||}t|S r/   )r   r  r   rm   rn   rZ   r3   r3   r4   rU    s    z numpy_to_tensor_wrapper.__call__N)r   r   ra   r   r  rU  r3   r3   r3   r4   r    s   r  c                 C   sF   t | tjrt| |}t|S t | tjrBtt| |}t|S d S r/   )r   r  r  r  r  rb   r  )r   rH  rZ   r3   r3   r4   numpy_attr_wrapper  s    
r  c                   @   s.   e Zd ZdZedddZdd Zdd Zd	S )
numpy_method_wrapperzgConvert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor.methodc                 C   s   || _ d| j  | _d S r  )r  r   )r   r  r3   r3   r4   r     s    znumpy_method_wrapper.__init__c                 C   s   d| j  dS )Nz<Wrapped method <original r  r  r   r3   r3   r4   r    s    znumpy_method_wrapper.__repr__c                 O   sD   |d }t |tjrt|}t|| j}||dd  |}t|S Nr   r   )r   rb   r  r  r  r  r  r  )r   rm   rn   r   Zmethod_callablerZ   r3   r3   r4   rU    s    
znumpy_method_wrapper.__call__N)r   r   ra   r   r>   r   r  rU  r3   r3   r3   r4   r    s   r  c                   @   s6   e Zd ZdZedef dddZdd Zdd	 Zd
S )numpy_operator_wrapperzQImplements dunder methods for tnp.ndarray via functions from the operator library.)r   c                 C   s   || _ d|j | _d S r  )r   r   )r   r   r3   r3   r4   r     s    znumpy_operator_wrapper.__init__c                 C   s   d| j  dS )Nz<Wrapped operator <original r  )r   r   r3   r3   r4   r    s    znumpy_operator_wrapper.__repr__c                 O   s(   |rt dd |D }| j| }t|S )Nc                 s   s(   | ] }t |tjrt|n|V  qd S r/   )r   rb   r  r  r  r.  r3   r3   r4   rA     s    z2numpy_operator_wrapper.__call__.<locals>.<genexpr>)r)  r   r  r  r3   r3   r4   rU    s    
znumpy_operator_wrapper.__call__N)	r   r   ra   r   r   r   r   r  rU  r3   r3   r3   r4   r    s   r  c                 C   s   t | ts| S | jrg }|  D ]4}t |tjrJ||jj	|jj
 q || q g }|  D ]4}t |tjr||jj	|jj
 qb|| qbn|  }|  }tj||| j| j| jd}|  |S )N)rg  rr  r`  )r   r   Z_has_symbolic_sizes_stridesru  rb   ZSymIntrj   r  r  Z	size_hintexprrp  Zempty_stridedrg  rr  r`  Zzero_)r~   ru  r  rp  rd  r3   r3   r4   defake  s0    
r  c                 C   s   dd l }| |jjjkS rJ   )Ztorch.utils.checkpointr  
checkpoint)r   rb   r3   r3   r4   is_utils_checkpoint  s    r  c                  K   sB   dd l m  m} ddlm} |j}tjjj	r4|j
}|j|f| S )Nr   r   ) TorchHigherOrderOperatorVariable)Ztorch._higher_order_ops.wrapZ_higher_order_opswrapZvariables.higher_order_opsr  Ztag_activation_checkpointrb   Z
_functorchr   Zfunctionalize_rng_opsZwrap_activation_checkpointmake)optionsZhigher_order_opsr  Zactivation_checkpoint_opr3   r3   r4   build_checkpoint_variable  s    
r  c                 C   s8   ddl m} | }| dkrn| dkr0|r0t }nd}|S )Nr   )is_dynamo_supportedrG  r  F)r  r  r*   )Zdevice_typer  Zcompile_supportedr3   r3   r4   is_compile_supported	  s    r  )r>   offsetrJ  c                 C   s$   |  d}t|d| jd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)r>   r  Zas_utf8r3   r3   r4   _fix_offset	  s    
r  c                   @   s.   e Zd ZU eed< eed< eed< eed< dS )_Anchorsleft_end_linenoleft_end_offsetright_start_linenoright_start_offsetNr  r3   r3   r3   r4   r  )	  s   
r  )segmentrJ  c                    s  t jdkstddl}z|d|  d }W n tk
rB   Y dS X t|jdkrVdS | d  fdd	} fd
d fdd} fdd}|jd }t	||j
r|j}t	||jrtt|jjd }|||jj}	||	\}}	 | |	  }
 s|
dkr8|
dkr(|||	\}}	q|||	\}}	q|	d }|t | k rz | |  }
 sz|
dkrz|d7 }t||	||S t	||jrtt|jjd }|||jj}||\}} | | dkr|||\}}qtt|jd }|||j}t||||S t	||jrtt|jjd }|||jj}||\}} | | dkrr|||\}}qNtt|jd }|||j}t||||S dS )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      r   Nz(
z
)r   r:   c                    s   t  |  |S r/   )r  )linenor  linesr3   r4   	normalizeM	  s    z-_extract_anchors_from_expr.<locals>.normalizec                    sR   | t  k r*|t  |  kr*d}| d7 } q | t  k rF|t  |  k sJt| |fS r  r   r)  r  colr  r3   r4   next_valid_charR	  s
    
 z3_extract_anchors_from_expr.<locals>.next_valid_charc                    s>   |d7 }| |\} }| t  k r2|t  |  k s6t| |fS rG   r
  r  r  r  r3   r4   	incrementZ	  s     z-_extract_anchors_from_expr.<locals>.incrementc                    sB   d}| d7 } | |\} }| t  k r6|t  |  k s:t| |fS r  r
  r  r  r3   r4   nextlinea	  s
     z,_extract_anchors_from_expr.<locals>.nextliner   z)\#z\#r  r  )r   r   r)  astparseSyntaxErrorr   bodyrQ  r   Exprr[   BinOpr   r>  left
end_linenoend_col_offsetisspacer  	SubscriptCallrw   )r  r  treer	  r  r  Z	statementr  Z
cur_linenoZcur_colchZ	right_colZleft_linenoZleft_colZright_linenor3   r  r4   _extract_anchors_from_expr3	  sh    

 
r  )r   instrJ  c                 C   s@  |j dk	st|j jdkrdS t| j|j j }|j jdkrD|S |j jdks\|j j	dkr`|S t
||j j}d}d}g }|j j|j jkrt
||j j	}||| }|d| d||    n||d d }|d| dt||    t| j|j j }t
||j j	}t|j jd |j jD ]V}t| j| }	||	d 7 }t|	t|	  }
|d|
 dt|	|
    q(||d| 7 }t|t|  }
|d|
 d||
    d}zt|}W n tk
r   Y nX |dkr dd |D }nd	d |D }|jd
kr(| j|7  _|jd
krB| j|7  _tt|D ]}tt|| D ]|}||jk rvqb||jkr||jk rqb||jkr||jkrqb||jkrqb|| | dkrbd|| |< qbqNdd |D }d}tt|D ]8}|t| j|j j|  d 7 }||| d 7 }q|S )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  rU   ~r:   r   c                 S   s   g | ]}| d dqS )r!  ^)r%  r?   markerr3   r3   r4   r   	  s     z.get_instruction_source_311.<locals>.<listcomp>c                 S   s   g | ]}t |qS r3   )r   r#  r3   r3   r4   r   	  s     r   r"  c                 S   s   g | ]}d  |qS )r  r&  r#  r3   r3   r4   r   
  s     )Z	positionsr)  r  	linecachegetliner9  rstripr  
col_offsetr  r  rj   r   r|  lstripr  r   r  r  r  )r   r   
first_lineZstart_offset
end_offsetr  markers	last_liner  line
num_spacesanchorsZmutable_markersr  rz  r  r3   r3   r4   get_instruction_source_311	  s     "
r1  c                 C   s   t | tjrt| dd S d S )NZ_dynamo_static_input_type)r   rb   r  r  r;  r3   r3   r4   get_static_address_type
  s    r2  c                 C   sD   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}| ||kS r/   )	rb   r  	GeneratorZ	get_stateZdefault_generatorr  r  Z	set_stater  )r[   getterssettersr3   r3   r4   is_rng_state_getter_or_setter
  s    r6  c                 C   s&   t | tjo$| jdko$| jjtjjkS )N__get__)	r   r  r   r   __self____objclass__rb   r  Z_TensorBaser   r3   r3   r4   is_tensor_base_attr_getter0
  s
    r:  c                 C   s
   t | dS )N__torch_function__)rj  r   r3   r3   r4   is_torch_function_object8
  s    r<  z,torch._dynamo.variables.base.VariableTracker)r  rJ  c                 C   sT   ddl m}m} ddlm} t| |r*dS t| |r>||  t| |oRt| jdS )Nr   )LazyVariableTrackerUserDefinedObjectVariable)TensorWithTFOverrideVariableTr;  )	Ztorch._dynamo.variablesr=  r>  Z&torch._dynamo.variables.torch_functionr?  r   Zrealizerj  r[   )r  r=  r>  r?  r3   r3   r4   has_torch_function<
  s    


 r@  c                 C   sD   d }d }t jj  }r2| |jkr2|j|  }|j}|j| d||dS )NF)Zstatic_shapessymbolic_contextsource)rb   rc   r$   rd   Ztensor_to_contextZtensor_sourceZfrom_tensor)r  r  rA  rB  Ztracing_contextr3   r3   r4   to_fake_tensorL
  s    

   rC  c                 G   s8   |D ]}t | |rt| |  S qt|  d| dS )zX
    Return the first available attribute or throw an exception if none is present.
    z% does not has any of the attributes: N)rj  r  r)  )r   attrsattrr3   r3   r4   get_first_attrY
  s    
rF  c              	   c   s8   dd }| r.t jj|}|V  W 5 Q R X nd V  d S )Nc                 S   s   dd }t j| |dddS )Nc                 S   s(   t jjjd d  d7  < t j| |S )Ncompiled_autogradZcompilesr   )rb   r  r  r,   Z	_inductorcompile)Zgm_Zexample_inputs_r3   r3   r4   inner_compilerg
  s    zKmaybe_enable_compiled_autograd.<locals>.compiler_fn.<locals>.inner_compilerT)backendZ	fullgraphZdynamic)rb   rH  )r  rI  r3   r3   r4   compiler_fnf
  s    z3maybe_enable_compiled_autograd.<locals>.compiler_fn)rb   r  rG  enable)Zshould_enablerK  r  r3   r3   r4   maybe_enable_compiled_autogradd
  s
    rM  c                  C   s   G dd dt } t|  S )Nc                   @   s   e Zd ZdS )z*invalid_removeable_handle.<locals>.InvalidN)r   r   ra   r3   r3   r3   r4   Invalidv
  s   rN  )r   r   )rN  r3   r3   r4   invalid_removeable_handlet
  s    rO  c                 C   s>   t | tjjs| S t | tjjr$| S | j| j}| j|_|S r/   )	r   rb   r   r  r"   rm  r\  __new__rO  )r%  proxyr3   r3   r4   nn_module_proxy
  s    rR  c                       s$   e Zd Z fddZdd Z  ZS )	GmWrapperc                    s   t    || _|| _d S r/   )rY  r   r  spec)r   r  rT  r[  r3   r4   r   
  s    
zGmWrapper.__init__c                 G   s   t |}| jt|| j S r/   )r   r  r  Ztree_unflattenrT  rT  r3   r3   r4   r`   
  s    zGmWrapper.forward)r   r   ra   r   r`   r]  r3   r3   r[  r4   rS  
  s   rS  rX  c                    sF   t |\}}|t| || dd t| jjD  fdd}|S )z
    Mutate inputs so that they are flat and wrap gm such that it
    accepts those inputs.  This is needed for graphs that take
    bumpy inputs.
    c                 S   s,   g | ]$\}}|j d kr|jddr|qS )r  Z	steal_argF)r   r  re   )r?   r  r  r3   r3   r4   r   
  s   
 z(flatten_graph_inputs.<locals>.<listcomp>c                     s(   t j|  }D ]}| |   q |S r/   )r  Zarg_tree_leavesrK   )rm   Z	flat_argsr  Zcompiled_fnZidx_to_stealr3   r4   wrapper
  s    
z%flatten_graph_inputs.<locals>.wrapper)r  Ztree_flattenrS  	enumeraterY  r   )r  inputsZ
compile_gmrT  rV  r3   rU  r4   flatten_graph_inputs
  s    
rY  c                 C   s*   t | tjjrt| dsg S | jdg S )Nr  locals_to_steal)r   rb   r"   rm  rj  r  re   )Zmaybe_gmr3   r3   r4   get_locals_to_steal
  s    r[  c                 C   s   || j d< d S )NrZ  )r  )r  rZ  r3   r3   r4   set_locals_to_steal
  s    r\  c                   @   s   e Zd Zdd Zdd ZdS )Litc                 C   s
   || _ d S r/   r  )r   r  r3   r3   r4   r   
  s    zLit.__init__c                 C   s   | j S r/   r^  r   r3   r3   r4   r  
  s    zLit.__repr__N)r   r   ra   r   r  r3   r3   r3   r4   r]  
  s   r]  warn_once_cachec                 C   s,   | t krd S t |  tj| |d d d S )Nr   )
stacklevel)r_  r   warningswarn)r*  r`  r3   r3   r4   	warn_once
  s    
rc  )NNT)r>   F)N)F)r   )F)T)F)FFF)FFF)r   (^  atexitr0   r   rk  rF  rn  r  r  r  r  r  rD   r%  r   rJ  r  r   r  r   rh  	threadingri   r  r   ra  r   r   r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   Zutils.hooksr   r  r   ModuleNotFoundErrorZtorch._loggingrb   Ztorch._numpyZ_numpyr  Ztorch._guardsr   r   r  r   ZfftZlinalgr  r   
ModuleTyper=  ZNP_TO_TNP_MODULEr   r  r   r    r!   rC   r  Ztorch._functorch.configZ%torch.fx.experimental.symbolic_shapesZtorch.utils._pytreer  Z_pytreer  r"   Ztorch._dispatch.pythonr#   r$   Ztorch._subclasses.meta_utilsr%   Ztorch._utils_internalr&   Ztorch.fx._utilsr'   r(   Ztorch.nn.modules.lazyr)   Ztorch.utils._tritonr*   r+   r1   r,   r>   r-   Ztroubleshooting_urlZnnmodule_doc_urlZnnmodule_doc_url_msgr   r   r   r.   r2   r7   rS  Ztimer_counterrB   rH   rI   rL   rM   rN   rT   r\   r_   r|   r   registerr   ZFloatTensorr  ZDoubleTensorr  doubleZ
HalfTensorr  ZhalfZBFloat16TensorrL  Z
ByteTensorr  Z
CharTensorr   Z
LongTensorr  longZ	IntTensorr  r>  ZShortTensorr   shortZ
BoolTensorr?  Ztensortype_to_dtyper   r   r   r   r   r   r   r   ZGraphr   r   r   r   r   r   r   ParamSpecArgsParamSpecKwargs	ParamSpecTypeVarTypeVarTupleTypeAliasTyper   r   r  r  r  r
  r  r  r  r#  r&  r'  r+  r7  r  r8  rg   Z!DEFAULT_COMPILATION_METRICS_LIMITrL  rC  rh   rM  rN  rO  rP  rR  rX  re  ri  r{  r  r  r  r  r  r  r  r  r  r  r  r  r  complexbytesrl   Ellipsisr\  CodeTyperr  rg  Zmemory_formatrn  r  Ztritonr   languager  r  r  r  r  r  r  r   r   r  rO   r  r   r  r  r  __length_hint__Ztuple_iterator_lenobjectrP  r  r  r  r  r  Z	iter_nextr  r  r  r  r  r  r  r  r  r'  ZGLOBAL_KEY_PREFIXZtorch._subclassesr(  r+  r-  r/  r  r2  rR  rS  Zorig_code_mapr   rT  rU  Zseen_code_maprV  rt  r   rv  rw  r  ry  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  Zall_hook_namesr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  Instructionr1  r2  r6  r:  r<  r@  rC  rF  rM  rO  rR  r   r  rS  rm  rY  r[  r\  r]  r   r_  rc  r3   r3   r3   r4   <module>   s   L
     

P$
 
 
 
    
 
 
 	!
	
 



J



	
	 





	)

!



 m
"c


}
	
1
'
	
  $  	 	y l 