U
    9%e                    @   s  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mZmZmZm Z  zd dl!Z"W n e#k
r&   dZ"Y nX d dl$Z%d dl&m'Z( d dl)m*Z* d dl$m+Z+ ddl,m-Z- e"re"e"j.e"j/e"j0fZ1e"e(e"j.e(j.e"j/e(j/e"j0e(j0iZ2ni Z1i Z2d dl3Z3d dl%Z%d dl4Z%d dl5Z%d d	l%m6Z6 d d
l7m8Z8 d dl9m:Z:m;Z; d dl<m=Z= d dl>m?Z? e@ejAZBdZCdZDdeD dZEeFeGZHeI ZJeI ZKeL aMdd ZNdd ZOd aPdd ZQdd ZRd aSdd ZTdd ZUdddZVdd"d#ZWe jXd$d% ZYe%jZe%j[e%j\fe%j]e%j^e%j_fe%j`e%jae%jbfe%jce%jdfe%jee%jffe%jge%jhfe%jie%jje%jkfe%jle%jme%jnfe%joe%jpe%jqfe%jre%jsfi
ZtG d&d' d'Zueu Zvd(d) Zwd*d+ Zxd,d- Zyd.d/ Zzd0d1 Z{d2d3 Z|e6j}d4d5d6Z~d7d8 Zd9d: ZG d;d< d<Zd=d> Zd?d@ ZdAdB ZdCdD ZdEdF ZdGdH ZdIdJ Ze	dKdLdM ZddNdOZdPdQ ZejG dRdS dSZejG dTdU dUZG dVdW dWeZe e_dXdY ZddZd[d\Zd]d^ Zed_d` Zdadb ZddcddZdedf Zdgdh Zdidj Ze	ddkdl Zdmdn Zd dodpZdqdr Zedsdtdu Zdvdw Zdxdy Zdzd{ Zd|d} Zd~d Zdd Zee  ZeeI  Zeee ZejZejZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd dlmZmZ dd Zdd Zdd Zdd!dd!dd!d!eHjfddZdd Zejdd Ze Ze@ešZeŃ Ze ZG dd dZe	ddd Zdd Zdd Zdd Zdd Zdd ZedddZdd ZejdddZedddZedddZG dd dejփZedddZe e%jef esdeesef dddĄZڐdddƄZddȄ Zddʄ Zdd̄ ZddgZddgZddddgZee e ZdddքZddd؄Zddڄ Zdd܄ ZG ddބ dރZdd ZG dd dZG dd dZdd Zdd Zdd Zdd ZeenendddZejG dd dZeee dddZejejedddZdd Zdd ZdS (      N)contextmanager)	lru_cachewraps)AnyDictOptionalTupleUnion)detect_fake_mode
LazyString   )config)fx)enable_python_dispatcher)
FakeTensoris_fake)LazyModuleMixin)tree_mapz<https://pytorch.org/docs/master/compile/troubleshooting.htmlz6https://pytorch.org/docs/master/compile/nn-module.htmlzSee z& for more information and limitations.c              
   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row r   R/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/_dynamo/utils.py	<genexpr>Z   s    ztabulate.<locals>.<genexpr>)tabulateImportErrorr   	itertoolschain)rowsr   r!   r   r   r   r!   T   s    
r!   c                    s   t   fdd}|S )Nc                     s    j tt d }t }|  |j f| |}|  td j  dtt d t	
|}|t	jjd |t	jjd || |S )Nz.profilez### Cprofile for z iter z ###   )__name__nexttimer_countercProfileZProfileenableZruncalldisableprintpstatsZStatsZ
sort_statsZSortKeyZTIMEZprint_statsZ
CUMULATIVEZ
dump_stats)argskwargsZdatafnZprofretvalZpsfuncr   r   profile_wrapper`   s    

z(dynamo_profiled.<locals>.profile_wrapperr   )r3   r4   r   r2   r   dynamo_profiled_   s    r6   c                   C   s   t d a d S Nr   )
curr_framer   r   r   r   increment_framex   s    r9   c                   C   s   t   t  dad S Nr   )frame_phase_timingclearcompilation_time_metricsr8   r   r   r   r   reset_frame_count~   s    r>   c                 C   s   t | 7 a d S N)op_count)Zcntr   r   r   increment_op_count   s    rA   c                  C   s   d} i }t  D ]@}| D ]2\}}| |7 } ||kr>|||< q||  |7  < qqd}| D ]"\}}| d| dt|d }q^t| d S )Nr   zTIMING: :   )r;   valuesitemsroundr-   )totalZtotal_by_keyZtimingskeyZtimingoutvaluer   r   r   print_time_report   s    
rL   c                    s    fdd}| r|| S |S )Nc                    s   t   fdd}|S )Nc               	      s    j }|tkrg t|< tj| d$ t } | |}t | }W 5 Q R X t| | rtt}|t	kr|i t	|< t	| kst
d d| |t	| < |S )Nz (dynamo_timed)zDuplicate phase name z for frame )__qualname__r=   torchZprofilerZrecord_functiontimeappendr   r8   r;   AssertionError)r/   r0   rI   t0rZ
time_spent	frame_key)r3   
phase_namer   r   time_wrapper   s$    

z>dynamo_timed.<locals>.dynamo_timed_inner.<locals>.time_wrapperr5   )r3   rV   rU   r2   r   dynamo_timed_inner   s    z(dynamo_timed.<locals>.dynamo_timed_innerr   )Zoriginal_functionrU   rX   r   rW   r   dynamo_timed   s    rY   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?   r   xr   r   r   <lambda>       zcompile_times.<locals>.<lambda>c                    s     r|t | S dt|| S )Nr   )sumr   r   )rE   item_fn)	aggregater   r   fmt_fn   s    zcompile_times.<locals>.fmt_fnr   c                    s$   g | ]}| t | d d dfqS )c                 S   s   | dS )Nz.4fr   rZ   r   r   r   r\      r]   *compile_times.<locals>.<listcomp>.<lambda>r_   )r=   r   kra   r   r   
<listcomp>   s   z!compile_times.<locals>.<listcomp>z!TorchDynamo compilation metrics:
)FunctionzRuntimes (s)r   csvc                    s   g | ]} |d d dqS )c                 S   s   | dS )Nz.6fr   rZ   r   r   r   r\      r]   rb   rc   r   )r   vrf   r   r   rg      s   N)r=   r!   rE   listkeys)reprr`   r%   rJ   rE   r   r   )r`   ra   r   compile_times   s    

rn   c                   C   s   t tddd d S )Nr   T)rm   r`   )loginforn   r   r   r   r   dump_compile_times   s    rq   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)selfrt   r   r   r   __init__	  s    z DuplicateWarningChecker.__init__c                 C   s   t  | _d S r?   )collectionsOrderedDictsetrv   r   r   r   ru     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)rz   move_to_endr   verboselenrt   popitemrv   rI   r   r   r   add  s    

zDuplicateWarningChecker.addN)rs   )r'   
__module__rM   rw   ru   r   r   r   r   r   rr     s   
rr   c                  C   s>   t jdddk} | r6tjjtjtjtjdd t S t	
 S )NZTORCH_COMPILE_DEBUG01T)ZdynamoZaotZinductorZoutput_code)osenvirongetrN   _loggingZset_logsloggingDEBUGadd_file_handler
contextlib	ExitStack)Zcompile_debugr   r   r   setup_compile_debug  s    r   c                   C   s   t   d S r?   )graph_break_dup_warning_checkerru   r   r   r   r   reset_graph_break_dup_checker.  s    r   c                     sn   t jt d} t j| s&t |  tt j| d td	  t
 }| fdd |S )NZtorchdynamoz	debug.logztorch._dynamoc                      s
     S r?   removeHandlerr   Zlog_file_handlerloggerr   r   r\   <  r]   z"add_file_handler.<locals>.<lambda>)r   pathr   get_debug_direxistsmakedirsr   FileHandler	getLogger
addHandlerr   r   callback)log_path	exitstackr   r   r   r   2  s    


r   c                     sR   t  } tjd k	rNttj t D ]"  |  fdd q&| S | S )Nc                      s
     S r?   r   r   r   r   r   r\   F  r]   z setup_log_file.<locals>.<lambda>)	r   r   r   Zlog_file_namer   r   Zget_loggersr   r   )r   r   r   r   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_nametyper'   co_firstlineno)exccoder   r   r   gen_record_file_nameL  s    r   c              	   C   s~   zTt j| rtd|  n6t jt j| dd t| d}|| W 5 Q R X W n$ t	k
rx   tj
d| dd Y nX d S )Nz9Unable to write execution record %s; file already exists.T)exist_okwbz#Unable to write execution record %sr   )exc_info)r   r   r   ro   warningr   dirnameopendump	Exceptionerror)filenameZexec_recordfr   r   r   write_record_to_fileQ  s     r   )gc                 C   s&   d}| j D ]}d|jkr
|d7 }q
|S )Nr   callr   )nodesop)r   cnr   r   r   count_calls_  s
    


r   c                 C   s   | S r?   r   rZ   r   r   r   identityg  s    r   c                  O   s   d S r?   r   r/   r0   r   r   r   nothingk  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?   )dictrE   refsr{   r   r   r   rw   r  s    zExactWeakKeyDictionary.__init__c                 C   s   | j t| S r?   )rE   idr   r   r   r   __getitem__v  s    z"ExactWeakKeyDictionary.__getitem__Nc                 C   s   | j t||S r?   )rE   r   r   )rv   rI   defaultr   r   r   r   y  s    zExactWeakKeyDictionary.getc                 C   s   t || jkS r?   )r   rE   r   r   r   r   __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idxrv   r   r   r\     r]   z4ExactWeakKeyDictionary.__setitem__.<locals>.<lambda>)r   r   weakrefr   rE   )rv   rI   rK   r   r   r   __setitem__  s    
z"ExactWeakKeyDictionary.__setitem__c                 C   s(   || j kr| j |= || jkr$| j|= d S r?   )rE   r   )rv   r   r   r   r   r     s    

z!ExactWeakKeyDictionary._remove_idc                 C   s   | j   | j  d S r?   )r   r<   rE   r{   r   r   r   r<     s    
zExactWeakKeyDictionary.clear)N)r'   r   rM   __doc__rw   r   r   r   r   r   r<   r   r   r   r   r   o  s   
r   c                 C   s(   t |tttfrt| |kS t| |kS )zisinstance() without subclasses)
isinstancetuplerk   rz   r   )objZallowed_typesr   r   r   istype  s    r   c                 C   s,   t jdk rt| tjS t| tjtjfS d S )N)   	   )sysversion_infor   typing_GenericAliasZ_SpecialGenericAliasZ_UnionGenericAliasrK   r   r   r   	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   r   r   r   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   r   r   r   is_numpy_float_type  s    r   c                 C   s   t sdS t| t jS r   )r   r   ndarrayr   r   r   r   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)	rN   Tensornn	Parameterr   Ztraceable_tensor_subclasses_subclassesr   r   )r   Ztensor_listr   r   r   istensor  s    r   c                 C   s
   t | tS r?   )r   r   modr   r   r   is_lazy_module  s    r   rs   c                  G   s   t |   d S r?   )r-   )r/   r   r   r   
print_once  s    r   c                    s,   |   fdd}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?   r   r   rZ   r   r   r     s    zmake_cell.<locals>.fr   r   )r   __closure__rQ   )valr   r   rZ   r   	make_cell  s    r   c                 C   s   z.t dd | D }dd | D }||fW S  tk
r } zBddlm} ddlm} |d||   d	|t|   |W 5 d }~X Y nX d S )
Nc                 s   s   | ]}|  V  qd S r?   Zas_proxyr   argr   r   r   r      s     z$proxy_args_kwargs.<locals>.<genexpr>c                 S   s   i | ]\}}||  qS r   r   )r   rI   r   r   r   r   
<dictcomp>  s      z%proxy_args_kwargs.<locals>.<dictcomp>r   unimplemented)typestrzcall_function args: rB   )	r   rF   NotImplementedErrorr   r   Zvariables.baser   rk   rE   )r/   r0   Z
proxy_argsproxy_kwargser   r   r   r   r   proxy_args_kwargs  s    
r   c                   @   s   e Zd ZU 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 ed< ee ed< dS )CompilationMetricsrT   r   co_filenamer   Z
cache_sizeZguard_countZgraph_op_countZgraph_node_countZgraph_input_countZentire_frame_compile_time_sZbackend_compile_time_sZfail_reasonN)r'   r   rM   r   __annotations__intr   floatr   r   r   r   r     s   
r   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scopenamec                 G   s   t  jd8  _| j| j= d S r7   )CleanupManagercountr  r  )rv   r/   r   r   r   __call__  s    zCleanupHook.__call__c                 C   s,   || kst t jd7  _|| |< t| |S r7   )rQ   r  r  r  )r  r  r   r   r   r   create  s    zCleanupHook.createN)r'   r   rM   r   r   r   r   r   r  staticmethodr  r   r   r   r   r    s   
r  c                       s    e Zd ZdZ fddZ  ZS )r  r   c                    s&   | j | D ]
}|  q
t | d S r?   )rE   superr   )rv   r   hook	__class__r   r   r     s    zCleanupManager._remove_id)r'   r   rM   r  r   __classcell__r   r   r  r   r    s   r  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[   yr   r   r   clone_tensor$  s    r  dtypec             
      sx  t | tjjr| S  fdd}t F | jjdkrJ|| W  5 Q R  S tdd t| 	 | 
 D }| jrt|d f| }ntj|d  p| j| jd}|  |  d |   }|| 	 | 
 | zH||   | jr|| j | jr| jdk	rt| j d	|_W n* tk
rD   ||  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 )Nr  _dynamo_dynamic_indices)
rN   r  r  r  r  r  clone_inputhasattrr  copyr  r  r   r   torch_clone3  s    

z clone_input.<locals>.torch_cloneZxlac                 s   s   | ]\}}|d  | V  qdS )r   Nr   )r   shapestrider   r   r   r    B  s    zclone_input.<locals>.<genexpr>    )r  deviceNr  r  )r   rN   r   r   no_gradr!  r   r^   zipsizer  Zis_quantizedZempty_quantizedemptyr  Zdata_ptrZelement_sizeZas_strided_copy_r  r  r  r  r  r  RuntimeErrorr  r  r  )r[   r  r  Zneeded_sizeresultZcache_line_offsetr   r  r   r  ,  s>    
  r  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?   )r   r   rF   r   r   clone_inputsrN   r   rQ   r  rk   ranger   )example_inputsresrI   rK   ir   r   r   r)  _  s    
r)  c                  c   s   t jj 0 t t j } t j r8t t j }W 5 Q R X z
d V  W 5 t jj ( t j	|  t j r~t j	| W 5 Q R X X d S r?   )
rN   utilsZ_python_dispatchZ_disable_current_modesr  randomget_rng_statecudais_availableset_rng_state)	rng_statecuda_rng_stater   r   r   preserve_rng_stateq  s    


r6  c                 C   s&   t | tjjjtjjjtjjtjjfS r?   )	r   rN   jitZ_traceZTopLevelTracedModule_scriptZRecursiveScriptModuleZScriptFunctionZScriptModule)Zmodel0r   r   r   is_jit_model  s    r9  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)	r9  rN   r7  tracer   scriptro   	exceptionr   )modelr+  r~   r   r   r   torchscript  s    r>  c                 C   s(   zt | W S  tk
r"   Y d S X d S r?   )inspectgetfile	TypeErrorr   r   r   r   r@    s    r@  c                 C   s   t t| S )LTest if an object is a namedtuple or a torch.return_types.* quasi-namedtuple)is_namedtuple_clsr   rB  r   r   r   is_namedtuple  s    rE  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 )	rC  	__bases__Nr   torch.return_typesr   _make_fieldsF)
issubclassr   getattrr  rA  )clsbasesmoduler   r   r   rD    s    
rD  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steprI  c                   @   s   e Zd ZU eed< dS )z!namedtuple_fields.<locals>.MarkerindexNr'   r   rM   r   r   r   r   r   r   Marker  s   
rT  rG  Nr   r   )slicerJ  r   rQ   r  rI  dataclasses	dataclassr   r   r*  n_fieldsdirr   rK  rR  )rL  rT  r   fieldsr  r   r   r   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?   )rN   r"  r/  r3  r1  r2  _versionr&  )paramversionoriginal_valuer5  r4  saved_stater   r   restore  s    


z"checkpoint_params.<locals>.restore)rN   r"  r  r/  r0  r1  r2  r#   r$   
parametersbuffersrP   r\  )gmr]  rb  r   r`  r   checkpoint_params  s    

$	rf  c                 C   sh   t j rt jj}nt}|  t  t d t	 }t
|D ]}| | }|  q@t	 }||| fS )Ni9  )rN   r1  r2  synchronizer   gcZcollectZmanual_seedrO   perf_counterr*  )r=  r+  timesrg  rR   r   r(  t1r   r   r   timed  s    


rl  c                 C   s    t dd t|| dD S )Nc                 s   s   | ]}|j V  qd S r?   )Zis_cudar   r[   r   r   r   r      s     z check_is_cuda.<locals>.<genexpr>T)allr#   r$   rc  )re  r+  r   r   r   check_is_cuda  s    ro  r   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 rj   r   )r   r-  r   r   r   rg     s     z rot_n_helper.<locals>.<listcomp>zlambda ,z: ()Zrot_Z_helper)rQ   r*  reversedevalr   r'   )r   varsZrotatedfnr   r   r   rot_n_helper  s    "rx  c                 C   sZ   t | ttfrttt| S t| tjt	fpXt | t
jtttttt	d tt	t	tjtjfS r?   )r   r   	frozensetrn  r   is_safe_constantr   enumEnumr   typesCodeTyper   r  boolr   bytesrU  rN   r!  r  rp  r   r   r   rz    s"    rz  c                 C   s8   ddl m}m} t| |r"|  S t| |r4|  S | S )Nr   )ConstantVariableSymNodeVariable)	variablesr  r  r   Zevaluate_exprZas_python_constant)r   r  r  r   r   r   guard_if_dyn  s    

r  c                 C   s   t dd t| | D S )Nc                 s   s   | ]}|  V  qd S r?   )Zis_python_constantrm  r   r   r   r    *  s     z&check_constant_args.<locals>.<genexpr>)rn  r#   r$   rE   r   r   r   r   check_constant_args)  s    r  c                 C   sb   ddl m} ddlm} d}t| | D ],}t||rD|d7 }q,t|||fs, dS q,|dkS )Nr   )r  )UnspecializedPythonVariabler   F)Zvariables.constantr  variables.tensorr  r#   r$   rE   r   )r/   r0   r  r  Zunspec_countr[   r   r   r   check_unspec_python_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   rm  r  r   r   r    @  s   z+check_numpy_ndarray_args.<locals>.<genexpr>)r  r  anyr#   r$   rE   r   r   r  r   check_numpy_ndarray_args=  s    r  c                 C   sP   g }i }|D ]}| ||  q| D ]\}}|||| i q*||fS r?   )rP   Zas_specializedrF   update)txr/   r0   Zspecialized_argsZspecialized_kwargsr[   re   rj   r   r   r   specialize_args_kwargsF  s    r  c                 C   s   t | }tjj| |S r?   )
object_newrN   r   Modulerw   )rL  r   r   r   r   nn_module_newW  s    r  c                 C   s   t tj| dS r7   )	functoolsreduceoperatormul)itr   r   r   product]  s    r  c                 C   s   |   \}\}}|||  S r?   )
__reduce__)r  rR  r   r   rO  r   r   r   tuple_iterator_getitema  s    r  c                 C   s2   | j j}| j}|rdnd}| d| d| }|S )NLGz["z"].)r  r'   r  )rK   localr  r   r  Z
local_namer   r   r   	enum_reprf  s
    r  c                 C   s   dd |   D S )Nc                 S   s(   h | ] }t |tjjtjfrt|qS r   )r   rN   r   r   r   r   rd   r   r   r   	<setcomp>q  s     z%dict_param_key_ids.<locals>.<setcomp>rl   r   r   r   r   dict_param_key_idsp  s    r  c                 C   s   dd |   D S )Nc                 S   s$   h | ]}t |tjjtjfs|qS r   )r   rN   r   r   r   rd   r   r   r   r  w  s     z"dict_const_keys.<locals>.<setcomp>r  r   r   r   r   dict_const_keysv  s    r  c                   s:   t dd | D r0 fdd| D  dd}n| }|S )Nc                 s   s   | ]}t |tjV  qd S r?   )r   r{  r|  rd   r   r   r   r    }  s     z'dict_const_keys_repr.<locals>.<genexpr>c                    s,   h | ]$}t |tjr t| d nt|qS )r  )r   r{  r|  r  rm   rd   r  r   r   r    s     z'dict_const_keys_repr.<locals>.<setcomp>' )r  replace)Z
const_keysr  Zconst_keys_strr   r  r   dict_const_keys_repr|  s     r  c                 C   s   dt |  S )NZ__dict_key_)r   )rI   r   r   r   global_key_name  s    r  )FakeTensorModeUnsupportedFakeTensorExceptionc              
   C   s^   z|  W S  t k
rX } z2ddlm} d|j d}t| |||W 5 d }~X Y nX d S )Nr   r   zUnsupported: z with fake tensor propagation.)r  r   r   reasonro   r   )rw  r   r   msgr   r   r   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?   )r  deepcopyr   rB  r   r   r\     r]   z)deepcopy_to_fake_tensor.<locals>.<lambda>)rN   r   fake_tensorZFakeCopyModer  )r   	fake_moder   rB  r   deepcopy_to_fake_tensor  s    r  c                 C   s   t t t | | S )z+
    Calculate root mean squared error
    )rN   sqrtZmeanZsquare)r   r,  r   r   r   rmse  s    r  g-C6?Tc
                    sT  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 trLt tstt t kstdt  d	t  t D ]@}
t|
 |
 |
  	d

sd|
  dS qdS t tjrt tjjrntt tjjrtjrjst  t tjstdt dt rJjjkrdjj dS jtjkrJrdS tjjtjdjtjd		d}|sFd |S  rʈ tj tjtj		ddrdS tjjjddd}|dk rt d|! " #  |dkS s܈jtj		drdS jtj$krt%# }t%# }d}& dk snj'dkrdj(d j(d   krbdksnn 	dkrrd}||| 	d  k}|sd||)  |S rdS d 	 dS nt t*t+tdttj,frrdS k}|sd!t |S t t-r>t.j/		d"}|s:d#	 |S t0sRt1rrtt0stt1st# ttkok}|sd$ |S t2rttkott3t3 	d

S tj4d%kr<ttkstt
 	f
d&dj5 D S t6d'tj4 dS )(z-Check correctness to see if ref and res matchNztype mismatch rB   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_fpr  relax_numpy_equalitytolr   r   r      s   zsame.<locals>.<genexpr>zkeys mismatch z == r  r  r  r  r  r  r  zAccuracy failed for key name %sTzdtype mismatch %s, %sr  )ZatolZrtolr  z+Accuracy failed: uint8 tensor did not matchr   gư>)dimZepsgGz?zSimilarity score=%sg       @i     rq  r   g{Gz?g      @g      $@z4RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%sz+Accuracy failed: allclose not within tol=%szAccuracy failed (%s): %s != %s)Zrel_tolZabs_tolz1Accuracy failed (float): %s != %s (within tol=%s)z!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 )r  N)r  rK  )r   rI   
r  r  r  fp64_refr  r  r   r  r,  r  r   r   r    e  s   zunsupported type: )7r   rk   r   rN   r   ZParameterListSizerQ   r   r   rn  r#  r   rz   rl   sortedr  r   r   r   Z	is_sparseZto_denser  r  Zallclosetor   flattenr   Z
functionalZcosine_similarityro   r   cpudetachitemr   r  Znumelndimr  r$  r   r   r!  r  mathiscloser   r   r   	as_tensorr'   __dict__r'  )r   r,  r  r  r  r  r  r  r  r  re   rS   ZscoreZ	ref_errorZ	res_error
multiplierZpasses_testr   r  r   r    s(   *(


*

 

	
   
r  c                 C   s,   | j dd }d| j d| d| j dS )N/rq  r  z' (rC   rs  )r   splitr   r   )r   Zshort_filenamer   r   r   format_func_infox  s    r  c                  c   s&   t j} tjt _z
d V  W 5 | t _X d S r?   )r   cache_size_limitr   rt   )Zpriorr   r   r   disable_cache_limit}  s
    
r  c                   @   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| _dd | _d S )Nr   c                   S   s   t  S r?   )r  r   r   r   r   r\     r]   z*CompileProfiler.__init__.<locals>.<lambda>)frame_countr@   Zbackend_ctx_ctorr{   r   r   r   rw     s    zCompileProfiler.__init__)re  c                 C   s:   |  j d7  _ |jjD ]}d|jkr|  jd7  _q|jS )Nr   r   )r  graphr   r   r@   forward)rv   re  r+  noder   r   r   r    s
    
zCompileProfiler.__call__c                 C   s   t j| _dt _| S )NT)r   report_guard_failuresold_report_guard_failurer{   r   r   r   	__enter__  s    zCompileProfiler.__enter__c                 C   s   | j t_d S r?   )r  r   r  )rv   typr   	tracebackr   r   r   __exit__  s    zCompileProfiler.__exit__c                 C   s   dt iS )Nguard_failures)r  r{   r   r   r   get_metrics  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 )Nr  c                    s   t  |  S r?   )r   r   gfr   r   num_recompiles  s    z.CompileProfiler.report.<locals>.num_recompilesc                    s   d dd  |  D S )Nr   c                 S   s   g | ]}t |qS r   )r   rm  r   r   r   rg     s     zECompileProfiler.report.<locals>.recompile_reasons.<locals>.<listcomp>r   r  r  r   r   recompile_reasons  s    z1CompileProfiler.report.<locals>.recompile_reasonsc                    s"   g | ]}t | ||gqS r   )r  r   r   )r  r  r   r   rg     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 r   r   )r   r  Zgraph_breaksr   r   rg     s     zFCompileProfiler.report.<locals>.graph_break_report.<locals>.<listcomp>zGraph Break ReasonZCountr   )countersr!   r   r   r  r   graph_break_report  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                    s   g | ]} |qS r   r   r  )r  r   r   rg     s     zHCompileProfiler.report.<locals>.recompilation_report.<locals>.<listcomp>rh   Z
RecompileszRecompile Reasonsr   zC

                    Set torch._dynamo.config.cache_size_limit to z/ to avoid being cache limited.
                )r   maxr!   textwrapdedent)Zmax_recompilesZrecomp_table)r  r  summarized_gfr   r   recompilation_report  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  r  r  )rv   Zmetricsr  r  reportr   )r  r  r  r  r   r    s$    zCompileProfiler.reportN)r'   r   rM   r   rw   rN   r   ZGraphModuler  r  r  r  r  r   r   r   r   r    s   r  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_namer   r   r   _get_debug_dir  s    
r  c                  C   s   t j} t| S r?   )r   Zdebug_dir_rootr  )Z
debug_rootr   r   r   r     s    r   c                    sz  ddl m}m}m}m}m} j}dd }tjj	ddd}	tjj
jjf|	\ t|  t|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zXjF t 4 t fddW  5 Q R  W  5 Q R  W S Q R X W 5 Q R X W n$ |k
rj    Y n tk
rt }
 z|
}|
jdk	r|
j}t|tj j!j"r|d|j#  nt|tj j!j$r|d|j#  ntt|tj j!j%r |d|j# d nNt|tjj&j'j(r&||j)dddn(t|tj*j+j,j-rN||j)|
jd
 |
|t.|
/|
j0dW 5 d}
~
X Y nX dS )z]
    Run the computation represented by `node` using fake tensors and return the result.
    r   )TorchRuntimeErrorr   Unsupported	UserErrorUserErrorTypec                 S   s   t | tjrt| st| S r?   )r   rN   r   r   rQ   )r   r   r   r   fake_wrapper  s    z$get_fake_value.<locals>.fake_wrapperr   c                 S   s
   | j d S )Nexample_value)metar  r   r   r   visit  s    zget_fake_value.<locals>.visitNcall_methodr   call_moduleZ_initialize_hookc                      s   t j S r?   )run_nodeoutputr   r/   r0   nnmoduler  r  r   r   r\   :  r]   z get_fake_value.<locals>.<lambda>zdata dependent operator: zdynamic shape operator: zunsupported operator: 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 APIsZconstrain_as_size_example)Z	case_name)1r   r  r   r  r  r  r   rN   r   Noder  map_argr/   r0   r   r   r   r   r  r  r  r   r  
nn_modulestargetr   r  Z_infer_parametersr   r  r'  	__cause__r   r  ZDataDependentOutputExceptionr3   ZDynamicOutputShapeExceptionZUnsupportedOperatorExceptionZexperimentalZsymbolic_shapesZGuardOnDataDependentSymNodeZCONSTRAIN_VIOLATIONr.  Z_sympyZvalue_rangesZValueRangeErrorr   with_traceback__traceback__)r  r  r  r   r  r  r  r   r  r  r   causer   r  r   get_fake_value  sn    

&"4    
r  c                 C   s  |j }z|dkr|j||W S |dkrFt|d |j|dd |W S |dkrf|dk	sZt|||W S |dkr|| |jW S |dkrd	|jkst|jd	 W S W n^ tk
 r } z>d
| d|j d| d| d	}t|t| 	|j
|W 5 d}~X Y nX t|dS )a  
    Runs a given node, with the given args and kwargs.

    Behavior is dicatated 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.
    Zcall_functionr  r   r   Nr  Zget_attrplaceholderr  zFailed running rB   z(*z, **z):
)r   r  rK  rQ   Zget_submoduler   r   r'  r   r  r  )tracerr  r/   r0   r  r   r   Zfn_strr   r   r   r  c  s$      ,r  c           
   
      s   ddl m}  j}| |kr"||  S | j}tjj| j| j	f fdd\}}|dkr j
j| j }t|svt|}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_valuer  r  r   r   r\     r]   z get_real_value.<locals>.<lambda>r  N)r   r  Zreal_value_cacher   rN   r   r  r	  r/   r0   Zoutput_graphr
  r  r   r  r  r  r'  r   r  r  )
r  r  r  cacher   r/   r0   Z	nn_module
real_valuer   r   r  r   r    s*    

(r  c                    s   ddl m   fdd}|  D ].\}}t|tjjr td| d|| q |  D ].\}}t|tjjrXtd| d|| qXd S )Nr   FakeTensorConfigc                    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)tr  r  r   r   stack_or_hint  s    z7assert_no_fake_params_or_buffers.<locals>.stack_or_hintzUnexpected fake buffer rB   zUnexpected fake param )	torch._subclasses.fake_tensorr  Znamed_buffersr   rN   r   r   rQ   Znamed_parameters)re  r  r  bufferr]  r   r  r    assert_no_fake_params_or_buffers  s       r  rB  c                 C   s   | j  d| j S )z9
    Returns the fully qualified name of the object.
    .)r   rM   rB  r   r   r   fqn  s    r!  c                 C   s   t jjjr| S |S d S r?   )rN   _dynamor   Zassume_static_by_default)Zcount1Zcount2r   r   r   ifdynstaticdefault  s    
r#  r   c                 C   sV   t ttj| 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)
r  r   listdirr   r   __file__endswith	importlibimport_moduler'   )r   r   r   r   r   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?  getattr_staticr   r}  FunctionTypeAttributeErrorr   r   r   r   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,  r   r.  rN   r   r  r0  )rK   Z
getattr_fnr   r   r   get_custom_getattr  s    
r1  c                   @   s   e Zd ZdZdZdZdS )TensorStaticReason   r  rD   N)r'   r   rM   	PARAMETER
NOT_TENSORNN_MODULE_PROPERTYr   r   r   r   r2    s   r2  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 )r2  r4  r5  r6  rQ   r7  r   r   r   tensor_static_reason_to_message  s    


r8  ZGuardSource)tensor	is_tensorguard_sourcereturnc                 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, esentially "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_shapesr2  r6  r   rN   r   r   Zforce_parameter_static_shapesr4  r5  )r9  r:  r;  r   r   r   tensor_always_has_static_shape  s    


r=  c                    s    fdd t  fddS )Nc                      s    d k	r d  S S d S )NrB   r   r   )maybe_idr  r   r   format_name  s    z+lazy_format_graph_code.<locals>.format_namec                      s$   t d   djjjjddS )Nz===== z =====
F)Zprint_output)_format_graph_coder  __code__r   Zprint_readabler   )r?  re  r   r   r\     s   
z(lazy_format_graph_code.<locals>.<lambda>r   )r  re  r>  r   )r?  re  r>  r  r   lazy_format_graph_code  s    rB  c                 C   s   d|  d| d| dS )NzTRACED GRAPH
 rB   r   r   )r  r   	graph_strr   r   r   r@  %  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   )r!   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 r   )r   r  r  r/   r0   )r   r   r   r   r   rg   3  s    z<lazy_format_graph_tabular.<locals>.inner.<locals>.<listcomp>opcoder  r  r/   r0   r   )
r!   r"   r   rB  r  r   r@  r  rA  r   )r!   Z
node_specsrC  fn_namere  r   r   inner*  s     z(lazy_format_graph_tabular.<locals>.innerr   )rF  re  rG  r   rE  r   lazy_format_graph_tabular)  s    rH  c                 C   s,   |  d| d| d| dt |   d
S )NrB   z line z 
r   )disBytecode)prefixr  r   line_nor   r   r   r   format_bytecode>  s    rM  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 jjjj}g }| o | o | }|s*|r4|t |s<|rF|t |rT|t g }|D ],}t	| |g }	|	D ]}
|	|
 }|
| qpq\|S r?   )rN   Z_Cr"  
eval_frame
reset_codeextendforward_hook_namesbackward_hook_namesstate_dict_hook_namesrK  rP   )r   check_forward_hookscheck_backward_hookscheck_state_dict_hooksrO  Zhook_dicts_to_checkZcheck_all_hooksZ	all_hooksZhook_dict_namehooks	hook_namer  r   r   r   nn_module_get_all_hooksM  s(    


rY  c                 C   s   t | |||d}t|S )zL
    Helper function to check if a module has any hooks attached to it.
    )rT  rU  rV  )rY  r  )r   rT  rU  rV  rW  r   r   r   nnmodule_has_hookso  s    	rZ  c                 C   sZ   t | tjrt| jS t | tjr.|   S t | t	t
frRt| dd | D S | S dS )z0Convert tensor and tnp.ndarray to numpy.ndarray.c                 s   s   | ]}t |V  qd S r?   )to_numpy_helperr   r   r   r   r   r      s     z"to_numpy_helper.<locals>.<genexpr>N)r   tnpr   r[  r9  rN   r   r  numpyr   rk   r   r   r   r   r   r[    s    
r[  c                 C   sT   t | tjrt| S t | tjr(| jS t | ttfrLt	| 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.c                 s   s   | ]}t |V  qd S r?   )numpy_to_tensorr\  r   r   r   r      s     z"numpy_to_tensor.<locals>.<genexpr>N)
r   r   r   rN   r  r]  r9  r   rk   r   r   r   r   r   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'   )rv   r   r   r   r   rw     s    z numpy_to_tensor_wrapper.__init__c                 C   s   d| j j dS )Nz<Wrapped function <original >>rb  r{   r   r   r   __repr__  s    z numpy_to_tensor_wrapper.__repr__c                 O   s   | j ||}t|S r?   )r   r_  rv   r/   r0   rJ   r   r   r   r    s    z numpy_to_tensor_wrapper.__call__N)r'   r   rM   rw   rd  r  r   r   r   r   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   rK  r_  rN   r   )r   r  rJ   r   r   r   numpy_attr_wrapper  s    
rf  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 ra  )ri  r'   )rv   ri  r   r   r   rw     s    znumpy_method_wrapper.__init__c                 C   s   d| j  dS )Nz<Wrapped method <original rc  rh  r{   r   r   r   rd    s    znumpy_method_wrapper.__repr__c                 O   sD   |d }t |tjrt|}t|| j}||dd  |}t|S Nr   r   )r   rN   r   r]  r   rK  ri  r_  )rv   r/   r0   r   Zmethod_callablerJ   r   r   r   r    s    
znumpy_method_wrapper.__call__Nr'   r   rM   r   r   rw   rd  r  r   r   r   r   rg    s   rg  c                   @   s.   e Zd ZdZe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 ra  )r   r'   )rv   r   r   r   r   rw     s    znumpy_operator_wrapper.__init__c                 C   s   d| j  dS )Nz<Wrapped operator <original rc  )r'   r{   r   r   r   rd    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   rN   r   r]  r   r   r   r   r   r      s    z2numpy_operator_wrapper.__call__.<locals>.<genexpr>)rQ   r   r_  re  r   r   r   r    s    
znumpy_operator_wrapper.__call__Nrk  r   r   r   r   rl    s   rl  c                 C   sp   t | ts| S | jr:dd |  D }dd |  D }n|  }|  }tj||| j| j| j	d}|
  |S )Nc                 S   s.   g | ]&}t |tjr&|jj|jjn|qS r   r   rN   ZSymIntr  Z	shape_envZ	size_hintexprr   sr   r   r   rg     s   
zdefake.<locals>.<listcomp>c                 S   s.   g | ]&}t |tjr&|jj|jjn|qS r   rm  ro  r   r   r   rg     s   
)r  r!  r  )r   r   Z_has_symbolic_sizes_stridesr$  r  rN   Zempty_stridedr  r!  r  Zzero_)r[   r$  r  r  r   r   r   defake  s(    
rq  c                 C   s   dd l }| |jjjkS r:   )Ztorch.utils.checkpointr.  
checkpoint)r   rN   r   r   r   is_utils_checkpoint  s    rs  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_opsrt  Ztag_activation_checkpointrN   Z
_functorchr   Zfunctionalize_rng_opsZwrap_activation_checkpointmake)optionsZhigher_order_opsrt  Zactivation_checkpoint_opr   r   r   build_checkpoint_variable  s    
rx  c                 C   sD   ddl m} | }| dkrn$| dkr<|r<ddlm} | }nd}|S )Nr   )is_dynamo_supportedr  r1  r   )
has_tritonF)rN  ry  Ztorch._inductor.utilsrz  )Zdevice_typery  Zcompile_supportedrz  r   r   r   is_compile_supported  s    r{  )r   offsetr<  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_utf8r   r   r   _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_offsetNrS  r   r   r   r   r  *  s   
r  )segmentr<  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r|jjd }|||jj}	||	\}}	 | |	  }
 s|
dkr2|
dkr"|||	\}}	q|||	\}}	q|	d }|t | k rt | |  }
 st|
dkrt|d7 }t||	||S t	||jr |jjd }|||jj}||\}} | | dkr|||\}}q|jd }|||j}t||||S t	||jr~|jjd }|||jj}||\}} | | dkrZ|||\}}q6|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|  linesr   r   	normalizeN  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 rj  r   rQ   r  colr  r   r   next_valid_charS  s
    
 z3_extract_anchors_from_expr.<locals>.next_valid_charc                    s>   |d7 }| |\} }| t  k r2|t  |  k s6t| |fS r7   r  r  r  r  r   r   	increment[  s     z-_extract_anchors_from_expr.<locals>.incrementc                    sB   d}| d7 } | |\} }| t  k r6|t  |  k s:t| |fS rj  r  r  r  r   r   nextlineb  s
     z,_extract_anchors_from_expr.<locals>.nextliner3  z)\#z\#[()r   r   rQ   astparseSyntaxErrorr   bodyr  r   ExprrK   BinOpleft
end_linenoend_col_offsetisspacer  	SubscriptCallr3   )r  r  treer  r  r  Z	statementrn  Z
cur_linenoZcur_colchZ	right_colZleft_linenoZleft_colZright_linenor   r  r   _extract_anchors_from_expr4  sh    

 


r  )r   instr<  c                 C   s2  |j jdkrdS t| j|j j }|j jdkr6|S |j jdksN|j jdkrR|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rdd |D }nd	d |D }|jd
kr| j|7  _|jd
kr4| j|7  _tt|D ]}	tt||	 D ]|}|	|jk rhqT|	|jkr||jk rqT|	|jkr||jkrqT|	|jkrqT||	 | dkrTd||	 |< qTq@d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  rB   ~r   r   c                 S   s   g | ]}| d dqS )r  ^)r  r   markerr   r   r   rg     s     z.get_instruction_source_311.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   )rk   r  r   r   r   rg     s     r   r  c                 S   s   g | ]}d  |qS )r  r  r  r   r   r   rg     s     )Z	positionsr  	linecachegetliner   rstripr  
col_offsetr  r  rP   r   r*  lstripr  rQ   r  r  r  r  )r   r  
first_lineZstart_offsetZ
end_offsetr  markers	last_liner  line
num_spacesanchorsr  r(  r-  r   r   r   get_instruction_source_311  s     "
r  c                   C   s   t jptjjjdS )NZ
recompiles)r   r  rN   r   	_internalZ	log_stateZis_artifact_enabledr   r   r   r   "is_guard_failure_reporting_enabled  s    r  c                 C   s   t | tjrt| dd S d S )NZ_dynamo_static_input_type)r   rN   r   rK  )r  r   r   r   get_static_address_type  s    r  )NN)r   F)N)F)r   )N)FFF)FFF)atexitrx   r   r  r*   rV  r  rI  r{  r  rh  r?  r#   r  r   r  r  r   r.   r   r  rO   r}  r   r   r   r   r   r   r   r   r   r	   r^  r   ModuleNotFoundErrorZtorch._loggingrN   Ztorch._numpyZ_numpyr]  Ztorch._guardsr
   r   r  r   ZfftZlinalgr/  ZNP_SUPPORTED_MODULESZNP_TO_TNP_MODULEr(  Ztorch._functorch.configZ%torch.fx.experimental.symbolic_shapesr   Ztorch._dispatch.pythonr   r  r   r   Ztorch.nn.modules.lazyr   Ztorch.utils._pytreer   defaultdictCounterr  Ztroubleshooting_urlZnnmodule_doc_urlZnnmodule_doc_url_msgr   r'   ro   ry   r=   r;   r  r)   r!   r6   r8   r9   r>   r@   rA   rL   rY   rn   registerrq   ZFloatTensorr   r  ZDoubleTensorr   doubleZ
HalfTensorr   ZhalfZBFloat16TensorZbfloat16Z
ByteTensorr   Z
CharTensorr   Z
LongTensorr   longZ	IntTensorr   r   ZShortTensorr   shortZ
BoolTensorr  Ztensortype_to_dtyperr   r   r   r   r   r   r   r   ZGraphr   r   r   r   r   r   r   r   r   r   r   r   r   r   rW  r   r  r  instancer  r  r)  r6  r9  r>  r@  rE  rD  r[  rf  rl  ro  rx  rz  r  r  r  r  r  r   r   rE   dict_valuesZodict_valuesiterr   tuple_iterator__length_hint__Ztuple_iterator_lenobject__new__r  r  r  r  r  r  r  r  r  Ztorch._subclassesr  r  r  r  r  r   r  r  r  Zorig_code_maprk   r  Zgraph_break_reasonsZseen_code_mapr  r  r   r  r  r  r  r!  r#  
ModuleTyper*  r/  r1  r|  r2  r8  r   r=  rB  r@  rH  rM  rQ  rR  rS  Zall_hook_namesrY  rZ  r[  r_  r`  rf  rg  rl  rq  rs  rx  r{  r   r  r  r  r~  Instructionr  r  r  r   r   r   r   <module>   s  
    

"

$
 
 
 
    
 
 
 !	

	3



		



 P

d
X$$	  
  
$  
		yk