o
    "iKt                     @  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rqd 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Z0	 ej-G dd de0Z1	 G 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 Z7	 G d&d' d'Z8G d(d) d)e2e3 Z9e: Z;	 G d*d+ d+Z<G d,d- d-Z=edAd0d1Z>edBd3d4Z?ej-d5d6G d7d8 d8Z@ej-d5d6G d9d: d:e@ZAdCdDd=d>ZBd?d@ ZCdS )E    )annotationsN)abstractmethod)contextmanager)AnyCallableDictGenericList
NamedTupleOptionalSetTupleTYPE_CHECKINGTypeVar)_pytree)CapturedTraceback)WeakTensorKeyDictionaryc                   @  &   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   K/home/ubuntu/SoloSpeech/.venv/lib/python3.10/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 )Nr   _)r%   strr$   r   r   r   r   r   J   s   

zTraceId.__str__Nr   r   r   r   r   r#   D   s   
 r#   c                   @  sX   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ZdddZdd ZdS )GuardSourcer                           	   
      returnboolc                 C  s   | 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   | t jt jfv 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v S r6   )r(   LOCALr<   r8   r   r   r   r   is_locall   s
   zGuardSource.is_localNr4   r5   )r   r    r!   r>   GLOBALr<   r;   CONSTANTRANDOM_VALUE	SHAPE_ENVr8   r7   BACKWARD_STATE	EPHEMERALSYNTHETIC_LOCALr9   r=   r?   r   r   r   r   r(   Q   s     


r(   c                   @     e Zd ZdS )GuardBuilderBaseNr   r    r!   r   r   r   r   rI      s    rI   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   rK      s   
 rK   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]rM   z Optional[traceback.StackSummary]
user_stackzOptional[int]_hashc                 C  s*   | j d u rt| j| jt| jf| _ | j S r6   )rW   hashnamesourceidrQ   r   r   r   r   __hash__   s   
zGuard.__hash__c                 C  sT   ddl m} t| jtjo| jj|ju }|| jr| jj	ndt
| j| j|  jjfS )Nr)   )GuardBuilder)_dynamo.guardsr]   
isinstancerQ   	functoolspartialfuncDUPLICATE_INPUTrZ   valuelenrY   inner_create_fn__code__co_firstlineno)r   r]   is_duplicate_inputr   r   r   sort_key   s   
zGuard.sort_keyc                 C  s   |   |  k S r6   )rk   r   otherr   r   r   __lt__   r:   zGuard.__lt__c                 C  s   t | jtjr| jjS | jS r6   )r`   rQ   ra   rb   rc   r   r   r   r   rg      s   zGuard.inner_create_fnr4   r'   c                 C  
   | j  S r6   )rP   rY   r   r   r   r   rY         
z
Guard.namer(   c                 C  ro   r6   )rP   guard_sourcer   r   r   r   rZ      rp   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>)r`   weakrefReferenceTypehexr[   	__class__r   r'   )rT   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
        }
        )rZ   rY   lowerreprrg   r   rR   rS   rx   rT   rU   )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: 
ry   z    Source: z    Create Function: z    Guard Types: z    Code List: z    Object Weakref: z    Guarded Class Weakref: )r|   rY   rZ   r{   rg   r   rR   rS   rx   rT   rU   )r   outputrZ   r   r   r   r      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:
%sry   )
rQ   	Exceptionlog	exceptionr'   rstriprM   errorjoinformat)r   r   r   r   r   create  s   $zGuard.createc                 C  ro   r6   )rZ   r=   r   r   r   r   r=        
zGuard.is_nn_modulec                 C  ro   r6   )rZ   r9   r   r   r   r   r9     r   zGuard.is_fsdp_modulec                 C  ro   r6   )rZ   r?   r   r   r   r   r?     r   zGuard.is_localc                 C  s   | j st | _ | j | | j|d fv sJ d|| _| js"|| _n| j| | j|d fv s>t| jr:|  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))rR   listappendrU   rS   extendrT   callable)r   
guard_typeguarded_classrS   rT   r   r   r   set_export_info  s0   
zGuard.set_export_infor4   r'   r4   r(   )r   rI   )r   r    r!   r"   rR   rS   rT   rU   rM   rV   rW   r\   rk   rn   rg   propertyrY   rZ   staticmethodrx   r~   r   r   r=   r9   r?   r   r   r   r   r   rN      s6   
 

	rN   Tc                   @  rH   )GuardEnvExprNrJ   r   r   r   r   r   ?  s    r   c                   @  r   )DuplicateInputsrO   input_source_ainput_source_bc                 C  s   | j | jksJ d S r6   )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                   @  s(   e Zd Zed	ddZed
ddZdS )Checkpointabler4   r   c                 C     d S r6   r   r   r   r   r   copy_graphstatea     zCheckpointable.copy_graphstatestatec                 C  r   r6   r   r   r   r   r   r   restore_graphstatee  r   z!Checkpointable.restore_graphstateN)r4   r   )r   r   )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  
   || _ d S r6   )r   )r   r   r   r   r   __init__q  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   
differencerf   r   rm   rr   r   r   difft  s   zGuardsCheckpointState.diffc                 C     |  |d u S r6   r   rl   r   r   r   __eq__     zGuardsCheckpointState.__eq__N)
r   r    r!   __doc__setr   r"   r   r   r   r   r   r   r   r   j  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   r6   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   rf   r   r   r   r   r        z!ModuleContextCheckpointState.diffc                 C  r   r6   r   rl   r   r   r   r     r   z#ModuleContextCheckpointState.__eq__N)r   r    r!   r   r"   r   r   r   r   r   r   r   r     
   
 r   c                   @  $   e Zd Zdd Zdd Zdd ZdS )ModuleContextc                 C  
   i | _ d S r6   r   r   r   r   r   r     r   zModuleContext.__init__c                 C     t t| jS r6   )r   dictr   r   r   r   r   r     r   zModuleContext.copy_graphstatec                 C  s   t |tsJ |j| _d S r6   )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                   @  r   )
GlobalContextCheckpointStatezDict[str, Tuple[Callable, ...]]global_statec                 C  r   r6   r   )r   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   rf   r   r   r   r   r     r   z!GlobalContextCheckpointState.diffc                 C  r   r6   r   rl   r   r   r   r     r   z#GlobalContextCheckpointState.__eq__N)r   r    r!   r   r"   r   r   r   r   r   r   r   r     r   r   c                   @  s0   e Zd ZdZh d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.
    >   grad_enabledautocast_enabledautocast_cpu_dtypeautocast_gpu_dtypeautocast_cpu_enabledautocast_cache_enabledtorch_function_enabledc                 C  r   r6   r   r   r   r   r   r     r   zGlobalContext.__init__c                 C  r   r6   )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)r`   r   r   rf   _supported_global_statesr   r   values)r   r   rc   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                   @  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 r6   )r   inner)r   r   r   r   r   r     s   
zGuardsSet.__init__c                 C  
   t | jS r6   )iterr   r   r   r   r   __iter__  r   zGuardsSet.__iter__c                 C  r   r6   )rf   r   r   r   r   r   __len__  r   zGuardsSet.__len__c                 C  s   t | j|j S r6   )r   r   rl   r   r   r   __sub__  r:   zGuardsSet.__sub__c                 C  r   r6   )r5   r   r   r   r   r   __bool__  r   zGuardsSet.__bool__Tr   )collect_debug_stackskipguardrN   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   rM   r   extractrV   TracingContextextract_stackadd)r   r   r   r   r   r   r   r     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   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   )rP   ).0r   rZ   r   r   	<setcomp>  s    z6GuardsSet.remove_guards_with_source.<locals>.<setcomp>N)r   )r   rZ   r   r   r   remove_guards_with_source
  s   z#GuardsSet.remove_guards_with_sourcer6   )r   rN   )r   r   )r   r    r!   r   r   r   r   r   r   r   r   r   r   r   r   r     s    


r   c                   @  r   )GuardsContextc                 C  s   t  | _g | _d S r6   )r   r   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     r:   zGuardsContext.copy_graphstatec                 C  s   t |tsJ t|j| _d S r6   )r`   r   r   r   r   r   r   r   r     s   z GuardsContext.restore_graphstateNr   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 )CompileContextr4   c                   C  s   t jd usJ t jS r6   )_TLScompile_contextr   r   r   r   get3  s   zCompileContext.getOptional[CompileContext]c                   C     t tdd S Nr   getattrr   r   r   r   r   try_get8     zCompileContext.try_getc                 C  s&   |d u st |tsJ || _d| _d S )Nr   )r`   r   r$   r%   )r   r$   r   r   r   r   <  s   
zCompileContext.__init__c                  C  s   t  } | d u 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 u r
d S | jd u 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)r4   r   )r4   r   )	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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.
    r4   Optional[TracingContext]c                   C  r   )Ntracing_contextr   r   r   r   r   r   Z  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  sZ   t  | _t | _t | _|| _g | _d | _d | _	d | _
d | _d | _d| _t | _d| _d S NF)r   guards_contextr   module_contextr   global_context	fake_modeframe_summary_stackloc_in_framefw_metadataaot_graph_nameparams_flatoutput_strides#force_unspec_int_unbacked_size_liker   tensor_to_context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  s    i }t  }|  D ]	}t||||< q|  D ]
\}}t||| qzd V  W | D ]
\}}t||| q-d S | D ]
\}}t||| q>w r6   )r   r   r   r   itemssetattr)kwargspriorr   keyvalr   r   r   patch  s   zTracingContext.patchc                  C  s@   t  } | d u rt S | j}| jd ur|| jg }tj|S r6   )r   r   	tracebackStackSummaryr   r  	from_list)r   rM   r   r   r   r     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 )Nr   r  
real_stack)	r   r   unittestmockr  objectr   hasattrr  )tcer   r   r   clear_frame  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 )Nr  )
r   r   r   r   r  r   r  r   r  pop)frame_summaryr  oldr  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 r6   )r   r   r  )r  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lineno
frame_namer   r   r   set_current_loc  s   zTracingContext.set_current_locN)r4   r   )r4   r   )r   r    r!   r   r   r   r   r   r	  r   r  r   
contextlibr  r  r!  r'  r   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   )r)  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.
    r   Nr  )
r   r   r   r   r  r   r  r   	shape_envcleanup)r)  r*  r  r   r   r   tracing  s,   	




r-  T)frozenc                   @  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 )rO   c                 C     dS r   r   r   r   r   r   is_dict_key$     zSource.is_dict_keyc                 C  r/  r   r   r   r   r   r   is_ephemeral'  r1  zSource.is_ephemeralc                 C     t r6   NotImplementedError)r   codegenr   r   r   reconstruct*  r1  zSource.reconstructr4   r(   c                 C  r3  r6   r4  r   r   r   r   rq   -  r1  zSource.guard_sourcer'   c                 C  r3  r6   r4  r   r   r   r   rY   0  r1  zSource.namerN   c                 C  s   |   tju r	tt| |S r6   )rq   r(   rB   r5  rN   )r   fnr   r   r   
make_guard3  s   
zSource.make_guardr5   c                 C  s   |    S r6   )rq   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)rq   r(   rG   r   r   r   r   subguards_allowed;  s   zSource.subguards_allowedNr   r   )r4   rN   r@   )r   r    r!   r0  r2  r7  rq   rY   r9  r=   r:  r   r   r   r   rO   "  s    



rO   c                   @  s&   e Zd ZU ded< dd Zdd ZdS )ChainedSourcerO   basec                 C  ro   r6   )r<  r0  r   r   r   r   r0  E  rp   zChainedSource.is_dict_keyc                 C  ro   r6   )r<  r2  r   r   r   r   r2  I  r   zChainedSource.is_ephemeralN)r   r    r!   r"   r0  r2  r   r   r   r   r;  A  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 rz   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_dispatchrA  	enumeratereversedr`   pytreetree_leavesrM   )r=  r>  r?  
fake_modesr)  r   rA  imflat_inputs
flat_inputdesc1i1desc2i2r   r   r   detect_fake_modeM  sH   



&rQ  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)rB  r?  rC  rA  rD  rE  r`   )r?  rA  r&   rJ  r   r   r   active_fake_modey  s   
rR  )r)  r   )r)  r   r6   )r=  r   )D
__future__r   r(  dataclassesenumra   logging	threadingr  unittest.mockr  rs   abcr   r   typingr   r   r   r   r	   r
   r   r   r   r   r   torch.utilsr   rF  torch.utils._tracebackr   torch.utils.weakr   	getLoggerr   r   sympytorchr   r#   Enumr(   rI   rK   	dataclassrN   r   r   r   r   r   r   r   r   r   r   r   localr   r   r   r   r-  rO   r;  rQ  rR  r   r   r   r   <module>   s|   4
# *
!
(  *	

,