o
    Zh=                     @  s2  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mZ d dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZ d dl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r}d dl(Z(	 e)dZ*e)dZ+eddG dd dZ,G dd deZ-G dd dej.Z/	 G dd dZ0ejddG dd dZ1G dd deZ2eejG dd dZ3edZ4	 ejG dd dZ5	 ejG d d! d!e5Z6	 ejG d"d# d#e5Z7	 G d$d% d%ee4 Z8G d&d' d'Z9G d(d) d)Z:G d*d+ d+e8e: Z;G d,d- d-Z<G d.d/ d/e8e< Z=	 G d0d1 d1Z>G d2d3 d3e8e9 Z?G d4d5 d5Z@G d6d7 d7e@ZAG d8d9 d9ZBeC ZD	 G d:d; d;ZEG d<d= d=ZFedOd@dAZGedPdCdDZHejddG dEdF dFZIejddG dGdH dHeIZJdQdRdKdLZKdMdN ZLdS )S    )annotationsN)abstractmethod)contextmanager)	dataclass)AnyCallableGeneric
NamedTupleOptionalTYPE_CHECKINGTypeVarUnion)_pytree)dataclass_slots)CapturedTracebackformat_frame)WeakTensorKeyDictionaryz-^(?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)frozenc                   @  s@   e Zd ZU ded< ded< dZded< dd Zedd
dZdS )	CompileIdOptional[int]frame_idframe_compile_idNcompiled_autograd_idc                 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   )selfZ	frame_str r   </var/www/auris/lib/python3.10/site-packages/torch/_guards.py__str__S   s   

zCompileId.__str__
compile_idOptional[str]c              
   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)clsr    patternr%   groupskver   r   r   from_string`   s"   zCompileId.from_string)r    r!   )__name__
__module____qualname____annotations__r   r   classmethodr1   r   r   r   r   r   D   s   
 r   c                   @  &   e Zd ZU ded< ded< dd ZdS )TraceIdr   r    r(   attemptc                 C  s&   | j dkr
t| jS | j d| j  S )Nr   _)r9   strr    r   r   r   r   r   }   s   

zTraceId.__str__Nr2   r3   r4   r5   r   r   r   r   r   r8   w   s   
 r8   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ddZdddZdddZdddZdd ZdS )GuardSourcer                           	   
                  returnboolc                 C     | t jt jfv S N)r>   GLOBAL_FSDP_MODULELOCAL_FSDP_MODULEr<   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   )Ztorch._dynamo.config_dynamoconfigZ_unsafe_skip_fsdp_module_guardsr>   GLOBAL_SPECIALIZED_NN_MODULELOCAL_SPECIALIZED_NN_MODULErT   )r   rX   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 rQ   )r>   GLOBAL_UNSPECIALIZED_NN_MODULELOCAL_UNSPECIALIZED_NN_MODULE&GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE%LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULEr<   r   r   r   is_unspecialized_nn_module   s   z&GuardSource.is_unspecialized_nn_modulec                 C  rP   rQ   )r>   r^   r_   r<   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 rQ   )r>   LOCALrZ   rS   r]   r_   r<   r   r   r   is_local   s   zGuardSource.is_localNrN   rO   )r2   r3   r4   rb   GLOBALrZ   rY   CONSTANTZRANDOM_VALUEZ	SHAPE_ENVrS   rR   ZBACKWARD_STATEZ	EPHEMERALSYNTHETIC_LOCALr]   r\   r_   r^   rT   r[   r`   ra   rc   r   r   r   r   r>      s,    



r>   c                   @     e Zd ZdS )GuardBuilderBaseNr2   r3   r4   r   r   r   r   ri      s    ri   c                   @  r7   )SLocz,Optional[Union[traceback.FrameSummary, str]]framework_locr!   maybe_user_locc                 C  sD   t | jtr	| jnt| j}| jd ur| j d| dS d| dS )Nz ()()
isinstancerl   r;   r   rm   )r   Zflocr   r   r   r      s   

zSLoc.__str__Nr=   r   r   r   r   rk         
 rk   c                   @  s&   e Zd ZU ded< ded< ded< dS )
ShapeGuardzsympy.logic.boolalg.Booleanexprrk   ZslocrO   Zsize_obliviousNr2   r3   r4   r5   r   r   r   r   rr      s   
 rr   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d Zdd Zdd Zdd Zed4ddZed5d d!Zed"d# Zd$d% Zd&d' Zd6d*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 ZdS )7GuardSourceoriginating_sourcez)Callable[[GuardBuilderBase, Guard], None]	create_fnNzOptional[list[str]]guard_types	code_listzOptional[object]obj_weakrefzOptional[type]guarded_class_weakrefzOptional[CapturedTraceback]stackz Optional[traceback.StackSummary]
user_stackr   _hashc                 C  s*   | j d u rt| j| jt| jf| _ | j S rQ   )r   hashnamesourceidrx   r<   r   r   r   __hash__  s   
zGuard.__hash__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)rp   rx   	functoolspartialfunctorchrW   ZguardsZGuardBuilderZDUPLICATE_INPUTr   valuelenr   inner_create_fn__code__co_firstlineno)r   Zis_duplicate_inputr   r   r   sort_key  s   
zGuard.sort_keyc                 C  s   |   |  k S rQ   )r   r   otherr   r   r   __lt__"  rU   zGuard.__lt__c                 C  s   t | jtjr| jjS | jS rQ   )rp   rx   r   r   r   r<   r   r   r   r   %  s   zGuard.inner_create_fnrN   r;   c                 C  
   | j  S rQ   )rw   r   r<   r   r   r   r   +     
z
Guard.namer>   c                 C  r   rQ   )rw   guard_sourcer<   r   r   r   r   /  r   zGuard.sourcec                 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>)rp   weakrefReferenceTypehexr   	__class__r2   r;   )r{   objr   r   r   weakref_to_str3  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	
        r    z&
        {
            'guard_types': z,
            'code': z,
            'obj_weakref': z
            'guarded_class': z
        }
        )r   r   lowerreprr   r2   ry   rz   r   r{   r|   )r   sr   r   r   __repr__L  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: 
r   z    Source: z    Create Function: z    Guard Types: z    Code List: z    Object Weakref: z    Guarded Class Weakref: )r   r   r   r   r   r2   ry   rz   r   r{   r|   )r   outputr   r   r   r   r   X  s   zGuard.__str__builderri   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:
%sr   )
rx   r*   log	exceptionr;   rstripr}   errorjoinformat)r   r   r   r   r   createc  s   $zGuard.createc                 C  r   rQ   )r   r[   r<   r   r   r   r[   l     
zGuard.is_specialized_nn_modulec                 C  r   rQ   )r   rT   r<   r   r   r   rT   o  r   zGuard.is_fsdp_modulec                 C  r   rQ   )r   rc   r<   r   r   r   rc   r  r   zGuard.is_localc                 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))ry   appendr|   rz   extendr{   callable)r   Z
guard_typeZguarded_classrz   r{   r   r   r   set_export_infou  s(   
zGuard.set_export_inforN   r;   rN   r>   )r   ri   )r2   r3   r4   r5   ry   rz   r{   r|   r}   r~   r   r   r   r   r   propertyr   r   staticmethodr   r   r   r   r[   rT   rc   r   r   r   r   r   ru      s6   
 

	ru   Tc                   @  rh   )GuardEnvExprNrj   r   r   r   r   r     s    r   c                   @  s&   e Zd ZU ded< ded< dd ZdS )DuplicateInputsrv   input_source_ainput_source_bc                 C  s   | j | jksJ d S rQ   )r   r   r<   r   r   r   __post_init__  s   zDuplicateInputs.__post_init__N)r2   r3   r4   r5   r   r   r   r   r   r     rq   r   c                   @  s   e Zd ZU ded< ded< dS )StorageOverlapzlist[Source]Zoverlapping_sourcesZnon_overlapping_sourcesNrt   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 )CheckpointablerN   r   c                 C     d S rQ   r   r<   r   r   r   copy_graphstate     zCheckpointable.copy_graphstatestatec                 C  r   rQ   r   r   r   r   r   r   restore_graphstate  r   z!Checkpointable.restore_graphstateN)rN   r   )r   r   )r2   r3   r4   r   r   r   r   r   r   r   r     s
    r   c                   @  s8   e Zd ZU dZe Zded< dd Zdd Zdd	 Z	d
S )GuardsCheckpointStatezW
    The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
    
set[Guard]dynamo_guardsc                 C  
   || _ d S rQ   )r   )r   r   r   r   r   __init__  r   zGuardsCheckpointState.__init__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 a set() of mismatched
        Guard type objects.
        r   N)r   
differencer   r   r   rr   r   r   diff  s   zGuardsCheckpointState.diffc                 C     |  |d u S rQ   r   r   r   r   r   __eq__     zGuardsCheckpointState.__eq__N)
r2   r3   r4   __doc__setr   r5   r   r   r   r   r   r   r   r     s   
 r   c                   @  2   e Zd ZU i Zded< dd Zdd Zdd Zd	S )
ModuleContextCheckpointStatezdict[str, torch.nn.Module]
nn_modulesc                 C  r   rQ   r   )r   r   r   r   r   r     r   z%ModuleContextCheckpointState.__init__c                 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)r   r   keysr   r   r   r   r   r   r        z!ModuleContextCheckpointState.diffc                 C  r   rQ   r   r   r   r   r   r     r   z#ModuleContextCheckpointState.__eq__N)r2   r3   r4   r   r5   r   r   r   r   r   r   r   r     
   
 r   c                   @  &   e Zd Zd
ddZdd Zdd Zd	S )ModuleContextrN   Nonec                 C  
   i | _ d S rQ   r   r<   r   r   r   r   
  r   zModuleContext.__init__c                 C     t t| jS rQ   )r   dictr   r<   r   r   r   r     r   zModuleContext.copy_graphstatec                 C  s   t |tsJ |j| _d S rQ   )rp   r   r   r   r   r   r   r     s   z ModuleContext.restore_graphstateNrN   r   r2   r3   r4   r   r   r   r   r   r   r   r   	  s    
r   c                   @  r   )
GlobalContextCheckpointStatezdict[str, tuple[Callable, ...]]global_statec                 C  r   rQ   r   )r   Zglobal_statesr   r   r   r     r   z%GlobalContextCheckpointState.__init__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     r   z!GlobalContextCheckpointState.diffc                 C  r   rQ   r   r   r   r   r   r   '  r   z#GlobalContextCheckpointState.__eq__N)r2   r3   r4   r   r5   r   r   r   r   r   r   r   r     r   r   c                   @  s2   e Zd ZdZh dZdddZdd Z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.
    >   Zgrad_enabledZautocast_cpu_dtypeZtorch_function_enabledZautocast_cpu_enabledZautocast_cache_enabledZautocast_gpu_dtypeZautocast_enabledrN   r   c                 C  r   rQ   r   r<   r   r   r   r   ;  r   zGlobalContext.__init__c                 C  r   rQ   )r   r   r   r<   r   r   r   r   >  r   zGlobalContext.copy_graphstatec                 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)rp   r   r   r   _supported_global_statesr   r   values)r   r   r   argsr   r   r   r   A  s   
z GlobalContext.restore_graphstateNr   )r2   r3   r4   r   r   r   r   r   r   r   r   r   r   +  s    

r   c                   @  sZ   e Zd ZdddZdd Zdd Zdd	 Zd
d ZddddddZdddZ	dd Z
dS )	GuardsSetNc                 C  s   |d u rt  }|| _d S rQ   )r   inner)r   r   r   r   r   r   W  s   
zGuardsSet.__init__c                 C  
   t | jS rQ   )iterr   r<   r   r   r   __iter__\  r   zGuardsSet.__iter__c                 C  r   rQ   )r   r   r<   r   r   r   __len___  r   zGuardsSet.__len__c                 C  s   t | j|j S rQ   )r   r   r   r   r   r   __sub__d  rU   zGuardsSet.__sub__c                 C  r   rQ   )rO   r   r<   r   r   r   __bool__g  r   zGuardsSet.__bool__Tr   )collect_debug_stackskipguardru   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 Nr?   )r   )r   r}   r   extractr~   TracingContextextract_stackadd)r   r   r   r   r   r   r   r   j  s   



zGuardsSet.addothersr   c                 G  s&   |D ]}|D ]	}| j |dd qqd S r   )r   )r   r   ogr   r   r   updatet  s
   zGuardsSet.updatec                   s    fdd| j D | _ dS )z%Delete all guards with a given sourcec                   s   h | ]	}|j  kr|qS r   )rw   ).0r   r   r   r   	<setcomp>{  s    z6GuardsSet.remove_guards_with_source.<locals>.<setcomp>N)r   )r   r   r   r   r   remove_guards_with_sourcey  s   z#GuardsSet.remove_guards_with_sourcerQ   )r   ru   )r   r   )r2   r3   r4   r   r   r   r   r   r   r   r  r   r   r   r   r   V  s    


r   c                   @  r   )GuardsContextrN   r   c                 C  s   t  | _g | _d S rQ   )r   r   Zaotautograd_guardsr<   r   r   r   r     s   
zGuardsContext.__init__c                 C  s   t t| jjS rQ   )r   r   r   r   r<   r   r   r   r     rU   zGuardsContext.copy_graphstatec                 C  s   t |tsJ t|j| _d S rQ   )rp   r   r   r   r   r   r   r   r     s   z GuardsContext.restore_graphstateNr   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	dS )HopSubgraphCache	cache_keyr;   
identifierc                 C  r   rQ   r   r   r  r  r   r   r   add_dynamo_identifier  r   z&HopSubgraphCache.add_dynamo_identifierrN   r!   c                 C  r   rQ   r   r   r  r   r   r   get_dynamo_identifier  r   z&HopSubgraphCache.get_dynamo_identifierkeyr   c                 C  r   rQ   r   r   r  r
  r   r   r   add_autograd_key_entry  r   z'HopSubgraphCache.add_autograd_key_entryc                 C  r   rQ   r   r   r  r   r   r   get_autograd_key_entry  r   z'HopSubgraphCache.get_autograd_key_entryc                 C  r   rQ   r   r  r   r   r   add_proxy_dispatch_entry  r   z)HopSubgraphCache.add_proxy_dispatch_entryc                 C  r   rQ   r   r  r   r   r   get_proxy_dispatch_entry  r   z)HopSubgraphCache.get_proxy_dispatch_entryNr  r;   r  r;   r  r;   rN   r!   r  r;   r
  r   r  r;   )
r2   r3   r4   r   r  r	  r  r  r  r  r   r   r   r   r    s    r  c                   @  sR   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S )InvokeSubgraphCacherN   r   c                 C  s   i | _ i | _i | _d S rQ   )autograd_cacheproxy_dispatch_cachedynamo_identifiersr<   r   r   r   r     s   
zInvokeSubgraphCache.__init__r  r;   r  c                 C     || j |< d S rQ   )r  r  r   r   r   r    r   z)InvokeSubgraphCache.add_dynamo_identifierr!   c                 C     | j |d S rQ   )r  getr  r   r   r   r	    r   z)InvokeSubgraphCache.get_dynamo_identifierr
  r   c                 C  r  rQ   )r  r  r   r   r   r    r   z*InvokeSubgraphCache.add_autograd_key_entryc                 C  r  rQ   )r  r  r  r   r   r   r    r   z*InvokeSubgraphCache.get_autograd_key_entryc                 C  r  rQ   )r  r  r   r   r   r    r   z,InvokeSubgraphCache.add_proxy_dispatch_entryc                 C  r  rQ   )r  r  r  r   r   r   r    r   z,InvokeSubgraphCache.get_proxy_dispatch_entryNr   r  r  r  r  )
r2   r3   r4   r   r  r	  r  r  r  r  r   r   r   r   r    s    





r  c                   @  s    e Zd ZdddZddd	Zd
S )HopDispatchSetCacherN   r   c                 C  s   ddl m} |t i| _d S )Nr   )invoke_subgraph)Z'torch._higher_order_ops.invoke_subgraphr  r  hop_cache_map)r   r  r   r   r   r     s   zHopDispatchSetCache.__init__optorch._ops.HigherOrderOperatorOptional[HopSubgraphCache]c                 C  s   || j vrd S | j | S rQ   )r  )r   r  r   r   r   	get_cache  s   

zHopDispatchSetCache.get_cacheNr   )r  r   rN   r!  )r2   r3   r4   r   r"  r   r   r   r   r    s    
r  c                   @  sH   e Zd ZedddZedddZdd Zed	d
 Zedd ZdS )CompileContextrN   c                   C  s   t jd usJ t jS rQ   )_TLScompile_contextr   r   r   r   r    s   zCompileContext.getOptional[CompileContext]c                   C     t tdd S Nr%  getattrr$  r   r   r   r   try_get     zCompileContext.try_getc                 C  s,   |d u st |tsJ || _d| _g | _d S rV   )rp   r   r    r9   Zshape_env_guards)r   r    r   r   r   r     s   
zCompileContext.__init__c                  C  s   t  } | d u r
d S | jS rQ   )r#  r+  r    r<   r   r   r   current_compile_id  s   z!CompileContext.current_compile_idc                  C  s0   t  } | d u r
d S | jd u rd S t| j| jS rQ   )r#  r+  r    r8   r9   r<   r   r   r   current_trace_id  s   
zCompileContext.current_trace_idN)rN   r#  )rN   r&  )	r2   r3   r4   r   r  r+  r   r-  r.  r   r   r   r   r#    s    
r#  c                   @  s   e Zd ZdZedddZedddZdd	 Zd
d Zee	dd Z
edd Zeej	dd Zeej	dd Zeej	dd Zedd ZdS )r   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.
    rN   Optional[TracingContext]c                   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.)r   r+  RuntimeError)ctxr   r   r   r    s
   zTracingContext.getc                 C  sn   t  | _t | _t | _|| _g | _d | _d | _	d | _
d | _d | _d | _d | _d| _t | _d| _t | _d S NF)r  Zguards_contextr   Zmodule_contextr   global_context	fake_modeframe_summary_stackloc_in_frameZfw_metadataZaot_graph_nameZparams_flatZparams_flat_unwrap_subclassesZparams_unwrapped_to_flat_indexoutput_stridesZ#force_unspec_int_unbacked_size_liker   Ztensor_to_contextZfakify_first_callr  Zhop_dispatch_set_cache)r   r5  r   r   r   r     s    
zTracingContext.__init__c                 C  s   i | j _d S rQ   )r4  r   r<   r   r   r   clear@  s   zTracingContext.clearc                  k  s    i }t  }|  D ]	}t||||< q|  D ]
\}}t||| qzd V  W | D ]
\}}t||| q-d S | D ]
\}}t||| q>w rQ   )r   r  r   r*  r'   setattr)kwargsZpriorr2  r
  valr   r   r   patchE  s   zTracingContext.patchc                  C  s@   t  } | d u rt S | j}| jd ur|| jg }tj|S rQ   )r   r+  	tracebackStackSummaryr6  r7  	from_list)r   r}   r   r   r   r   V  s   
zTracingContext.extract_stackc                  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 )Nr6  r7  
real_stack)	r   r  unittestZmockr=  objectr*   hasattrrA  )tcr0   r   r   r   clear_frameb  s    

PzTracingContext.clear_framec              
   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 )NrA  )
r   r  r6  r   r7  r*   rD  r   rA  pop)frame_summaryrE  oldr0   r   r   r   current_frame  s*   





zTracingContext.current_framec                  c  sF    t  } | d u rd V  d S | j}g | _z
| jV  W || _d S || _w rQ   )r   r+  r8  )rE  Zold_output_stridesr   r   r   report_output_strides  s   
z$TracingContext.report_output_stridesc                 C  s   t j| ||ddt _d S )NF)lookup_line)r>  FrameSummaryr   r  r7  )filenamelinenoZ
frame_namer   r   r   set_current_loc  s   zTracingContext.set_current_locN)rN   r/  )rN   r   )r2   r3   r4   r   r   r+  r  r   r9  r   r=  r   
contextlibrF  rJ  rK  rP  r   r   r   r   r     s0    -
r   contextr&  c                 c  s0    t tdd }| t_z	| V  W |t_d S |t_w r(  )r*  r$  r%  )rR  old_contextr   r   r   r%    s   r%  r/  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.
    r0  NrA  )
r*  r$  r0  r*   rD  r   rA  r5  Z	shape_envcleanup)rR  rS  r0   r   r   r   tracing  s,   	




rU  c                   @  sT   e Zd Zdd Zdd Zdd Zdd	d
ZdddZdddZdddZ	dd Z
dS )rv   c                 C     dS r3  r   r<   r   r   r   is_dict_key  r   zSource.is_dict_keyc                 C  rV  r3  r   r<   r   r   r   is_ephemeral  r   zSource.is_ephemeralc                 C     t rQ   NotImplementedError)r   Zcodegenr   r   r   reconstruct  r   zSource.reconstructrN   r>   c                 C  rY  rQ   rZ  r<   r   r   r   r     r   zSource.guard_sourcer;   c                 C  rY  rQ   rZ  r<   r   r   r   r     r   zSource.nameru   c                 C  s   |   tju r	tt| |S rQ   )r   r>   rf   r[  ru   )r   fnr   r   r   
make_guard  s   
zSource.make_guardrO   c                 C  s   |    S rQ   )r   r[   r<   r   r   r   r[     s   zSource.is_specialized_nn_modulec                 C  s   |   tjkS )z+True if you can guard on attributes of this)r   r>   rg   r<   r   r   r   subguards_allowed  s   zSource.subguards_allowedNr   r   )rN   ru   rd   )r2   r3   r4   rW  rX  r\  r   r   r^  r[   r_  r   r   r   r   rv     s    



rv   c                   @  s0   e Zd ZU ded< dd Zdd Zddd	Zd
S )ChainedSourcerv   basec                 C  r   rQ   )ra  rW  r<   r   r   r   rW    r   zChainedSource.is_dict_keyc                 C  r   rQ   )ra  rX  r<   r   r   r   rX    r   zChainedSource.is_ephemeralrN   c                 C  s"   | }t |tr|j}t |ts|S rQ   )rp   r`  ra  )r   currentr   r   r   get_base  s
   

zChainedSource.get_baseN)rN   rv   )r2   r3   r4   r5   rW  rX  rc  r   r   r   r   r`    s
   
 r`  inputsr   c                 C  sB  ddl 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 ]\}}
t|
|rY||
jd|f qG|r|d \}}}|dd D ]3\}}}||u sJ d	| d
| d| d| d
| d| d| d| d|j d| d| d|j qi|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   )
FakeTensorFakeTensorModeNztracing context _get_current_dispatch_mode_stackzactive fake modezfake tensor inputr?   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_tensorre  rf  r   r+  r5  r   torch.utils._python_dispatchrh  	enumeratereversedrp   pytreeZtree_leavesr}   )rd  re  rf  Z
fake_modesrR  r5  rh  imZflat_inputsZ
flat_inputZdesc1i1Zdesc2i2r   r   r   detect_fake_mode  sH   



&rr  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   )rf  rg  N)ri  rf  rj  rh  rk  rl  rp   )rf  rh  r:   ro  r   r   r   active_fake_mode0  s   
rs  )rR  r&  )rR  r/  rQ   )rd  r   )M
__future__r   rQ  dataclassesenumr   loggingre	threadingr>  Zunittest.mockrB  r   abcr   r   r   typingr   r   r   r	   r
   r   r   r   r   Ztorch.utilsr   rm  Ztorch.utils._backport_slotsr   Ztorch.utils._tracebackr   r   Ztorch.utils.weakr   	getLoggerr2   r   Zsympycompiler#   r$   r   r8   Enumr>   ri   rk   rr   ru   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  localr$  r#  r   r%  rU  rv   r`  rr  rs  r   r   r   r   <module>   s   (

2>
 %!
(" .	

,