a
    h]                     @  sZ  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 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*m+Z+ d dl,Z,e-dZ.e-dZ/eddG dd dZ0G dd deZ1G dd dej2Z3G dd dZ4ejddG dd dZ5G dd deZ6e!ejG dd dZ7edZ8ejddG d d! d!Z9ejddG d"d# d#e9Z:ejddG d$d% d%e9Z;G d&d' d'ee8 Z<G d(d) d)Z=G d*d+ d+Z>G d,d- d-e<e> Z?G d.d/ d/Z@G d0d1 d1e<e@ ZAG d2d3 d3ZBG d4d5 d5e<e= ZCG d6d7 d7ZDG d8d9 d9eDZEG d:d; d;ZFeG ZHG d<d= d=ZIG d>d? d?ZJed@dAdBdCZKedDdAdEdFZLejddG dGdH dHZMejddG dIdJ dJeMZNdQdKdLdMdNZOdOdP ZPdS )R    )annotationsN)abstractmethod)defaultdict)contextmanager)	dataclass)AnyCallableGeneric
NamedTupleOptionalTYPE_CHECKINGTypeVarUnion)_pytree)dataclass_slots)CapturedTracebackformat_frame)WeakTensorKeyDictionary)CodeTypez-^(?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                   @  sD   e Zd ZU ded< ded< dZded< dd Zedd	d
dZdS )	CompileIdOptional[int]frame_idframe_compile_idNcompiled_autograd_idc                 C  s   | j d urT| jd u | jd u ks"J d}| jd urDd| j d| j }d| j  | S | jd urh| jd uslJ | j d| j S d S )N /!)r   r   r   )selfZ	frame_str r   ;/var/www/auris/lib/python3.9/site-packages/torch/_guards.py__str__V   s    

zCompileId.__str__Optional[str])
compile_idc              
   C  s   |du rdS zft tfD ]T}|| }r| }| D ]\}}|dur8t|||< q8| f i |  W S qtW n6 ty } ztd| d|W Y d}~n
d}~0 0 dS )z
        Factory method that creates a CompileId from its string representation.
        Keep this in sync with the __str__ method.
        NzInvalid compile_id '')COMPILE_ID_PATTERNCA_COMPILE_ID_PATTERNmatch	groupdictitemsint
ValueError	Exception)clsr#   patternr'   groupskver   r   r    from_stringc   s    zCompileId.from_string)__name__
__module____qualname____annotations__r   r!   classmethodr3   r   r   r   r    r   G   s   
r   c                   @  s&   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 d S )Nr   _)r:   strr#   r   r   r   r    r!      s    

zTraceId.__str__Nr4   r5   r6   r7   r!   r   r   r   r    r9   z   s   
r9   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dZddddZddddZddddZdd ZdS )GuardSourcer                           	   
                  boolreturnc                 C  s   | t jt jfv S N)r?   GLOBAL_FSDP_MODULELOCAL_FSDP_MODULEr=   r   r   r    is_fsdp_module   s    zGuardSource.is_fsdp_modulec                 C  s@   dd l m  m} |jr0| 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_MODULErU   )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 rR   )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  s   | t jt jfv S rR   )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 rR   )r?   LOCALrZ   rT   r]   r_   r=   r   r   r    is_local   s    zGuardSource.is_localN)r4   r5   r6   rb   GLOBALrZ   rY   CONSTANTZRANDOM_VALUEZ	SHAPE_ENVrT   rS   ZBACKWARD_STATEZ	EPHEMERALSYNTHETIC_LOCALr]   r\   r_   r^   rU   r[   r`   ra   rc   r   r   r   r    r?      s*   r?   c                   @  s   e Zd ZdS )GuardBuilderBaseNr4   r5   r6   r   r   r   r    rg      s   rg   c                   @  s&   e Zd ZU ded< ded< dd ZdS )SLocz,Optional[Union[traceback.FrameSummary, str]]framework_locr"   maybe_user_locc                 C  sH   t | jtr| jnt| j}| jd ur8| j d| dS d| dS d S )Nz ()()
isinstancerj   r<   r   rk   )r   Zflocr   r   r    r!      s    

zSLoc.__str__Nr>   r   r   r   r    ri      s   
ri   c                   @  s&   e Zd ZU ded< ded< ded< dS )
ShapeGuardzsympy.logic.boolalg.Booleanexprri   ZslocrO   Zsize_obliviousNr4   r5   r6   r7   r   r   r   r    ro      s   
ro   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ddddZeddd d!Zed"d# Zd$d% Zd&d' Zd(d)d*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 ZdS )4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 rR   )r|   hashnamesourceidru   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
r2| j
jndt| j| j|  jjfS )N)rn   ru   	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 rR   )r   r   otherr   r   r    __lt__%  s    zGuard.__lt__c                 C  s    t | jtjr| jjS | jS d S rR   )rn   ru   r   r   r   r=   r   r   r    r   (  s    zGuard.inner_create_fnr<   rP   c                 C  s
   | j  S rR   )rt   r~   r=   r   r   r    r~   .  s    z
Guard.namer?   c                 C  s
   | j  S rR   )rt   guard_sourcer=   r   r   r    r   2  s    zGuard.sourcec                 C  sh   t | tjr\|  }|durFdtt|  d|jj dtt| dS dtt|  dS nt| S d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>)rn   weakrefReferenceTypehexr   	__class__r4   r<   )rx   objr   r   r    weakref_to_str6  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   r4   rv   rw   r   rx   ry   )r   sr   r   r    __repr__O  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   r4   rv   rw   r   rx   ry   )r   outputr   r   r   r    r!   [  s    zGuard.__str__rg   )builderc                 C  sf   z|  || W S  ty`   tdt|   | jrZtdd| j	 dd     Y n0 d S )NzError while creating guard:
%szCreated at:
%sr   )
ru   r,   log	exceptionr<   rstriprz   errorjoinformat)r   r   r   r   r    createf  s    $zGuard.createc                 C  s
   | j  S rR   )r   r[   r=   r   r   r    r[   o  s    zGuard.is_specialized_nn_modulec                 C  s
   | j  S rR   )r   rU   r=   r   r   r    rU   r  s    zGuard.is_fsdp_modulec                 C  s
   | j  S rR   )r   rc   r=   r   r   r    rc   u  s    zGuard.is_localc                 C  s   | j sg | _ | j | | j|d fv s.J d|| _| jsB|| _n| j| | j|d fv szt| jrr|  d u szJ d|| _d S )Nz+Guarded class id must be identical, or NonezBGuarded object must be identical, None or ephemeral (dead weakref))rv   appendry   rw   extendrx   callable)r   Z
guard_typeZguarded_classrw   rx   r   r   r    set_export_infox  s,    
zGuard.set_export_info)r4   r5   r6   r7   rv   rw   rx   ry   rz   r{   r|   r   r   r   r   propertyr~   r   staticmethodr   r   r!   r   r[   rU   rc   r   r   r   r   r    rr      s4   

	rr   Tc                   @  s   e Zd ZdS )GuardEnvExprNrh   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 )DuplicateInputsrs   input_source_ainput_source_bc                 C  s   | j | jksJ d S rR   )r   r   r=   r   r   r    __post_init__  s    zDuplicateInputs.__post_init__N)r4   r5   r6   r7   r   r   r   r   r    r     s   
r   c                   @  s   e Zd ZU ded< ded< dS )StorageOverlapzlist[Source]Zoverlapping_sourcesZnon_overlapping_sourcesNrq   r   r   r   r    r     s   
r   c                   @  s0   e Zd ZeddddZeddddZdS )	Checkpointabler   rP   c                 C  s   d S rR   r   r=   r   r   r    copy_graphstate  s    zCheckpointable.copy_graphstate)statec                 C  s   d S rR   r   r   r   r   r   r    restore_graphstate  s    z!Checkpointable.restore_graphstateN)r4   r5   r6   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  s
   || _ d S rR   )r   )r   r   r   r   r    __init__  s    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  s   |  |d u S rR   r   r   r   r   r    __eq__  s    zGuardsCheckpointState.__eq__N)
r4   r5   r6   __doc__setr   r7   r   r   r   r   r   r   r    r     s
   
r   c                   @  s2   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  s
   || _ d S rR   r   )r   r   r   r   r    r     s    z%ModuleContextCheckpointState.__init__c                 C  s2   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     s    z!ModuleContextCheckpointState.diffc                 C  s   |  |d u S rR   r   r   r   r   r    r     s    z#ModuleContextCheckpointState.__eq__N)r4   r5   r6   r   r7   r   r   r   r   r   r   r    r     s   
r   c                   @  s*   e Zd ZddddZdd Zdd Zd	S )
ModuleContextNonerP   c                 C  s
   i | _ d S rR   r   r=   r   r   r    r     s    zModuleContext.__init__c                 C  s   t t| jS rR   )r   dictr   r=   r   r   r    r     s    zModuleContext.copy_graphstatec                 C  s   t |tsJ |j| _d S rR   )rn   r   r   r   r   r   r    r     s    z ModuleContext.restore_graphstateNr4   r5   r6   r   r   r   r   r   r   r    r     s   r   c                   @  s2   e Zd ZU i Zded< dd Zdd Zdd Zd	S )
GlobalContextCheckpointStatezdict[str, tuple[Callable, ...]]global_statec                 C  s
   || _ d S rR   r   )r   Zglobal_statesr   r   r    r     s    z%GlobalContextCheckpointState.__init__c                 C  s2   t | j t |j }t|dkr.dS |S )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     s    z!GlobalContextCheckpointState.diffc                 C  s   |  |d u S rR   r   r   r   r   r    r   *  s    z#GlobalContextCheckpointState.__eq__N)r4   r5   r6   r   r7   r   r   r   r   r   r   r    r     s   
r   c                   @  s6   e Zd ZdZh dZd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_enabledZautocast_cpu_dtypeZautocast_gpu_dtypeZautocast_enabledZautocast_cache_enabledr   rP   c                 C  s
   i | _ d S rR   r   r=   r   r   r    r   =  s    zGlobalContext.__init__c                 C  s   t t| jS rR   )r   r   r   r=   r   r   r    r   @  s    zGlobalContext.copy_graphstatec                 C  sf   t |tsJ |j| _t| jt| jkr>t| j | jksFJ d| j D ]\}}|| qPd S )NzGlobal state mismatch)rn   r   r   r   _supported_global_statesr   r   values)r   r   r   argsr   r   r    r   C  s    z GlobalContext.restore_graphstateN)r4   r5   r6   r   r   r   r   r   r   r   r   r    r   .  s
   	r   c                   @  sb   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dZddddZ	dd Z
dS )	GuardsSetNc                 C  s   |d u rt  }|| _d S rR   )r   inner)r   r   r   r   r    r   Q  s    zGuardsSet.__init__c                 C  s
   t | jS rR   )iterr   r=   r   r   r    __iter__V  s    zGuardsSet.__iter__c                 C  s
   t | jS rR   )r   r   r=   r   r   r    __len__Y  s    zGuardsSet.__len__c                 C  s   t | j|j S rR   )r   r   r   r   r   r    __sub__^  s    zGuardsSet.__sub__c                 C  s
   t | jS rR   )rO   r   r=   r   r   r    __bool__a  s    zGuardsSet.__bool__Tr   )collect_debug_stackskiprr   )guardc                C  sR   || j v rd S |rB|jd u r.tjd| d|_|jd u rBt |_| j | d S Nr@   )r   )r   rz   r   extractr{   TracingContextextract_stackadd)r   r   r   r   r   r   r    r   d  s    



zGuardsSet.addr   )othersc                 G  s&   |D ]}|D ]}| j |dd qqd S r   )r   )r   r   ogr   r   r    updaten  s    zGuardsSet.updatec                   s(   ddl m   fdd| jD | _dS )z.Delete all guards that contains a given sourcer@   )is_from_sourcec                   s   h | ]} |j s|qS r   )rt   ).0r   r   r   r   r    	<setcomp>w  s   z6GuardsSet.remove_guards_with_source.<locals>.<setcomp>N)Z_dynamo.sourcer   r   )r   r   r   r   r    remove_guards_with_sources  s    z#GuardsSet.remove_guards_with_source)N)r4   r5   r6   r   r   r   r   r   r   r   r   r   r   r   r    r   P  s   

r   c                   @  s*   e Zd ZddddZdd Zdd Zd	S )
GuardsContextr   rP   c                 C  s   t  | _g | _d S rR   )r   r   Zaotautograd_guardsr=   r   r   r    r     s    zGuardsContext.__init__c                 C  s   t t| jjS rR   )r   r   r   r   r=   r   r   r    r     s    zGuardsContext.copy_graphstatec                 C  s   t |tsJ t|j| _d S rR   )rn   r   r   r   r   r   r   r    r     s    z GuardsContext.restore_graphstateNr   r   r   r   r    r     s   r   c                   @  s   e Zd ZedddddZeddddd	Zedd
dddZeddddZedd
dddZeddddZ	eddddddZ
eddddddZdS )HopSubgraphCacher*   r<   fn_id
identifierc                 C  s   d S rR   r   r   r   r   r   r   r    add_dynamo_installed_submodule  s    z/HopSubgraphCache.add_dynamo_installed_submodule	list[str]r   rQ   c                 C  s   d S rR   r   r   r   r   r   r    get_dynamo_installed_submodules  s    z0HopSubgraphCache.get_dynamo_installed_submodulesr   r   keyc                 C  s   d S rR   r   r   r   r   r   r   r    add_autograd_key_entry  s    z'HopSubgraphCache.add_autograd_key_entryr   c                 C  s   d S rR   r   r   r   r   r   r    get_autograd_key_entry  s    z'HopSubgraphCache.get_autograd_key_entryc                 C  s   d S rR   r   r   r   r   r    add_proxy_dispatch_entry  s    z)HopSubgraphCache.add_proxy_dispatch_entryc                 C  s   d S rR   r   r   r   r   r    get_proxy_dispatch_entry  s    z)HopSubgraphCache.get_proxy_dispatch_entrytuple[object]torch.fx.GraphModuler   tangent_metadatagmodc                 C  s   d S rR   r   )r   r   r  r  r   r   r    add_lazy_bwd_entry  s    z#HopSubgraphCache.add_lazy_bwd_entry)r   r  rQ   c                 C  s   d S rR   r   r   r   r  r   r   r    get_lazy_bwd_entry  s    z#HopSubgraphCache.get_lazy_bwd_entryN)r4   r5   r6   r   r   r   r   r   r   r   r  r  r   r   r   r    r     s    r   c                   @  s   e Zd ZddddZddddd	Zdd
dddZdddddZddddZdddddZddddZ	ddddddZ
ddddd Zd!S )"InvokeSubgraphCacher   rP   c                 C  s$   i | _ i | _tt| _tt| _d S rR   )autograd_cacheproxy_dispatch_cacher   listdynamo_installed_submodulesr   lazy_bwd_cacher=   r   r   r    r     s
    
zInvokeSubgraphCache.__init__r*   r<   r   c                 C  s   | j | | d S rR   )r  r   r   r   r   r    r     s    z2InvokeSubgraphCache.add_dynamo_installed_submoduler   r   c                 C  s   | j |g S rR   )r  getr   r   r   r    r     s    z3InvokeSubgraphCache.get_dynamo_installed_submodulesr   r   c                 C  s   || j |< d S rR   )r
  r   r   r   r    r     s    z*InvokeSubgraphCache.add_autograd_key_entryr   c                 C  s   | j |d S rR   )r
  r  r   r   r   r    r     s    z*InvokeSubgraphCache.get_autograd_key_entryc                 C  s   || j |< d S rR   )r  r   r   r   r    r     s    z,InvokeSubgraphCache.add_proxy_dispatch_entryc                 C  s   | j |d S rR   )r  r  r   r   r   r    r     s    z,InvokeSubgraphCache.get_proxy_dispatch_entryr  r  r  c                 C  s$   t | j| }||f| j| |< |S rR   )r   r  )r   r   r  r  Z	num_gmodsr   r   r    r    s    z&InvokeSubgraphCache.add_lazy_bwd_entry)r   r  c                 C  s    || j vrdS | j | |dS )N)NN)r  r  r  r   r   r    r    s    
z&InvokeSubgraphCache.get_lazy_bwd_entryN)r4   r5   r6   r   r   r   r   r   r   r   r  r  r   r   r   r    r	    s   r	  c                   @  s*   e Zd ZddddZddddd	Zd
S )HopDispatchSetCacher   rP   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__ztorch._ops.HigherOrderOperatorzOptional[HopSubgraphCache])oprQ   c                 C  s   || j vrd S | j | S rR   )r  )r   r  r   r   r    	get_cache  s    
zHopDispatchSetCache.get_cacheN)r4   r5   r6   r   r  r   r   r   r    r    s   r  c                   @  sP   e Zd Zed dddZeddddZdd Zed	d
 Zedd ZdS )CompileContextrP   c                   C  s   t jd usJ t jS rR   )_TLScompile_contextr   r   r   r    r    s    zCompileContext.getOptional[CompileContext]c                   C  s   t tdd S Nr  getattrr  r   r   r   r    try_get
  s    zCompileContext.try_getc                 C  s,   |d u st |tsJ || _d| _g | _d S rV   )rn   r   r#   r:   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 rR   )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 rR   )r  r  r#   r9   r:   r=   r   r   r    current_trace_id  s    
zCompileContext.current_trace_idN)	r4   r5   r6   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dZed dddZdd	 Zd
d Zee	dd Z
edd Z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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.
    Optional[TracingContext]rP   c                   C  s   t tdd S )Ntracing_contextr  r   r   r   r    r  .  s    zTracingContext.try_getc                  C  s   t   } r| S tdd S )Nz<TracingContext.get() must be called within an ongoing trace.)r   r  RuntimeError)ctxr   r   r    r  2  s
    zTracingContext.getc                 C  s   t  | _t | _t | _t | _t | _|| _	g | _
d | _d | _d | _d | _d | _d | _d | _d| _t | _d| _t | _g | _d S NF)r   Zguards_contextr   Zmodule_contextr   global_contextr   previously_inlined_functionspreviously_cleaned_instructions	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traced_code)r   r'  r   r   r    r   :  s&    
zTracingContext.__init__c                 C  s    i | j _| j  | j  d S rR   )r$  r   r%  clearr&  r=   r   r   r    r,  k  s    
zTracingContext.clearc                  k  s   i }t  }|  D ]}t||||< q|  D ]\}}t||| q0z(d V  W | D ]\}}t||| qXn | D ]\}}t||| qx0 d S rR   )r   r  r   r  r)   setattr)kwargsZpriorr"  r   valr   r   r    patchr  s    zTracingContext.patchc                  C  sB   t  } | d u rt S | j}| jd ur6||  g }tj|S rR   )r   r  	tracebackStackSummaryr(  r)  _populate_loc_in_frame_summary	from_list)r   rz   r   r   r    r     s    
zTracingContext.extract_stackc                 C  s,   | j d usJ | j \}}}tj|||ddS )NF)lookup_line)r)  r1  FrameSummary)r   filenamelineno
frame_namer   r   r    r3    s    z-TracingContext._populate_loc_in_frame_summaryc                  c  s   t  } tjj| dg  tjj| dd R z
d V  W n6 typ } zt|dsZd |_ W Y d }~n
d }~0 0 W d    n1 s0    Y  W d    n1 s0    Y  d S )Nr(  r)  
real_stack)	r   r  unittestZmockr0  objectr,   hasattrr:  )tcr2   r   r   r    clear_frame  s    

zTracingContext.clear_framec              
   c  s   t  }| d ur|j|  |j}d |_zbz
d V  W n: tyn } z"t|dsX| |_ W Y d }~n
d }~0 0 W | d ur|j	  ||_n| d ur|j	  ||_0 d S )Nr:  )
r   r  r(  r   r)  r,   r=  r   r:  pop)frame_summaryr>  oldr2   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 || _n|| _0 d S rR   )r   r  r*  )r>  Zold_output_stridesr   r   r    report_output_strides  s    
z$TracingContext.report_output_stridesc                 C  s   | ||ft  _d S rR   )r   r  r)  )r7  r8  r9  r   r   r    set_current_loc  s    zTracingContext.set_current_locc                  C  s   t  } | d u rd S | jS rR   )r   r  r+  )r>  r   r   r    get_traced_code  s    zTracingContext.get_traced_codeN)r4   r5   r6   r   r   r  r  r   r,  r   r0  r   r3  
contextlibr?  rC  rD  rE  rF  r   r   r   r    r   &  s4   1
	
r   r  )contextc                 c  s0   t tdd }| t_z| V  W |t_n|t_0 d S r  )r  r  r  )rH  old_contextr   r   r    r    s
    r  r  c              
   c  s   t tdd}| t_zz
| V  W nB ty` } z*t|dsJ| durJ|  |_ W Y d}~n
d}~0 0 W | dur| jdur| jjdur| jj	  |t_n2| dur| jdur| jjdur| jj	  |t_0 dS )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  r  r   r,   r=  r   r:  r'  Z	shape_envcleanup)rH  rI  r2   r   r   r    tracing  s0    	



rK  c                   @  sd   e Zd Zdd Zdd Zdd Zddd	d
ZddddZddddZddddZ	dd Z
dS )rs   c                 C  s   dS r#  r   r=   r   r   r    is_dict_key  s    zSource.is_dict_keyc                 C  s   dS r#  r   r=   r   r   r    is_ephemeral  s    zSource.is_ephemeralc                 C  s   t d S rR   NotImplementedError)r   Zcodegenr   r   r    reconstruct  s    zSource.reconstructr?   rP   c                 C  s   t d S rR   rN  r=   r   r   r    r     s    zSource.guard_sourcer<   c                 C  s   t d S rR   rN  r=   r   r   r    r~     s    zSource.namerr   c                 C  s   |   tju rtt| |S rR   )r   r?   re   rO  rr   )r   fnr   r   r    
make_guard  s    zSource.make_guardrO   c                 C  s   |    S rR   )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?   rf   r=   r   r   r    subguards_allowed%  s    zSource.subguards_allowedN)r4   r5   r6   rL  rM  rP  r   r~   rR  r[   rS  r   r   r   r    rs     s   rs   c                   @  s4   e Zd ZU ded< dd Zdd Zdddd	Zd
S )ChainedSourcers   basec                 C  s
   | j  S rR   )rU  rL  r=   r   r   r    rL  /  s    zChainedSource.is_dict_keyc                 C  s
   | j  S rR   )rU  rM  r=   r   r   r    rM  3  s    zChainedSource.is_ephemeralrP   c                 C  s   | }t |tr|j}q|S rR   )rn   rT  rU  )r   currentr   r   r    get_base6  s    
zChainedSource.get_baseN)r4   r5   r6   r7   rL  rM  rW  r   r   r   r    rT  +  s   
rT  r   )inputsc                 C  sH  ddl m}m} g }t  }r>|j}|dur>||ddf ddlm} t	t
| D ]"\}}t||rX||d|f qXt| }	t	|	D ]$\}}
t|
|r||
jd|f q|r@|d \}}}|dd D ]f\}}}||u sJ d	| d
| d| d| d
| d| d| d| d|j d| d| d|j q|S d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_tensorrY  rZ  r   r  r'  r   torch.utils._python_dispatchr\  	enumeratereversedrn   pytreeZtree_leavesrz   )rX  rY  rZ  Z
fake_modesrH  r'  r\  imZflat_inputsZ
flat_inputZdesc1i1Zdesc2i2r   r   r    detect_fake_mode=  sD    



&rf  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   )rZ  r[  N)r]  rZ  r^  r\  r_  r`  rn   )rZ  r\  r;   rc  r   r   r    active_fake_modei  s    

rg  )N)Q
__future__r   rG  Zdataclassesenumr   loggingre	threadingr1  Zunittest.mockr;  r   abcr   collectionsr   r   r   typingr   r   r	   r
   r   r   r   r   r   Ztorch.utilsr   ra  Ztorch.utils._backport_slotsr   Ztorch.utils._tracebackr   r   Ztorch.utils.weakr   	getLoggerr4   r   typesr   Zsympycompiler%   r&   r   r9   Enumr?   rg   ri   ro   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  localr  r  r   r  rK  rs   rT  rf  rg  r   r   r   r    <module>   s   (


2L
 %




"4!-" @	

,