U
    zhKt                     @  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mZ d dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dl m!Z! e"e#Z$erd dl%Z%d dl&Z&G d	d
 d
eZ'G dd deZ(G dd dej)Z*G dd dZ+G dd deZ,ej-G dd dZ.edZ/ej-G dd dZ0ej-G dd de0Z1G dd dee/ Z2G dd dZ3G dd dZ4G d d! d!e2e4 Z5G d"d# d#Z6G d$d% d%e2e6 Z7G d&d' d'Z8G d(d) d)e2e3 Z9e: Z;G d*d+ d+Z<G d,d- d-Z=ed.d/d0d1Z>ed2d/d3d4Z?ej-d5d6G d7d8 d8Z@ej-d5d6G d9d: d:e@ZAdAd;d<d=d>ZBd?d@ ZCdS )B    )annotationsN)abstractmethod)contextmanager)AnyCallableDictGenericList
NamedTupleOptionalSetTupleTYPE_CHECKINGTypeVar)_pytree)CapturedTraceback)WeakTensorKeyDictionaryc                   @  s&   e Zd ZU ded< ded< dd ZdS )	CompileIdintframe_idframe_compile_idc                 C  s   | j  d| j S )N/)r   r   self r   ?/var/www/html/venv/lib/python3.8/site-packages/torch/_guards.py__str__@   s    zCompileId.__str__N__name__
__module____qualname____annotations__r   r   r   r   r   r   7   s   
r   c                   @  s&   e Zd ZU ded< ded< dd ZdS )TraceIdr   
compile_idr   attemptc                 C  s*   | j dkrt| jS | j d| j  S d S )Nr   _)r$   strr#   r   r   r   r   r   J   s    

zTraceId.__str__Nr   r   r   r   r   r"   D   s   
r"   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dddZddddZdd ZdS )GuardSourcer                           	   
      boolreturnc                 C  s   | t jt jfkS N)r'   GLOBAL_FSDP_MODULELOCAL_FSDP_MODULEr   r   r   r   is_fsdp_module_   s    zGuardSource.is_fsdp_modulec                 C  s   | t jt jfkp|  S r6   )r'   GLOBAL_NN_MODULELOCAL_NN_MODULEr9   r   r   r   r   is_nn_moduleb   s    zGuardSource.is_nn_modulec                 C  s   | t jt jt jfkS r6   )r'   LOCALr;   r8   r   r   r   r   is_locall   s
    zGuardSource.is_localN)r   r   r    r=   GLOBALr;   r:   CONSTANTZRANDOM_VALUEZ	SHAPE_ENVr8   r7   ZBACKWARD_STATEZ	EPHEMERALSYNTHETIC_LOCALr9   r<   r>   r   r   r   r   r'   Q   s   
r'   c                   @  s   e Zd ZdS )GuardBuilderBaseNr   r   r    r   r   r   r   rB      s   rB   c                   @  s   e Zd ZU ded< ded< dS )
ShapeGuardz
sympy.Exprexprr   stackN)r   r   r    r!   r   r   r   r   rD      s   
rD   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]rF   z Optional[traceback.StackSummary]
user_stackzOptional[int]_hashc                 C  s*   | j d kr$t| j| jt| jf| _ | j S r6   )rP   hashnamesourceidrJ   r   r   r   r   __hash__   s    
zGuard.__hash__c                 C  sT   ddl m} t| jtjo&| jj|jk}|| jr8| jj	ndt
| j| j|  jjfS )Nr(   )GuardBuilder)Z_dynamo.guardsrV   
isinstancerJ   	functoolspartialfuncZDUPLICATE_INPUTrS   valuelenrR   inner_create_fn__code__co_firstlineno)r   rV   Zis_duplicate_inputr   r   r   sort_key   s    
zGuard.sort_keyc                 C  s   |   |  k S r6   )ra   r   otherr   r   r   __lt__   s    zGuard.__lt__c                 C  s    t | jtjr| jjS | jS d S r6   )rX   rJ   rY   rZ   r[   r   r   r   r   r^      s    zGuard.inner_create_fnr&   r4   c                 C  s
   | j  S r6   )rI   rR   r   r   r   r   rR      s    z
Guard.namer'   c                 C  s
   | j  S r6   )rI   guard_sourcer   r   r   r   rS      s    zGuard.sourcec                 C  sh   t | tjr\|  }|dk	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>)rX   weakrefReferenceTypehexrT   	__class__r   r&   )rM   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	
          z&
        {
            'guard_types': z,
            'code': z,
            'obj_weakref': z
            'guarded_class': z
        }
        )rS   rR   lowerreprr^   r   rK   rL   rl   rM   rN   )r   sr   r   r   __repr__   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: 
rm   z    Source: z    Create Function: z    Guard Types: z    Code List: z    Object Weakref: z    Guarded Class Weakref: )rp   rR   rS   ro   r^   r   rK   rL   rl   rM   rN   )r   outputrS   r   r   r   r      s    zGuard.__str__rB   )builderc                 C  sh   z|  || W S  tk
rb   tdt|   | jr\tdd| j	 dd     Y nX d S )NzError while creating guard:
%szCreated at:
%srm   )
rJ   	Exceptionlog	exceptionr&   rstriprF   errorjoinformat)r   ru   r   r   r   create  s    $zGuard.createc                 C  s
   | j  S r6   )rS   r<   r   r   r   r   r<     s    zGuard.is_nn_modulec                 C  s
   | j  S r6   )rS   r9   r   r   r   r   r9     s    zGuard.is_fsdp_modulec                 C  s
   | j  S r6   )rS   r>   r   r   r   r   r>     s    zGuard.is_localc                 C  s   | j st | _ | j | | j|d fks0td|| _| jsD|| _n| j| | j|d fks|t| jrt|  d ks|td|| _d S )Nz+Guarded class id must be identical, or NonezBGuarded object must be identical, None or ephemeral (dead weakref))	rK   listappendrN   AssertionErrorrL   extendrM   callable)r   Z
guard_typeZguarded_classrL   rM   r   r   r   set_export_info  s4    
	zGuard.set_export_info)r   r   r    r!   rK   rL   rM   rN   rF   rO   rP   rU   ra   rd   r^   propertyrR   rS   staticmethodrl   rr   r   r~   r<   r9   r>   r   r   r   r   r   rG      s4   

	rG   Tc                   @  s   e Zd ZdS )GuardEnvExprNrC   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 )DuplicateInputsrH   input_source_ainput_source_bc                 C  s   | j | jkstd S r6   )r   r   r   r   r   r   r   __post_init__O  s    zDuplicateInputs.__post_init__N)r   r   r    r!   r   r   r   r   r   r   J  s   
r   c                   @  s0   e Zd ZeddddZeddddZdS )	Checkpointabler   r4   c                 C  s   d S r6   r   r   r   r   r   copy_graphstatea  s    zCheckpointable.copy_graphstate)statec                 C  s   d S r6   r   r   r   r   r   r   restore_graphstatee  s    z!Checkpointable.restore_graphstateN)r   r   r    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 r6   )r   )r   r   r   r   r   __init__q  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   rc   rr   r   r   difft  s    zGuardsCheckpointState.diffc                 C  s   |  |d kS r6   r   rb   r   r   r   __eq__  s    zGuardsCheckpointState.__eq__N)
r   r   r    __doc__setr   r!   r   r   r   r   r   r   r   r   j  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 r6   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 kS r6   r   rb   r   r   r   r     s    z#ModuleContextCheckpointState.__eq__N)r   r   r    r   r!   r   r   r   r   r   r   r   r     s   
r   c                   @  s$   e Zd Zdd Zdd Zdd ZdS )ModuleContextc                 C  s
   i | _ d S r6   r   r   r   r   r   r     s    zModuleContext.__init__c                 C  s   t t| jS r6   )r   dictr   r   r   r   r   r     s    zModuleContext.copy_graphstatec                 C  s   t |tst|j| _d S r6   )rX   r   r   r   r   r   r   r   r     s    z ModuleContext.restore_graphstateNr   r   r    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 r6   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 kS r6   r   rb   r   r   r   r     s    z#GlobalContextCheckpointState.__eq__N)r   r   r    r   r!   r   r   r   r   r   r   r   r     s   
r   c                   @  s:   e Zd ZdZdddddddhZ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torch_function_enabledZautocast_enabledZautocast_cpu_enabledZautocast_gpu_dtypeZautocast_cpu_dtypeZautocast_cache_enabledc                 C  s
   i | _ d S r6   r   r   r   r   r   r     s    zGlobalContext.__init__c                 C  s   t t| jS r6   )r   r   r   r   r   r   r   r     s    zGlobalContext.copy_graphstatec                 C  sf   t |tst|j| _t| jt| jkr>t| j | jksFtd| j D ]\}}|| qPd S )NzGlobal state mismatch)	rX   r   r   r   r]   _supported_global_statesr   r   values)r   r   r[   argsr   r   r   r     s    z GlobalContext.restore_graphstateN)r   r   r    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 krt  }|| _d S r6   )r   inner)r   r   r   r   r   r     s    zGuardsSet.__init__c                 C  s
   t | jS r6   )iterr   r   r   r   r   __iter__  s    zGuardsSet.__iter__c                 C  s
   t | jS r6   )r]   r   r   r   r   r   __len__  s    zGuardsSet.__len__c                 C  s   t | j|j S r6   )r   r   rb   r   r   r   __sub__  s    zGuardsSet.__sub__c                 C  s
   t | jS r6   )r3   r   r   r   r   r   __bool__  s    zGuardsSet.__bool__Tr   )collect_debug_stackskiprG   )guardc                C  sR   || j krd S |rB|jd kr.tjd| d|_|jd krBt |_| j | d S Nr(   )r   )r   rF   r   extractrO   TracingContextextract_stackadd)r   r   r   r   r   r   r   r     s    



zGuardsSet.addr   )othersc                 G  s&   |D ]}|D ]}| j |dd qqd S r   )r   )r   r   ogr   r   r   update  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   )rI   ).0r   rS   r   r   	<setcomp>  s     
 z6GuardsSet.remove_guards_with_source.<locals>.<setcomp>N)r   )r   rS   r   r   r   remove_guards_with_source
  s    z#GuardsSet.remove_guards_with_source)N)r   r   r    r   r   r   r   r   r   r   r   r   r   r   r   r     s   

r   c                   @  s$   e Zd Zdd Zdd Zdd ZdS )GuardsContextc                 C  s   t  | _g | _d S r6   )r   r   Zaotautograd_guardsr   r   r   r   r     s    zGuardsContext.__init__c                 C  s   t t| jjS r6   )r   r   r   r   r   r   r   r   r     s    zGuardsContext.copy_graphstatec                 C  s   t |tstt|j| _d S r6   )rX   r   r   r   r   r   r   r   r   r     s    z GuardsContext.restore_graphstateNr   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 )CompileContextr4   c                   C  s   t jd k	stt jS r6   )_TLScompile_contextr   r   r   r   r   get3  s    zCompileContext.getOptional[CompileContext]c                   C  s   t tdd S Nr   getattrr   r   r   r   r   try_get8  s    zCompileContext.try_getc                 C  s&   |d kst |tst|| _d| _d S )Nr   )rX   r   r   r#   r$   )r   r#   r   r   r   r   <  s    zCompileContext.__init__c                  C  s   t  } | d krd S | jS r6   )r   r   r#   r   r   r   r   current_compile_idA  s    z!CompileContext.current_compile_idc                  C  s0   t  } | d krd S | jd kr"d S t| j| jS r6   )r   r   r#   r"   r$   r   r   r   r   current_trace_idH  s    
zCompileContext.current_trace_idN)	r   r   r    r   r   r   r   r   r   r   r   r   r   r   2  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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.
    Optional[TracingContext]r4   c                   C  s   t tdd S )Ntracing_contextr   r   r   r   r   r   Z  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   ^  s
    zTracingContext.getc                 C  sZ   t  | _t | _t | _|| _g | _d | _d | _	d | _
d | _d | _d| _t | _d| _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_flatoutput_stridesZ#force_unspec_int_unbacked_size_liker   Ztensor_to_contextZfakify_first_call)r   r   r   r   r   r   f  s    
zTracingContext.__init__c                 C  s   i | j _d S r6   )r   r   r   r   r   r   clear  s    zTracingContext.clearc                  k  sv   i }t  }|  D ]}t||||< q|  D ]\}}t||| q0z
d V  W 5 | D ]\}}t||| qZX d S r6   )r   r   r   r   itemssetattr)kwargsZpriorr   keyvalr   r   r   patch  s    
zTracingContext.patchc                  C  s@   t  } | d krt S | j}| jd k	r4|| jg }tj|S r6   )r   r   	tracebackStackSummaryr   r   	from_list)r   rF   r   r   r   r     s    
zTracingContext.extract_stackc                  c  s   t  } tjj| dg d tjj| dd F z
d V  W n4 tk
rn } zt|ds\d |_ W 5 d }~X Y nX W 5 Q R X W 5 Q R X d S )Nr   r   
real_stack)	r   r   unittestZmockr   objectrw   hasattrr   )tcer   r   r   clear_frame  s      

zTracingContext.clear_framec              
   c  s   t  }| d k	r|j|  |j}d |_zHz
d V  W n8 tk
rl } zt|dsZ| |_	 W 5 d }~X Y nX W 5 | d k	r|j  ||_X d S )Nr   )
r   r   r   r   r   poprw   r   r   r   )frame_summaryr   oldr   r   r   r   current_frame  s    



zTracingContext.current_framec                  c  s@   t  } | d krd V  d S | j}g | _z| jV  W 5 || _X d S r6   )r   r   r   )r   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   r   )filenamelinenoZ
frame_namer   r   r   set_current_loc  s       zTracingContext.set_current_locN)r   r   r    r   r   r   r   r   r   r   r   r   
contextlibr   r   r   r   r   r   r   r   r   R  s.   *
r   r   )contextc                 c  s*   t tdd }| t_z
| V  W 5 |t_X d S r   )r   r   r   )r   old_contextr   r   r   r     s
    
r   r   c              
   c  s   t tdd}| t_zPz
| V  W n@ tk
r^ } z"t|dsL| dk	rL|  |_	 W 5 d}~X Y nX W 5 | dk	r| jdk	r| jjdk	r| jj  |t_X 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   Z	shape_envcleanuprw   r   r   r   )r   r   r   r   r   r   tracing  s     	


r   T)frozenc                   @  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 )rH   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 r6   NotImplementedError)r   Zcodegenr   r   r   reconstruct*  s    zSource.reconstructr'   r4   c                 C  s   t d S r6   r   r   r   r   r   re   -  s    zSource.guard_sourcer&   c                 C  s   t d S r6   r   r   r   r   r   rR   0  s    zSource.namerG   c                 C  s   |   tjkrtt| |S r6   )re   r'   r@   r   rG   )r   fnr   r   r   
make_guard3  s    zSource.make_guardr3   c                 C  s   |    S r6   )re   r<   r   r   r   r   r<   8  s    zSource.is_nn_modulec                 C  s   |   tjkS )z+True if you can guard on attributes of this)re   r'   rA   r   r   r   r   subguards_allowed;  s    zSource.subguards_allowedN)r   r   r    r   r   r   re   rR   r   r<   r  r   r   r   r   rH   "  s   rH   c                   @  s&   e Zd ZU ded< dd Zdd ZdS )ChainedSourcerH   basec                 C  s
   | j  S r6   )r  r   r   r   r   r   r   E  s    zChainedSource.is_dict_keyc                 C  s
   | j  S r6   )r  r   r   r   r   r   r   I  s    zChainedSource.is_ephemeralN)r   r   r    r!   r   r   r   r   r   r   r  A  s   
r  r   )inputsc                 C  sH  ddl m}m} g }t  }r>|j}|dk	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\}}}||kst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 rn   z doesn't match mode (z

fake mode from z allocated at:
z
fake mode from )torch._subclasses.fake_tensorr  r  r   r   r   r   torch.utils._python_dispatchr  	enumeratereversedrX   pytreeZtree_leavesr   rF   )r  r  r  Z
fake_modesr   r   r  imZflat_inputsZ
flat_inputZdesc1i1Zdesc2i2r   r   r   detect_fake_modeM  s,    



N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  rX   )r  r  r%   r  r   r   r   active_fake_modey  s    

r  )N)D
__future__r   r   dataclassesenumrY   logging	threadingr   Zunittest.mockr   rg   abcr   r   typingr   r   r   r   r	   r
   r   r   r   r   r   Ztorch.utilsr   r  Ztorch.utils._tracebackr   Ztorch.utils.weakr   	getLoggerr   rx   ZsympyZtorchr   r"   Enumr'   rB   rD   	dataclassrG   r   r   r   r   r   r   r   r   r   r   r   localr   r   r   r   r   rH   r  r  r  r   r   r   r   <module>   sl   4
1 *


+(  *	

,