o
    i                     @  s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZmZmZ ejdkrhd d	lmZ nd
d Zd dlZd dlm Z! d dl"m#Z# d dl$m%Z% d dl&m'Z'm(Z( d dl)m*Z* e+e,Z-erd dl.m/Z/m0Z0m1Z1 d dl2m3Z3 d dl4Z4d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< 	 e=dZ>e=dZ?eddddG dd dZ@G dd deZAG dd  d ejBZC	 G d!d" d"ZDejdd#G d$d% d%ZEG d&d' d'eZFejdd(G d)d* d*ZGed+ZH	 ejdd#G d,d- d-ZI	 ejdd#G d.d/ d/eIZJ	 ejdd#G d0d1 d1eIZK	 G d2d3 d3eeH ZLG d4d5 d5ZMG d6d7 d7ZNG d8d9 d9eLeN ZOG d:d; d;ZPG d<d= d=eLeP ZQG d>d? d?ZR	 G d@dA dAeLeM ZSG dBdC dCZTG dDdE dEeTZUG dFdG dGZVe	W ZX	 G dHdI dIZYG dJdK dKZZedldPdQZ[edmdTdUZ\edndZd[Z]e	dodpd^d[Z]e 	dodqdad[Z]e]dd#G dbdc dcZ^e]dd#G ddde dee^Z_dodrdhdiZ`dsdjdkZadS )t    )annotationsN)abstractmethod)defaultdict)contextmanager)	dataclass)AnyGeneric
NamedTupleOptionaloverloadTYPE_CHECKINGTypeVar)      )dataclass_transformc                  C  s   dd } | S )Nc                 S  s   | S N )fnr   r   O/sda-disk/www/egybert/egybert_env/lib/python3.10/site-packages/torch/_guards.py	decorator      z&dataclass_transform.<locals>.decoratorr   )r   r   r   r   r      s   r   )_pytree)
OrderedSet)is_traceable_wrapper_subclass)CapturedTracebackformat_frame)WeakTensorKeyDictionary)Callable	GeneratorIterator)CodeType)DDPOptimizerContext)	PyCodegen)ViewAndMutationMetaFakeTensorModez-^(?P<frame_id>\d+)/(?P<frame_compile_id>\d+)$zQ^!(?P<compiled_autograd_id>\d+)(?:/(?P<frame_id>\d+)/(?P<frame_compile_id>\d+))?$T)frozenkw_onlyslotsc                   @  sB   e Zd ZU ded< ded< dZded< ddd	ZedddZdS )	CompileId
int | Noneframe_idframe_compile_idNcompiled_autograd_idreturnstrc                 C  s~   | j d ur*| jd u | jd u ksJ d}| jd ur"d| j d| j }d| j  | S | jd ur4| jd us6J | j d| j S )N /!)r-   r+   r,   )self	frame_strr   r   r   __str___   s   

zCompileId.__str__
compile_id
str | NoneCompileId | Nonec              
   C  s   |du rdS z1t tfD ]*}|| }r5| }| D ]\}}|dur*t|||< q| di |  W S qt tyL } z	td| d|d}~ww )z
        Factory method that creates a CompileId from its string representation.
        Keep this in sync with the __str__ method.
        NzInvalid compile_id ''r   )COMPILE_ID_PATTERNCA_COMPILE_ID_PATTERNmatch	groupdictitemsint
ValueError	Exception)clsr6   patternr<   groupskver   r   r   from_stringl   s"   zCompileId.from_stringr.   r/   )r6   r7   r.   r8   )__name__
__module____qualname____annotations__r-   r5   classmethodrH   r   r   r   r   r)   P   s   
 
r)   c                   @  (   e Zd ZU ded< ded< d
ddZd	S )TraceIdr)   r6   r?   attemptr.   r/   c                 C  s&   | j dkr
t| jS | j d| j  S )Nr   _)rQ   r/   r6   r3   r   r   r   r5      s   

zTraceId.__str__NrI   rJ   rK   rL   rM   r5   r   r   r   r   rP      s   
 rP   c                   @  s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdddZdddZdddZdddZdddZdS ) GuardSourcer         r                  	   
   r                  r.   boolc                 C     | t jt jfv S r   )rU   GLOBAL_FSDP_MODULELOCAL_FSDP_MODULErS   r   r   r   is_fsdp_module      zGuardSource.is_fsdp_modulec                 C  s@   dd l m  m} |jr| tjtjfv p|  S | tjtjfv S Nr   )torch._dynamo.config_dynamoconfig_unsafe_skip_fsdp_module_guardsrU   GLOBAL_SPECIALIZED_NN_MODULELOCAL_SPECIALIZED_NN_MODULErh   )r3   rm   r   r   r   is_specialized_nn_module   s   z$GuardSource.is_specialized_nn_modulec                 C  s   | t jt jt jt jfv S r   )rU   GLOBAL_UNSPECIALIZED_NN_MODULELOCAL_UNSPECIALIZED_NN_MODULE&GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE%LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULErS   r   r   r   is_unspecialized_nn_module   s   z&GuardSource.is_unspecialized_nn_modulec                 C  re   r   )rU   rt   ru   rS   r   r   r   "is_unspecialized_builtin_nn_module   s   z.GuardSource.is_unspecialized_builtin_nn_modulec                 C  s   | t jt jt jt jt jfv S r   )rU   LOCALrp   rg   rs   ru   rS   r   r   r   is_local   s   zGuardSource.is_localNr.   rd   )rJ   rK   rL   rx   GLOBALrp   ro   CONSTANTRANDOM_VALUE	SHAPE_ENVrg   rf   BACKWARD_STATE	EPHEMERALSYNTHETIC_LOCALrs   rr   ru   rt   
TEMP_LOCALrh   rq   rv   rw   ry   r   r   r   r   rU      s.    



rU   c                   @     e Zd ZdS )GuardBuilderBaseNrJ   rK   rL   r   r   r   r   r      s    r   )r&   c                   @  rO   )SLocz#traceback.FrameSummary | str | Noneframework_locr7   maybe_user_locr.   r/   c                 C  sD   t | jtr	| jnt| j}| jd ur| j d| dS d| dS )Nz ()()
isinstancer   r/   r   r   )r3   flocr   r   r   r5      s   

zSLoc.__str__NrI   rT   r   r   r   r   r         
 r   c                   @  s&   e Zd ZU ded< ded< ded< dS )
ShapeGuardzsympy.logic.boolalg.Booleanexprr   slocrd   size_obliviousNrJ   rK   rL   rM   r   r   r   r   r      s   
 r   )r(   c                   @  s   e Zd ZU ded< ded< dZded< dZded< dZd	ed
< dZded< dZded< dZ	ded< dZ
ded< dZded< dCddZdDddZdEddZdFd!d"ZedGd$d%ZedHd'd(ZedId*d+ZdGd,d-ZdGd.d/ZdJd3d4ZdKd5d6ZdKd7d8ZdKd9d:ZdGd;d<ZdLdAdBZdS )MGuardSourceoriginating_sourcez)Callable[[GuardBuilderBase, Guard], None]	create_fnNzlist[str] | Noneguard_types	code_listzobject | Noneobj_weakref!weakref.ReferenceType[Any] | Noneguarded_class_weakrefzCapturedTraceback | Nonestackztraceback.StackSummary | None
user_stackr*   _hashFrd   _unserializabler.   r?   c                 C  s*   | j d u rt| j| jt| jf| _ | j S r   )r   hashnamesourceidr   rS   r   r   r   __hash__  s   
zGuard.__hash__tuple[bool, int, int, str, int]c                 C  sN   t | jtjo| jjtjjjj	u }|| j
r| j
jndt| j| j|  jjfS )N)r   r   	functoolspartialfunctorchrl   guardsGuardBuilderDUPLICATE_INPUTr   valuelenr   inner_create_fn__code__co_firstlineno)r3   is_duplicate_inputr   r   r   sort_key  s   
zGuard.sort_keyotherc                 C  s   |   |  k S r   )r   r3   r   r   r   r   __lt__/  ri   zGuard.__lt__(Callable[[GuardBuilderBase, Guard], Any]c                 C  s   t | jtjr| jjS | jS r   )r   r   r   r   r   rS   r   r   r   r   2  s   zGuard.inner_create_fnr/   c                 C     | j jS r   )r   r   rS   r   r   r   r   8     z
Guard.namerU   c                 C  r   r   )r   guard_sourcerS   r   r   r   r   <  r   zGuard.sourceobjectc                 C  sb   t | tjr-|  }|dur#dtt|  d|jj dtt| dS dtt|  dS t| S )a  
        This is a workaround of a Python weakref bug.

        `obj_weakref` is instance returned by `weakref.ref`,
        `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g:

            class MyConfig(dict):
                def __getattr__(self, x):
                    return self[x]

            obj = MyConfig(offset=5)
            obj_weakref = weakref.ref(obj)
            str(obj_weakref)  # raise error: KeyError: '__name__'
        Nz<weakref at z; to 'z' at >z; dead>)r   weakrefReferenceTypehexr   	__class__rJ   r/   )r   objr   r   r   weakref_to_str@  s   ,zGuard.weakref_to_strc                 C  s`   d| j r
| j j nd dt| j d|  j d| j d| j d| | j	 d| j
 d}|S )	Nz	
        r0    z&
        {
            'guard_types': z,
            'code': z,
            'obj_weakref': z
            'guarded_class': z
        }
        )r   r   lowerreprr   rJ   r   r   r   r   r   )r3   sr   r   r   __repr__Y  s    
	zGuard.__repr__c                 C  s   dt | j d}| jr| jj nd}|d| d7 }|d|  j d7 }|d| j d7 }|d| j d7 }|d| | j	 d7 }|d	| j
 d7 }|S )
NzName: 
r0   z    Source: z    Create Function: z    Guard Types: z    Code List: z    Object Weakref: z    Guarded Class Weakref: )r   r   r   r   r   rJ   r   r   r   r   r   )r3   outputr   r   r   r   r5   e  s   zGuard.__str__builderr   r   c                 C  s^   z|  || W S  ty.   tdt|   | jr-tdd| j	 dd     w )NzError while creating guard:
%szCreated at:
%sr0   )
r   rA   log	exceptionr/   rstripr   errorjoinformat)r3   r   r   r   r   createp  s   $zGuard.createc                 C  
   | j  S r   )r   rq   rS   r   r   r   rq   y     
zGuard.is_specialized_nn_modulec                 C  r   r   )r   rh   rS   r   r   r   rh   |  r   zGuard.is_fsdp_modulec                 C  r   r   )r   ry   rS   r   r   r   ry     r   zGuard.is_localc                 C  s(   t | jtjr| jj}|jS | j}|jS r   )r   r   r   r   r   rJ   )r3   r   r   r   r   create_fn_name  s
   zGuard.create_fn_name
guard_typeguarded_class	list[str]Nonec                 C  s   | j sg | _ | j | | j|d fv sJ d|| _| js!|| _n| j| | j|d fv s=t| jr9|  d u s=J d|| _d S )Nz+Guarded class id must be identical, or NonezBGuarded object must be identical, None or ephemeral (dead weakref))r   appendr   r   extendr   callable)r3   r   r   r   r   r   r   r   set_export_info  s(   
zGuard.set_export_infor.   r?   )r.   r   )r   r   r.   rd   )r.   r   rI   r.   rU   )r   r   r.   r/   )r   r   r.   r   rz   )
r   r/   r   r   r   r   r   r   r.   r   )rJ   rK   rL   rM   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   staticmethodr   r   r5   r   rq   rh   ry   r   r   r   r   r   r   r      s:   
 







	


r   Tc                   @  r   )GuardEnvExprNr   r   r   r   r   r     s    r   c                   @  s(   e Zd ZU ded< ded< d	ddZdS )
DuplicateInputsr   input_source_ainput_source_br.   r   c                 C  s   | j | jksJ d S r   )r   r   rS   r   r   r   __post_init__     zDuplicateInputs.__post_init__Nr.   r   )rJ   rK   rL   rM   r   r   r   r   r   r     r   r   c                   @  s   e Zd ZU ded< ded< dS )StorageOverlapzlist[Source]overlapping_sourcesnon_overlapping_sourcesNr   r   r   r   r   r     s   
 r   c                   @  s(   e Zd Zed
ddZedddZd	S )Checkpointabler.   r   c                 C     d S r   r   rS   r   r   r   copy_graphstate  r   zCheckpointable.copy_graphstatestater   c                 C  r   r   r   r3   r   r   r   r   restore_graphstate  r   z!Checkpointable.restore_graphstateN)r.   r   )r   r   r.   r   )rJ   rK   rL   r   r   r   r   r   r   r   r     s
    r   c                   @  s8   e Zd ZU dZded< dddZdd
dZdddZdS )GuardsCheckpointStatezW
    The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
    OrderedSet[Guard]dynamo_guardsr.   r   c                 C  
   || _ d S r   )r   )r3   r   r   r   r   __init__  r   zGuardsCheckpointState.__init__r   Optional[OrderedSet[Guard]]c                 C  s"   | j |j }t|dkrdS |S )z
        Produces a delta against another GuardsCheckpointState.

        Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched
        Guard type objects.
        r   N)r   
differencer   r3   r   rr   r   r   diff  s   zGuardsCheckpointState.diffr   rd   c                 C     t |tsdS | |d u S NF)r   r   r   r   r   r   r   __eq__	     
zGuardsCheckpointState.__eq__N)r   r   r.   r   )r   r   r.   r   r   r   r.   rd   )rJ   rK   rL   __doc__rM   r   r   r   r   r   r   r   r     s   
 

r   c                   @  s8   e Zd ZU i Zded< dddZdd	d
ZdddZdS )ModuleContextCheckpointStatedict[str, torch.nn.Module]
nn_modulesr.   r   c                 C  r   r   r  )r3   r  r   r   r   r     r   z%ModuleContextCheckpointState.__init__r   set[str] | Nonec                 C  2   t | j t |j }t|dkrdS |S )z
        Produces a delta against another ModuleContextCheckpointState.

        Returns None if no delta is found, otherwise, return a set() of mismatched
        module key names.
        r   N)setr  keysr   r   r   r   r   r   r        z!ModuleContextCheckpointState.diffr   rd   c                 C  r   r   )r   r  r   r   r   r   r   r   !  r  z#ModuleContextCheckpointState.__eq__N)r  r  r.   r   )r   r  r.   r  r  )rJ   rK   rL   r  rM   r   r   r   r   r   r   r   r    
   
 

r  c                   @  *   e Zd ZdddZdddZdd	d
ZdS )ModuleContextr.   r   c                 C  
   i | _ d S r   r  rS   r   r   r   r   (  r   zModuleContext.__init__r  c                 C  s   t t| jS r   )r  dictr  rS   r   r   r   r   +     zModuleContext.copy_graphstater   c                 C  s   t |tsJ |j| _d S r   )r   r  r  r   r   r   r   r   .  s   z ModuleContext.restore_graphstateNr   )r.   r  )r   r  r.   r   rJ   rK   rL   r   r   r   r   r   r   r   r  '  s    

r  c                   @  s8   e Zd ZU i Zded< dddZdd
dZdddZdS )GlobalContextCheckpointStatedict[str, tuple[Callable, Any]]global_stateglobal_statesr.   r   c                 C  r   r   r  )r3   r  r   r   r   r   6  r   z%GlobalContextCheckpointState.__init__r   r  c                 C  r	  )z
        Produces a delta against another GlobalContextCheckpointState.

        Returns None if no delta is found, otherwise, return a set() of mismatched
        global key names.
        r   N)r
  r  r  r   r   r   r   r   r   r   9  r  z!GlobalContextCheckpointState.diffr   rd   c                 C  r   r   )r   r  r   r   r   r   r   r   E  r  z#GlobalContextCheckpointState.__eq__N)r  r  r.   r   )r   r  r.   r  r  )rJ   rK   rL   r  rM   r   r   r   r   r   r   r   r  3  r  r  c                   @  s6   e Zd ZdZh dZdddZddd	ZdddZdS )GlobalContextzz
    This keeps track of the global torch state during tracing of a function.
    For example, torch.is_grad_enabled.
    >   grad_enabledautocast_enabledautocast_cpu_dtypeautocast_gpu_dtypeautocast_cpu_enabledautocast_cache_enabledr.   r   c                 C  r  r   r  rS   r   r   r   r   Z  r   zGlobalContext.__init__r  c                 C  
   t | jS r   )r  r  rS   r   r   r   r   ]  r   zGlobalContext.copy_graphstater   c                 C  sf   t |tsJ |j| _t| jt| jkrt| j | jks#J d| j D ]\}}|| q(d S )NzGlobal state mismatch)r   r  r  r   _supported_global_statesr
  r  values)r3   r   r   argsr   r   r   r   `  s   
z GlobalContext.restore_graphstateNr   )r.   r  )r   r  r.   r   )rJ   rK   rL   r  r!  r   r   r   r   r   r   r   r  K  s    
	
r  c                   @  sf   e Zd Zd%d&ddZd'd	d
Zd(ddZd)ddZd*ddZdddd+ddZd,dd Z	d-d#d$Z
dS ).	GuardsSetNinnerr   r.   r   c                 C  s   |d u r
t  | _d S || _d S r   )r   r%  )r3   r%  r   r   r   r   n  s   
zGuardsSet.__init__Iterator[Guard]c                 C  r   r   )iterr%  rS   r   r   r   __iter__t  r   zGuardsSet.__iter__r?   c                 C  r   r   )r   r%  rS   r   r   r   __len__w  r   zGuardsSet.__len__r   c                 C  s   t | j|j S r   )r$  r%  r   r   r   r   __sub__|  ri   zGuardsSet.__sub__rd   c                 C  r   r   )rd   r%  rS   r   r   r   __bool__  r   zGuardsSet.__bool__Tr   )collect_debug_stackskipguardr   r,  r-  c                C  sR   || j v rd S |r|jd u rtjd| d|_|jd u r!t |_| j | d S NrV   )r-  )r%  r   r   extractr   TracingContextextract_stackadd)r3   r.  r,  r-  r   r   r   r3    s   



zGuardsSet.addothers
set[Guard]c                 G  s&   |D ]}|D ]	}| j |dd qqd S r/  )r3  )r3   r4  ogr   r   r   update  s
   zGuardsSet.updater   r   c                   s,   ddl m  t fdd| jD | _dS )z.Delete all guards that contains a given sourcerV   )is_from_sourcec                 3  s     | ]} |j s|V  qd S r   )r   ).0r7  r9  r   r   r   	<genexpr>  s    
z6GuardsSet.remove_guards_with_source.<locals>.<genexpr>N)_dynamo.sourcer9  r   r%  )r3   r   r   r;  r   remove_guards_with_source  s   z#GuardsSet.remove_guards_with_sourcer   )r%  r   r.   r   )r.   r&  r   )r   r$  r.   r$  rz   )r.  r   r,  rd   r-  r?   r.   r   )r4  r5  r.   r   )r   r   r.   r   )rJ   rK   rL   r   r(  r)  r*  r+  r3  r8  r>  r   r   r   r   r$  m  s    




r$  c                   @  r  )GuardsContextr.   r   c                 C  s   t  | _g | _d S r   )r$  r   aotautograd_guardsrS   r   r   r   r     s   
zGuardsContext.__init__r   c                 C  s   t t| jjS r   )r   r   r   r%  rS   r   r   r   r     ri   zGuardsContext.copy_graphstater   c                 C  s   t |tsJ t|j| _d S r   )r   r   r$  r   r   r   r   r   r     s   z GuardsContext.restore_graphstateNr   )r.   r   )r   r   r.   r   r  r   r   r   r   r?    s    

r?  c                   @  s|   e Zd Zed!ddZed"d
dZed#ddZed$ddZed#ddZed$ddZ	ed%ddZ
ed&ddZd S )'HopSubgraphCachefn_idr?   
identifierr/   r.   r   c                 C  r   r   r   r3   rB  rC  r   r   r   add_dynamo_installed_submodule  r   z/HopSubgraphCache.add_dynamo_installed_submoduler   c                 C  r   r   r   r3   rB  r   r   r   get_dynamo_installed_submodules  r   z0HopSubgraphCache.get_dynamo_installed_submoduleskeyr   c                 C  r   r   r   r3   rC  rH  r   r   r   add_autograd_key_entry  r   z'HopSubgraphCache.add_autograd_key_entryCallable | Nonec                 C  r   r   r   r3   rC  r   r   r   get_autograd_key_entry  r   z'HopSubgraphCache.get_autograd_key_entryc                 C  r   r   r   rI  r   r   r   add_proxy_dispatch_entry  r   z)HopSubgraphCache.add_proxy_dispatch_entryc                 C  r   r   r   rL  r   r   r   get_proxy_dispatch_entry  r   z)HopSubgraphCache.get_proxy_dispatch_entrytangent_metadatatuple[object]gmodtorch.fx.GraphModulec                 C  r   r   r   )r3   rC  rP  rR  r   r   r   add_lazy_bwd_entry  s   z#HopSubgraphCache.add_lazy_bwd_entry.tuple[torch.fx.GraphModule | None, int | None]c                 C  r   r   r   r3   rC  rP  r   r   r   get_lazy_bwd_entry     z#HopSubgraphCache.get_lazy_bwd_entryNrB  r?   rC  r/   r.   r   rB  r?   r.   r   rC  r/   rH  r   r.   r   rC  r/   r.   rK  rC  r/   rP  rQ  rR  rS  r.   r?   rC  r/   rP  rQ  r.   rU  )rJ   rK   rL   r   rE  rG  rJ  rM  rN  rO  rT  rW  r   r   r   r   rA    s"    rA  c                   @  sz   e Zd Zd*ddZd+d	d
Zd,ddZd-ddZd.ddZd-ddZd.ddZ	d/ddZ
d0d d!Zd1d$d%Zd2d'd(Zd)S )3InvokeSubgraphCacher.   r   c                 C  s*   i | _ i | _tt| _tt| _i | _d S r   )autograd_cacheproxy_dispatch_cacher   listdynamo_installed_submodulesr  lazy_bwd_cacheeffects_cacherS   r   r   r   r     s   
zInvokeSubgraphCache.__init__rB  r?   rC  r/   c                 C  s   | j | | d S r   )rc  r   rD  r   r   r   rE    r   z2InvokeSubgraphCache.add_dynamo_installed_submoduler   c                 C  s   | j |g S r   )rc  getrF  r   r   r   rG    r  z3InvokeSubgraphCache.get_dynamo_installed_submodulesrH  r   c                 C     || j |< d S r   )r`  rI  r   r   r   rJ    r  z*InvokeSubgraphCache.add_autograd_key_entryrK  c                 C     | j |d S r   )r`  rf  rL  r   r   r   rM    r  z*InvokeSubgraphCache.get_autograd_key_entryc                 C  rg  r   )ra  rI  r   r   r   rN    r  z,InvokeSubgraphCache.add_proxy_dispatch_entryc                 C  rh  r   )ra  rf  rL  r   r   r   rO    r  z,InvokeSubgraphCache.get_proxy_dispatch_entryrP  rQ  rR  rS  c                 C  s$   t | j| }||f| j| |< |S r   )r   rd  )r3   rC  rP  rR  	num_gmodsr   r   r   rT    s   z&InvokeSubgraphCache.add_lazy_bwd_entryrU  c                 C  s    || j vrdS | j | |dS )N)NN)rd  rf  rV  r   r   r   rW    s   
z&InvokeSubgraphCache.get_lazy_bwd_entryeffectsr
  c                 C  sD   | j |d }r||ksJ d| d| d| d|| j |< dS )z>Store the effect types for a given invoke_subgraph identifier.NzPDifferent number of effects were found for invoke_subgraph call with identifier z,. 
Previously we had the following effects: z.
But now we have: .re  rf  )r3   rC  rj  prev_effectsr   r   r   add_effects  s   
zInvokeSubgraphCache.add_effects
set | Nonec                 C  s   | j |dS )zARetrieve the effect types for a given invoke_subgraph identifier.Nrl  rL  r   r   r   get_effects  s   zInvokeSubgraphCache.get_effectsNr   rY  rZ  r[  r\  r]  r^  )rC  r/   rj  r
  r.   r   )rC  r/   r.   ro  )rJ   rK   rL   r   rE  rG  rJ  rM  rN  rO  rT  rW  rn  rp  r   r   r   r   r_    s    









r_  c                   @  s    e Zd ZdddZddd	Zd
S )HopDispatchSetCacher.   r   c                 C  s   ddl m} |t i| _d S )Nr   )invoke_subgraph)'torch._higher_order_ops.invoke_subgraphrr  r_  hop_cache_map)r3   rr  r   r   r   r     s   zHopDispatchSetCache.__init__optorch._ops.HigherOrderOperatorHopSubgraphCache | Nonec                 C  s   || j vrd S | j | S r   )rt  )r3   ru  r   r   r   	get_cache  s   

zHopDispatchSetCache.get_cacheNr   )ru  rv  r.   rw  )rJ   rK   rL   r   rx  r   r   r   r   rq    s    
rq  c                   @  sN   e Zd ZedddZedddZdd
dZedddZedddZdS )CompileContextr.   c                   C  s   t jd usJ t jS r   )_TLScompile_contextr   r   r   r   rf  7  s   zCompileContext.getCompileContext | Nonec                   C     t tdd S Nr{  getattrrz  r   r   r   r   try_get<     zCompileContext.try_getr6   r8   r   c                 C  s,   |d u st |tsJ || _d| _g | _d S rj   )r   r)   r6   rQ   shape_env_guards)r3   r6   r   r   r   r   @  s   
zCompileContext.__init__c                  C     t  } | d u r
d S | jS r   )ry  r  r6   rS   r   r   r   current_compile_idG     z!CompileContext.current_compile_idTraceId | Nonec                  C  s0   t  } | d u r
d S | jd u rd S t| j| jS r   )ry  r  r6   rP   rQ   rS   r   r   r   current_trace_idN  s   
zCompileContext.current_trace_idN)r.   ry  )r.   r|  )r6   r8   r.   r   )r.   r8   )r.   r  )	rJ   rK   rL   r   rf  r  r   r  r  r   r   r   r   ry  6  s    
ry  c                   @  s   e Zd ZdZed.ddZed/ddZd0ddZd1ddZee	d2ddZ
ed3ddZd4ddZeej	d5ddZeej	d6ddZeej	d7d!d"Zed8d(d)Zed9d+d,Zd-S ):r1  z
    Provides the currently installed TracingContext, or None.

    Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but
    will return None.
    r.   TracingContext | Nonec                   C  r}  )Ntracing_contextr  r   r   r   r   r  `  r  zTracingContext.try_getc                  C  s   t   } r| S td)Nz<TracingContext.get() must be called within an ongoing trace.)r1  r  RuntimeError)ctxr   r   r   rf  d  s
   zTracingContext.get	fake_modeFakeTensorMode | Noner   c                 C  s   t  | _t | _t | _t | _t | _|| _	g | _
d | _d | _d | _d | _d | _d | _d | _d | _d| _t | _d| _t | _g | _d S r   )r?  guards_contextr  module_contextr  global_contextr  previously_inlined_functionspreviously_cleaned_instructionsr  frame_summary_stackloc_in_framefw_metadataddp_optimizer_ctxaot_graph_nameparams_flatparams_flat_unwrap_subclassesparams_unwrapped_to_flat_indexoutput_strides#force_unspec_int_unbacked_size_liker   tensor_to_contextfakify_first_callrq  hop_dispatch_set_cachetraced_code)r3   r  r   r   r   r   l  s(   

zTracingContext.__init__c                 C  s    i | j _| j  | j  d S r   )r  r  r  clearr  rS   r   r   r   r    s   
zTracingContext.clearkwargsr   Generator[None, None, None]c                  k  s    i }t  }| D ]	}t||||< q	|  D ]
\}}t||| qzd V  W | D ]
\}}t||| q+d S | D ]
\}}t||| q<w r   )r1  rf  r  r>   setattr)r  priorr  rH  valr   r   r   patch  s   zTracingContext.patchtraceback.StackSummaryc                  C  sB   t  } | d u rt S | j}| jd ur||  g }tj|S r   )r1  r  	tracebackStackSummaryr  r  _populate_loc_in_frame_summary	from_list)r3   r   r   r   r   r2    s   
zTracingContext.extract_stacktraceback.FrameSummaryc                 C  s,   | j d usJ | j \}}}tj|||ddS )NF)lookup_line)r  r  FrameSummary)r3   filenamelineno
frame_namer   r   r   r    s   z-TracingContext._populate_loc_in_frame_summaryc                  c  s    t  } tjj| dg E tjj| dd # zd V  W n ty3 } z	t|ds.d |_ d }~ww W d    n1 s>w   Y  W d    d S W d    d S 1 sVw   Y  d S )Nr  r  
real_stack)	r1  rf  unittestmockr  r   rA   hasattrr  )tcrG   r   r   r   clear_frame  s    

PzTracingContext.clear_frameframe_summarytraceback.FrameSummary | Nonec              
   c  s    t  }| d ur|j|  |j}d |_z,zd V  W n ty2 } zt|ds-| |_ d }~ww W | d ur=|j	  ||_d S | d urK|j	  ||_w )Nr  )
r1  rf  r  r   r  rA   r  r2  r  pop)r  r  oldrG   r   r   r   current_frame  s*   





zTracingContext.current_frame:Generator[list[tuple[int, ...] | None] | None, None, None]c                  c  sF    t  } | d u rd V  d S | j}g | _z
| jV  W || _d S || _w r   )r1  r  r  )r  old_output_stridesr   r   r   report_output_strides  s   
z$TracingContext.report_output_stridesr  r/   r  r?   r  c                 C  s   | ||ft  _d S r   )r1  rf  r  )r  r  r  r   r   r   set_current_loc  s   zTracingContext.set_current_loclist[CodeType] | Nonec                  C  r  r   )r1  r  r  )r  r   r   r   get_traced_code  r  zTracingContext.get_traced_codeN)r.   r  )r.   r1  )r  r  r.   r   r   )r  r   r.   r  )r.   r  )r.   r  )r.   r  )r  r  r.   r  )r.   r  )r  r/   r  r?   r  r/   r.   r   )r.   r  )rJ   rK   rL   r  r   r  rf  r   r  r   r  r2  r  
contextlibr  r  r  r  r  r   r   r   r   r1  X  s6    

3
	r1  contextr|  r.   ,Generator[CompileContext | None, None, None]c                 c  s0    t tdd }| t_z	| V  W |t_d S |t_w r~  )r  rz  r{  )r  old_contextr   r   r   r{    s   r{  r  ,Generator[TracingContext | None, None, None]c              
   c  s    t tdd}| t_z<z| V  W n ty+ } zt|ds&| dur&|  |_ d}~ww W | durB| jdurB| jjdurB| jj	  |t_dS | dur\| jdur\| jjdur\| jj	  |t_w )z
    This function installs the passed in tracing context as a dynamic scoped
    global variable.

    Calls to TracingContext.get() while not under a `with tracing()` context
    will return None.
    r  Nr  )
r  rz  r  rA   r  r2  r  r  	shape_envcleanup)r  r  rG   r   r   r   tracing)  s,   




r  rB   type[T]r  r   c                 K  r   r   r   rB   r  r   r   r   dataclass_with_cached_hashF  r   r  r   Callable[[type[T]], type[T]]c                 K  r   r   r   r  r   r   r   r  J  rX  type[T] | None&type[T] | Callable[[type[T]], type[T]]c                   s"   d fdd}| d u r|S || S )N	cls_innerr  r.   c                   s>   t j| fi }| j d fdd}dd }||_||_|S )Nr.   r?   c                   s"   t | dst| d |  | jS )Nr   )r  r   __setattr__r   rS   old_hashr   r   r   X  s   
z:dataclass_with_cached_hash.<locals>.wrap.<locals>.__hash__c                   s*   t  }t fdd|D } j|fS )Nc                 3  s    | ]	}t  |jV  qd S r   )r  r   )r:  frS   r   r   r<  b  s    zOdataclass_with_cached_hash.<locals>.wrap.<locals>.__reduce__.<locals>.<genexpr>)dataclassesfieldstupler   )r3   r  field_valuesr   rS   r   
__reduce__]  s   

z<dataclass_with_cached_hash.<locals>.wrap.<locals>.__reduce__r   )r  r   r   r  )r  new_clsr   r  r  r  r   wrapT  s   z(dataclass_with_cached_hash.<locals>.wrap)r  r  r.   r  r   )rB   r  r  r   r  r   r  P  s   c                   @  s   e Zd Zd&ddZd&ddZd'd
dZejd(ddZe	d)ddZ
ejd)ddZd*ddZd+dd Zd&d!d"Zd&d#d$Zd%S ),r   r.   rd   c                 C     dS r   r   rS   r   r   r   is_dict_keys  r   zSource.is_dict_keyc                 C  r  r   r   rS   r   r   r   is_ephemeralv  r   zSource.is_ephemeralcodegenr"   r   c                 C     t r   NotImplementedError)r3   r  r   r   r   reconstructy  r   zSource.reconstructrU   c                 C  r  r   r  rS   r   r   r   r   |  s   zSource.guard_sourcer/   c                 C  r  )a  
        A template for the name of the source. Used to prevent code duplication between
        `name` and `get_value`.

        For non-ChainedSources, `name` and `get_value` use the returned string directly.

        For ChainedSources, `name` and `get_value` expect the return to be a format string
        with `{0}` present - `name` and `get_value` will apply different values to this function's
        returned format string.
        r  rS   r   r   r   _name_template  s   zSource._name_templatec                 C  s   | j S r   )r  rS   r   r   r   r     s   zSource.nameglobalsdict[str, Any]localscache&weakref.WeakKeyDictionary[Source, Any]r   c                 C  s*   | |v r||  S t | j||}||| < |S r   )evalr  )r3   r  r  r  r   r   r   r   	get_value  s
   zSource.get_valuer   Callable[..., Any]r   c                 C  s   | j tju rtt| |S r   )r   rU   r|   r  r   )r3   r   r   r   r   
make_guard  s   
zSource.make_guardc                 C  r   r   )r   rq   rS   r   r   r   rq     r   zSource.is_specialized_nn_modulec                 C  s   | j tjkS )z+True if you can guard on attributes of this)r   rU   r   rS   r   r   r   subguards_allowed  r  zSource.subguards_allowedNrz   )r  r"   r.   r   r   rI   r  r  r  r  r  r  r.   r   )r   r  r.   r   )rJ   rK   rL   r  r  r  r   cached_propertyr   r   r  r   r  r  rq   r  r   r   r   r   r   q  s    





r   c                   @  s^   e Zd ZU ded< dddZdddZejdd
dZdddZ	ejdddZ
dddZdS )ChainedSourcer   baser.   rd   c                 C  r   r   )r  r  rS   r   r   r   r    s   
zChainedSource.is_dict_keyc                 C  r   r   )r  r  rS   r   r   r   r    r   zChainedSource.is_ephemeralrU   c                 C  r   r   )r  r   rS   r   r   r   r     r   zChainedSource.guard_sourcec                 C  s"   | }t |tr|j}t |ts|S r   )r   r  r  )r3   currentr   r   r   get_base  s
   

zChainedSource.get_baser/   c                 C  s   | j | jjS r   )r  r   r  r   rS   r   r   r   r     s   zChainedSource.namer  r  r  r  r  r   c                 C  st   | |v r||  S d}d}||v rd| }|d7 }||v s| j |||||< t| j|||}||= ||| < |S )Ntmpr   rV   )r  r  r  r  r   )r3   r  r  r  tmpvarcounterr   r   r   r   r    s   
zChainedSource.get_valueNrz   r   )r.   r   rI   r  )rJ   rK   rL   rM   r  r  r   r  r   r  r   r  r   r   r   r   r    s   
 


r  inputsr  c                   s  ddl m m}m} g }t  }r!|j}|dur!||ddf ddlm	} t
t| D ]\}t||r?||df q.t| }t
|D ]5\}	t|	 r[||	jdf t|	r~g }
||	|
d  fd	d
|
D }|fdd
t
|D  qI|r|d \}}}|dd D ]3\}}}||u sJ d| d| d| d| d| d| d| d| d|j d| d| d|j q|S dS )a  
    Attempts to "detect" what the current fake mode is.  If there is one ambiently
    available from TracingContext, we preferentially use that.  Otherwise, we
    heuristically detect the fake mode via the following sources, in order of
    priority:

        - Currently active fake mode on stack
        - Fake mode associated with passed in tensors (inputs does not
          have to be flattened)
    r   )
FakeTensorr%   get_plain_tensorsNztracing context _get_current_dispatch_mode_stackzactive fake modezfake tensor input)outc                   s   g | ]	}t | r|qS r   )r   )r:  x)r  r   r   
<listcomp>   s
    
z$detect_fake_mode.<locals>.<listcomp>c                   s"   g | ]\}}|j d   |fqS )zsubclass input )r  )r:  ixtensor)ir   r   r    s    rV   zfake mode (z) from r   z doesn't match mode (z

fake mode from z allocated at:
z
fake mode from )torch._subclasses.fake_tensorr  r%   r  r1  r  r  r   torch.utils._python_dispatchr   	enumeratereversedr   pytreetree_leavesr   r   r   )r  r%   r  
fake_modesr  r  r   mflat_inputs
flat_inputr  fake_tensorsdesc1i1desc2i2r   )r  r  r   detect_fake_mode  s^   





&r  c                  C  sF   ddl m}  ddlm} tt| D ]\}}t|| r |  S qdS )z~
    Inspects the dispatch mode stack for an active fake mode and returns it.
    Returns None if no fake mode is active.
    r   r$   r  N)r  r%   r  r   r	  r
  r   )r%   r   rR   r  r   r   r   active_fake_mode  s   
r  )r  r|  r.   r  )r  r  r.   r  )rB   r  r  r   r.   r  r   )rB   r   r  r   r.   r  )rB   r  r  r   r.   r  )r  r   r.   r  )r.   r  )b
__future__r   r  r  enumr   loggingresys	threadingr  unittest.mockr  r   abcr   collectionsr   r   r   typingr   r   r	   r
   r   r   r   version_infor   r   torch.utilsr   r  torch.utils._ordered_setr   r  r   torch.utils._tracebackr   r   torch.utils.weakr   	getLoggerrJ   r   collections.abcr   r   r   typesr    sympy"torch._dynamo.backends.distributedr!   torch._dynamo.codegenr"   &torch._functorch._aot_autograd.schemasr#   r  r%   compiler:   r;   r)   rP   EnumrU   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r$  r?  rA  r_  rq  localrz  ry  r1  r{  r  r  r   r  r  r  r   r   r   r   <module>   s    $


2?

 3


"/!A" F :,B