
    Pg                       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mZ d dlmZ d dlm Z m!Z! d dl"m#Z#  ejH                  e%      Z&erd dl'Z'd dl(Z(	  G d	 d
e      Z) G d de      Z* G d dejV                        Z,	  G d d      Z- ej\                  d       G d d             Z/ G d de      Z0ej\                   G d d             Z1 ed      Z2	 ej\                   G d d             Z3	 ej\                   G d de3             Z4	 ej\                   G d de3             Z5	  G d  d!ee2         Z6 G d" d#      Z7 G d$ d%      Z8 G d& d'e6e8         Z9 G d( d)      Z: G d* d+e6e:         Z;	  G d, d-      Z< G d. d/e6e7         Z= G d0 d1      Z> G d2 d3e>      Z? G d4 d5      Z@ ej                         ZB	  G d6 d7      ZC G d8 d9      ZDedBd:       ZEedCd;       ZF ej\                  d       G d< d=             ZG ej\                  d       G d> d?eG             ZHdDdEd@ZIdA ZJy)F    )annotationsN)abstractmethod)contextmanager)AnyCallableDictGenericList
NamedTupleOptionalSetTupleTYPE_CHECKINGTypeVarUnion)_pytree)CapturedTracebackformat_frame)WeakTensorKeyDictionaryc                  (    e Zd ZU ded<   ded<   d Zy)	CompileIdintframe_idframe_compile_idc                8    | j                    d| j                   S )N/)r   r   selfs    T/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/_guards.py__str__zCompileId.__str__@   s    --$"7"7!899    N__name__
__module____qualname____annotations__r     r!   r   r   r   7   s    M
 :r!   r   c                  (    e Zd ZU ded<   ded<   d Zy)TraceIdr   
compile_idr   attemptc                    | j                   dk(  rt        | j                        S | j                   d| j                    S )Nr   _)r+   strr*   r   s    r   r    zTraceId.__str__J   s7    <<1t''oo&a~66r!   Nr"   r'   r!   r   r)   r)   D   s     L7r!   r)   c                  r    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ZddZddZddZd Zy)GuardSourcer                           	   
                  c                F    | t         j                  t         j                  fv S N)r0   GLOBAL_FSDP_MODULELOCAL_FSDP_MODULEr   s    r   is_fsdp_modulezGuardSource.is_fsdp_modulec   s    668U8UVVVr!   c                F    | t         j                  t         j                  fv S rA   )r0   GLOBAL_SPECIALIZED_NN_MODULELOCAL_SPECIALIZED_NN_MODULEr   s    r   is_specialized_nn_modulez$GuardSource.is_specialized_nn_modulef   s&    4433
 
 	
r!   c                    | t         j                  t         j                  t         j                  t         j                  fv S rA   )r0   GLOBAL_UNSPECIALIZED_NN_MODULELOCAL_UNSPECIALIZED_NN_MODULE&GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE%LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULEr   s    r   is_unspecialized_nn_modulez&GuardSource.is_unspecialized_nn_modulel   s8    6655>>==	
 
 	
r!   c                F    | t         j                  t         j                  fv S rA   )r0   rL   rM   r   s    r   "is_unspecialized_builtin_nn_modulez.GuardSource.is_unspecialized_builtin_nn_modulet   s&    >>==
 
 	
r!   c                    | t         j                  t         j                  t         j                  t         j                  t         j
                  fv S rA   )r0   LOCALrG   rC   rK   rM   r   s    r   is_localzGuardSource.is_localz   sA    33))55==
 
 	
r!   Nreturnbool)r#   r$   r%   rR   GLOBALrG   rF   CONSTANTRANDOM_VALUE	SHAPE_ENVrC   rB   BACKWARD_STATE	EPHEMERALSYNTHETIC_LOCALrK   rJ   rM   rL   rD   rH   rN   rP   rS   r'   r!   r   r0   r0   Q   st    EF"##$ HLINIO$&!%'",.)-/*W



r!   r0   c                      e Zd Zy)GuardBuilderBaseNr#   r$   r%   r'   r!   r   r_   r_      s    r!   r_   T)frozenc                  (    e Zd ZU ded<   ded<   d Zy)SLocz,Optional[Union[traceback.FrameSummary, str]]framework_locOptional[str]maybe_user_locc                    t        | j                  t              r| j                  nt        | j                        }| j                  | j                   d| dS d| dS )Nz ()()
isinstancerd   r.   r   rf   )r   flocs     r   r    zSLoc.__str__   sh     $,,c2 d001 	
 *))*"TF!44tfA;r!   Nr"   r'   r!   r   rc   rc      s    ??!!	r!   rc   c                  "    e Zd ZU ded<   ded<   y)
ShapeGuardzsympy.logic.boolalg.Booleanexprrc   slocNr#   r$   r%   r&   r'   r!   r   rm   rm      s    
%%
Jr!   rm   c                      e Zd ZU ded<   ded<   dZded<   dZded<   dZd	ed
<   dZded<   dZded<   dZ	ded<   dZ
ded<   d Zd Zd Zd Zed!d       Zed"d       Zed        Zd Zd Zd#dZd Zd Zd Zd  Zy)$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_stackzOptional[int]_hashc                    | j                   :t        | j                  | j                  t	        | j
                        f      | _         | j                   S rA   )r|   hashnamesourceidru   r   s    r   __hash__zGuard.__hash__   s:    ::tyy$++r$..7IJKDJzzr!   c                n   ddl m} t        | j                  t        j
                        xr" | j                  j                  |j                  u }|| j                  r| j                  j                  ndt        | j                        | j                  | j                         j                  j                  fS )Nr   )GuardBuilder)torch._dynamo.guardsr   rj   ru   	functoolspartialfuncDUPLICATE_INPUTr   valuelenr   inner_create_fn__code__co_firstlineno)r   r   is_duplicate_inputs      r   sort_keyzGuard.sort_key   s     	6 t~~y'8'89 D##|'C'CC 	
 !%DKK"		NII  "++::
 	
r!   c                D    | j                         |j                         k  S rA   )r   r   others     r   __lt__zGuard.__lt__   s    }}!111r!   c                    t        | j                  t        j                        r| j                  j                  S | j                  S rA   )rj   ru   r   r   r   r   s    r   r   zGuard.inner_create_fn   s0    dnni&7&78>>&&&>>!r!   c                6    | j                   j                         S rA   )rt   r   r   s    r   r   z
Guard.name   s    &&++--r!   c                6    | j                   j                         S rA   )rt   guard_sourcer   s    r   r   zGuard.source   s    &&3355r!   c           
        t        | t        j                        re |        }|Dd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__'
        z<weakref at z; to 'z' at >z; dead>)rj   weakrefReferenceTypehexr   	__class__r#   r.   )rx   objs     r   weakref_to_strzGuard.weakref_to_str   s      k7#8#89-C%c"[/&:%;6#--BXBXAYY^_bceficj_k^llmnn%c"[/&:%;7CC{##r!   c                Z   d| j                   r$| j                   j                  j                         nd dt        | j                         d| j	                         j
                   d| j                   d| j                   d| j                  | j                         d| j                   d}|S )	Nz	
          z&
        {
            'guard_types': z,
            'code': z,
            'obj_weakref': z
            'guarded_class': z
        }
        )r   r   lowerreprr   r#   rv   rw   r   rx   ry   )r   ss     r   __repr__zGuard.__repr__  s    	%)[[					!b94		?:K1TMaMaMcMlMlLm n ,,- .^^$ % //0@0@AB C"889 :	 r!   c                   dt        | j                         d}| j                  r$| j                  j                  j                         nd}|d| dz  }|d| j	                         j
                   dz  }|d| j                   dz  }|d| j                   dz  }|d| j                  | j                         dz  }|d	| j                   dz  }|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   r#   rv   rw   r   rx   ry   )r   outputr   s      r   r    zGuard.__str__  s    $tyy/*"--1[[!!'')bL++)$*>*>*@*I*I)J"MM%d&6&6%7r::ODNN#3266()<)<T=M=M)N(OrRR/0J0J/K2NNr!   c           	     R   	 | j                  ||       S # t        $ r t        j                  dt	        |       j                                | j                  rNt        j                  ddj                  | j                  j                         dd        j                                 w xY w)NzError while creating guard:
%szCreated at:
%sr   )
ru   	Exceptionlog	exceptionr.   rstriprz   errorjoinformat)r   builders     r   createzGuard.create#  s    	>>'400 	MM;SY=M=M=OPzz		+RWWTZZ5F5F5H5M-N-U-U-WX		s
    BB&c                6    | j                   j                         S rA   )r   rH   r   s    r   rH   zGuard.is_specialized_nn_module,  s    {{3355r!   c                6    | j                   j                         S rA   )r   rD   r   s    r   rD   zGuard.is_fsdp_module/  s    {{))++r!   c                6    | j                   j                         S rA   )r   rS   r   s    r   rS   zGuard.is_local2  s    {{##%%r!   c                   | j                   sg | _         | j                   j                  |       | j                  |d fv sJ d       || _        | j                  s|| _        n| j                  j	                  |       | j
                  |d fv s,t        | j
                        r| j                         J d       || _        y )Nz+Guarded class id must be identical, or NonezBGuarded object must be identical, None or ephemeral (dead weakref))rv   appendry   rw   extendrx   callable)r   
guard_typeguarded_classrw   rx   s        r   set_export_infozGuard.set_export_info5  s    !D
+)).
 
 	9 9	9 
 &3"~~&DNNN!!), d 33(()  "*	P P		P+ 'r!   rU   r.   rU   r0   )r   r_   )r#   r$   r%   r&   rv   rw   rx   ry   rz   r{   r|   r   r   r   r   propertyr   r   staticmethodr   r   r    r   rH   rD   rS   r   r'   r!   r   rr   rr      s    & 88 (,K$+%)I")$(K!(,0>0)-E&-37J07E=

"2" . . 6 6 $ $0
	6,&'r!   rr   Tc                      e Zd Zy)GuardEnvExprNr`   r'   r!   r   r   r   \  s    r!   r   c                  (    e Zd ZU ded<   ded<   d Zy)DuplicateInputsrs   input_source_ainput_source_bc                :    | j                   | j                  k7  sJ y rA   )r   r   r   s    r   __post_init__zDuplicateInputs.__post_init__l  s    ""d&9&9999r!   N)r#   r$   r%   r&   r   r'   r!   r   r   r   g  s    :r!   r   c                  "    e Zd ZU ded<   ded<   y)StorageOverlapzList[Source]overlapping_sourcesnon_overlapping_sourcesNrp   r'   r!   r   r   r   ~  s    %%))r!   r   c                  0    e Zd Zedd       Zedd       Zy)Checkpointablec                     y rA   r'   r   s    r   copy_graphstatezCheckpointable.copy_graphstate  s    $'r!   c                     y rA   r'   r   states     r   restore_graphstatez!Checkpointable.restore_graphstate  s    ,/r!   N)rU   r   )r   r   )r#   r$   r%   r   r   r   r'   r!   r   r   r     s    ' '/ /r!   r   c                  <    e Zd ZU dZ e       Zded<   d Zd Zd Z	y)GuardsCheckpointStatezW
    The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
    
Set[Guard]dynamo_guardsc                    || _         y rA   )r   )r   r   s     r   __init__zGuardsCheckpointState.__init__  s
    *r!   c                n    | j                   j                  |j                         }t        |      dk(  ry|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   rs      r   diffzGuardsCheckpointState.diff  s3     ))%*=*=>q6Q;r!   c                (    | j                  |      d u S rA   r   r   s     r   __eq__zGuardsCheckpointState.__eq__      yy4''r!   N)
r#   r$   r%   __doc__setr   r&   r   r   r   r'   r!   r   r   r     s$     !$M:%+
(r!   r   c                  .    e Zd ZU i Zded<   d Zd Zd Zy)ModuleContextCheckpointStatezDict[str, torch.nn.Module]
nn_modulesc                    || _         y rA   r   )r   r   s     r   r   z%ModuleContextCheckpointState.__init__  s	    $r!   c                    t        | j                  j                               j                  t        |j                  j                                     }t	        |      dk(  ry|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   s      r   r   z!ModuleContextCheckpointState.diff  sM     $$&'223u7G7G7L7L7N3OPq6Q;r!   c                (    | j                  |      d u S rA   r   r   s     r   r   z#ModuleContextCheckpointState.__eq__  r   r!   N)r#   r$   r%   r   r&   r   r   r   r'   r!   r   r   r     s    -/J*/%
(r!   r   c                       e Zd ZddZd Zd Zy)ModuleContextc                    i | _         y rA   r   r   s    r   r   zModuleContext.__init__  s	    *,r!   c                >    t        t        | j                              S rA   )r   dictr   r   s    r   r   zModuleContext.copy_graphstate  s    +D,ABBr!   c                J    t        |t              sJ |j                  | _        y rA   )rj   r   r   r   s     r   r   z ModuleContext.restore_graphstate  s     %!=>>>**r!   NrU   Noner#   r$   r%   r   r   r   r'   r!   r   r   r     s    -C+r!   r   c                  .    e Zd ZU i Zded<   d Zd Zd Zy)GlobalContextCheckpointStatezDict[str, Tuple[Callable, ...]]global_statec                    || _         y rA   r   )r   global_statess     r   r   z%GlobalContextCheckpointState.__init__  s
    )r!   c                    t        | j                  j                               j                  t        |j                  j                                     }t	        |      dk(  ry|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   s      r   r   z!GlobalContextCheckpointState.diff  sO     !!&&()44S9K9K9P9P9R5STq6Q;r!   c                (    | j                  |      d u S rA   r   r   s     r   r   z#GlobalContextCheckpointState.__eq__  r   r!   N)r#   r$   r%   r   r&   r   r   r   r'   r!   r   r   r     s    46L16*
(r!   r   c                  ,    e Zd ZdZh dZddZd Zd Zy)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                    i | _         y rA   r   r   s    r   r   zGlobalContext.__init__  s
    =?r!   c                >    t        t        | j                              S rA   )r   r   r   r   s    r   r   zGlobalContext.copy_graphstate  s    +D1B1B,CDDr!   c                b   t        |t              sJ |j                  | _        t        | j                        t        | j                        k(  r0t        | j                  j                               | j                  k(  sJ d       | j                  j                         D ]  \  }} ||        y )NzGlobal state mismatch)rj   r   r   r   _supported_global_statesr   r   values)r   r   r   argss       r   r   z GlobalContext.restore_graphstate  s    %!=>>>!..!!"c$*G*G&HHD%%**,-1N1NN	# #	#O ++224 	JD$J	r!   Nr   )r#   r$   r%   r   r  r   r   r   r'   r!   r   r  r    s     
 @Er!   r  c                  J    e Zd ZddZd Zd Zd Zd Zddd	dd
ZddZ	d Z
y)	GuardsSetNc                *    |
t               }|| _        y rA   )r   inner)r   r  s     r   r   zGuardsSet.__init__  s    =EE
r!   c                ,    t        | j                        S rA   )iterr  r   s    r   __iter__zGuardsSet.__iter__      DJJr!   c                ,    t        | j                        S rA   )r   r  r   s    r   __len__zGuardsSet.__len__  s    4::r!   c                F    t        | j                  |j                  z
        S rA   )r  r  r   s     r   __sub__zGuardsSet.__sub__$  s    ekk122r!   c                ,    t        | j                        S rA   )rV   r  r   s    r   __bool__zGuardsSet.__bool__'  r  r!   Tr   )collect_debug_stackskipc                   || j                   v ry |rO|j                  t        j                  d|z         |_        |j                  t
        j                         |_        | j                   j                  |       y Nr1   )r"  )r  rz   r   extractr{   TracingContextextract_stackadd)r   guardr!  r"  s       r   r(  zGuardsSet.add*  sa    DJJ{{"/77QXF'#1#?#?#A 

ur!   c                F    |D ]  }|D ]  }| j                  |d         y r$  )r(  )r   othersogs       r   updatezGuardsSet.update4  s0     	$A $#$	$r!   c                l    | j                   D ch c]  }|j                  |k7  s| c}| _         yc c}w )z%Delete all guards with a given sourceN)r  rt   )r   r   r-  s      r   remove_guards_with_sourcez#GuardsSet.remove_guards_with_source9  s(    !%NAq/C/Cv/MaN
Ns   11rA   )r)  rr   )r+  r   )r#   r$   r%   r   r  r  r  r   r(  r.  r0  r'   r!   r   r  r    s2    
 
3  8<! $
Or!   r  c                       e Zd ZddZd Zd Zy)GuardsContextc                0    t               | _        g | _        y rA   )r  r   aotautograd_guardsr   s    r   r   zGuardsContext.__init__?  s    (168r!   c                R    t        t        | j                  j                              S rA   )r   r   r   r  r   s    r   r   zGuardsContext.copy_graphstateC  s    $S););)A)A%BCCr!   c                \    t        |t              sJ t        |j                        | _        y rA   )rj   r   r  r   r   s     r   r   z GuardsContext.restore_graphstateF  s&    %!6777&u':':;r!   Nr   r   r'   r!   r   r2  r2  >  s    9D<r!   r2  c                  x    e Zd Zedd       Zed	d       Zed
d       Zedd       Zed
d       Zedd       Z	y)HopSubgraphCachec                     y rA   r'   r   	cache_key
identifiers      r   add_dynamo_identifierz&HopSubgraphCache.add_dynamo_identifierM      FIr!   c                     y rA   r'   r   r;  s     r   get_dynamo_identifierz&HopSubgraphCache.get_dynamo_identifierP  r>  r!   c                     y rA   r'   r   r<  keys      r   add_autograd_key_entryz'HopSubgraphCache.add_autograd_key_entryS  r>  r!   c                     y rA   r'   r   r<  s     r   get_autograd_key_entryz'HopSubgraphCache.get_autograd_key_entryV  s    7:r!   c                     y rA   r'   rC  s      r   add_proxy_dispatch_entryz)HopSubgraphCache.add_proxy_dispatch_entryY  s    HKr!   c                     y rA   r'   rG  s     r   get_proxy_dispatch_entryz)HopSubgraphCache.get_proxy_dispatch_entry\  s    9<r!   Nr;  r.   r<  r.   r;  r.   rU   re   r<  r.   rD  r   r<  r.   )
r#   r$   r%   r   r=  rA  rE  rH  rJ  rL  r'   r!   r   r8  r8  L  sV    I II II I: :K K< <r!   r8  c                  D    e Zd Zd	dZd
dZddZddZddZddZddZ	y)InvokeSubgraphCachec                .    i | _         i | _        i | _        y rA   )autograd_cacheproxy_dispatch_cachedynamo_identifiersr   s    r   r   zInvokeSubgraphCache.__init__a  s    359;!24r!   c                "    || j                   |<   y rA   )rV  r:  s      r   r=  z)InvokeSubgraphCache.add_dynamo_identifierf  s    -7	*r!   c                :    | j                   j                  |d       S rA   )rV  getr@  s     r   rA  z)InvokeSubgraphCache.get_dynamo_identifieri  s    &&**9d;;r!   c                "    || j                   |<   y rA   )rT  rC  s      r   rE  z*InvokeSubgraphCache.add_autograd_key_entryl  s    *-J'r!   c                :    | j                   j                  |d       S rA   )rT  rY  rG  s     r   rH  z*InvokeSubgraphCache.get_autograd_key_entryo  s    ""&&z488r!   c                "    || j                   |<   y rA   )rU  rC  s      r   rJ  z,InvokeSubgraphCache.add_proxy_dispatch_entryr  s    03!!*-r!   c                :    | j                   j                  |d       S rA   )rU  rY  rG  s     r   rL  z,InvokeSubgraphCache.get_proxy_dispatch_entryu  s    ((,,Z>>r!   Nr   rM  rN  rO  rP  )
r#   r$   r%   r   r=  rA  rE  rH  rJ  rL  r'   r!   r   rR  rR  `  s%    5
8<.94?r!   rR  c                  $    e Zd ZddZ	 	 	 	 ddZy)HopDispatchSetCachec                2    ddl m} |t               i| _        y )Nr   )invoke_subgraph)'torch._higher_order_ops.invoke_subgraphra  rR  hop_cache_map)r   ra  s     r   r   zHopDispatchSetCache.__init__z  s    K-/B/DEr!   c                >    || j                   vry | j                   |   S rA   )rc  )r   ops     r   	get_cachezHopDispatchSetCache.get_cache  s&     T'''!!"%%r!   Nr   )re  ztorch._ops.HigherOrderOperatorrU   zOptional[HopSubgraphCache])r#   r$   r%   r   rf  r'   r!   r   r_  r_  y  s    F&0&	#&r!   r_  c                  V    e Zd Zedd       Zedd       Zd Zed        Zed        Zy)	CompileContextc                 F    t         j                  J t         j                  S rA   )_TLScompile_contextr'   r!   r   rY  zCompileContext.get  s     ##///###r!   c                 $    t        t        dd       S Nrk  getattrrj  r'   r!   r   try_getzCompileContext.try_get      t.55r!   c                V    |t        |t              sJ || _        d| _        g | _        y )Nr   )rj   r   r*   r+   shape_env_guards)r   r*   s     r   r   zCompileContext.__init__  s-    !Z
I%FFF/9+-r!   c                 H    t         j                         } | y | j                  S rA   )rh  rp  r*   r   s    r   current_compile_idz!CompileContext.current_compile_id  s"    %%'<r!   c                     t         j                         } | y | j                  y t        | j                  | j                        S rA   )rh  rp  r*   r)   r+   r   s    r   current_trace_idzCompileContext.current_trace_id  s:    %%'<??"t55r!   N)rU   rh  )rU   Optional[CompileContext])	r#   r$   r%   r   rY  rp  r   ru  rw  r'   r!   r   rh  rh    sU    $ $ 6 6.   6 6r!   rh  c                     e Zd ZdZedd       Zedd       Zd Zd Zee	d               Z
ed        Zeej                  d               Zeej                  d	               Zeej                  d
               Zed        Zy)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.
    c                 $    t        t        dd       S )Ntracing_contextrn  r'   r!   r   rp  zTracingContext.try_get  rq  r!   c                 H    t         j                         x} r| S t        d      )Nz<TracingContext.get() must be called within an ongoing trace.)r&  rp  RuntimeError)ctxs    r   rY  zTracingContext.get  s+     ((**3*JJ
 	
r!   c                4   t               | _        t               | _        t	               | _        || _        g | _        d | _        d | _	        d | _
        d | _        d | _        d | _        d | _        d| _        t!               | _        d| _        t'               | _        y NF)r2  guards_contextr   module_contextr  global_context	fake_modeframe_summary_stackloc_in_framefw_metadataaot_graph_nameparams_flatparams_flat_unwrap_subclassesparams_unwrapped_to_flat_indexoutput_strides#force_unspec_int_unbacked_size_liker   tensor_to_contextfakify_first_callr_  hop_dispatch_set_cache)r   r  s     r   r   zTracingContext.__init__  s    +o+o+o"#%  !"-1*.2+ JN 490!8!:
 "'&9&;#r!   c                &    i | j                   _        y rA   )r  r   r   s    r   clearzTracingContext.clear   s     ,.(r!   c               +  r  K   i }t         j                         }| j                         D ]  }t        ||      ||<    | j	                         D ]  \  }}t        |||        	 d  |j	                         D ]  \  }}t        |||        y # |j	                         D ]  \  }}t        |||        w xY wwrA   )r&  rY  r   ro  itemssetattr)kwargspriorr~  rD  vals        r   patchzTracingContext.patch  s        ";;= 	+C c*E#J	+  	#HCCc"	#	'!KKM 'SS#&'EKKM 'SS#&'s   A B7#B '&B7'B44B7c                     t         j                         } | t        j                         S | j                  }| j
                  || j
                  gz   }t        j                  j                  |      S rA   )r&  rp  	tracebackStackSummaryr  r  	from_list)r   rz   s     r   r'  zTracingContext.extract_stack  se    %%'<))++(((T..//E%%//66r!   c               #    K   t         j                         } t        j                  j                  j                  | dg       5  t        j                  j                  j                  | dd       5  	 d  	 d d d        d d d        y # t        $ r}t        |d      sd |_         d }~ww xY w# 1 sw Y   7xY w# 1 sw Y   y xY ww)Nr  r  
real_stack)	r&  rY  unittestmockr  objectr   hasattrr  )tces     r   clear_framezTracingContext.clear_frame"  s      !]]  ''%r
 	==%%b.$?			 	 	
  $ q,/#'AL)	 	 	 	sT   A C,B7.B+0B5B7=	C	B(B##B((B++B4	0B77C <Cc              #    K   t         j                         }| |j                  j                  |        |j                  }d |_        	 d  	 | |j                  j                          ||_        y # t
        $ r'}t        |d      s|j                         |_         d }~ww xY w# | |j                  j                          ||_        w xY ww)Nr  )
r&  rY  r  r   r  r   r  r'  r  pop)frame_summaryr  oldr  s       r   current_framezTracingContext.current_frameA  s     
 !$""))-8oo		" (&&**,!BO  	1l+!//1	
 (&&**,!BOs6   ACA1 $C1	B!:"BB!!B$ $%C		Cc               #     K   t         j                         } | d  y | j                  }g | _        	 | j                   || _        y # || _        w xY wwrA   )r&  rp  r  )r  old_output_stridess     r   report_output_stridesz$TracingContext.report_output_stridesV  sY      ##%:J..	3### 2B 2Bs   /AA  A	AAc                d    t        j                  | ||d      t        j                         _        y )NF)lookup_line)r  FrameSummaryr&  rY  r  )filenamelineno
frame_names      r   set_current_loczTracingContext.set_current_locd  s'    ,5,B,Bfje-
)r!   N)rU   Optional[TracingContext])rU   r&  )r#   r$   r%   r   r   rp  rY  r   r  r   r  r'  
contextlibr  r  r  r  r'   r!   r   r&  r&    s     6 6 
 
+<Z.
 '  ' 7 7   : "  "& 
3  
3 
 
r!   r&  c              #     K   t        t        dd       }| t        _        	 |  |t        _        y # |t        _        w xY wwrm  )ro  rj  rk  )contextold_contexts     r   rk  rk  k  s7     $ 148K"D+*{s   A 0 A =A c              #    K   t        t        dd      }| t        _        	 |  	 | F| j                  :| j                  j                  $| j                  j                  j                          |t        _        y# t        $ r)}t	        |d      s| | j                         |_         d}~ww xY w# | F| j                  :| j                  j                  $| j                  j                  j                          |t        _        w xY w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  )
ro  rj  r{  r   r  r'  r  r  	shape_envcleanup)r  r  r  s      r   tracingr  u  s      $ 148K"D+ !!-!!++7''//1*  q,'G,?"002AL !!-!!++7''//1*s5   DA9 AD9	B+$B&&B++B. .ADDc                  D    e Zd Zd Zd Zd Zd
dZddZddZddZ	d Z
y	)rs   c                     yr  r'   r   s    r   is_dict_keyzSource.is_dict_key      r!   c                     yr  r'   r   s    r   is_ephemeralzSource.is_ephemeral  r  r!   c                    t         rA   NotImplementedError)r   codegens     r   reconstructzSource.reconstruct      !!r!   c                    t         rA   r  r   s    r   r   zSource.guard_source  r  r!   c                    t         rA   r  r   s    r   r   zSource.name  r  r!   c                f    | j                         t        j                  u rt        t	        | |      S rA   )r   r0   rX   r  rr   )r   fns     r   
make_guardzSource.make_guard  s+    +"6"66%%T2r!   c                >    | j                         j                         S rA   )r   rH   r   s    r   rH   zSource.is_specialized_nn_module  s      ";;==r!   c                D    | j                         t        j                  k7  S )z+True if you can guard on attributes of this)r   r0   r]   r   s    r   subguards_allowedzSource.subguards_allowed  s      "k&A&AAAr!   Nr   r   )rU   rr   rT   )r#   r$   r%   r  r  r  r   r   r  rH   r  r'   r!   r   rs   rs     s+    """
>Br!   rs   c                  $    e Zd ZU ded<   d Zd Zy)ChainedSourcers   basec                6    | j                   j                         S rA   )r  r  r   s    r   r  zChainedSource.is_dict_key  s    yy$$&&r!   c                6    | j                   j                         S rA   )r  r  r   s    r   r  zChainedSource.is_ephemeral  s    yy%%''r!   N)r#   r$   r%   r&   r  r  r'   r!   r   r  r    s    
L'(r!   r  c                z   ddl m}m} g }t        j	                         x}r"|j
                  }||j                  |ddf       ddlm} t        t         |                   D ]&  \  }}t        ||      s|j                  |d|f       ( t        j                  |       }	t        |	      D ]0  \  }}
t        |
|      s|j                  |
j
                  d|f       2 |r\|d   \  }}}|dd D ]I  \  }}}||u rJ d	| d
| d| d| d
| d| d| d| d|j                   d| d| d|j                           |S y)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 inputr1   zfake mode (z) from r   z doesn't match mode (z

fake mode from z allocated at:
z
fake mode from )torch._subclasses.fake_tensorr  r  r&  rp  r  r   torch.utils._python_dispatchr  	enumeratereversedrj   pytreetree_leavesrz   )inputsr  r  
fake_modesr  r  r  imflat_inputs
flat_inputdesc1i1desc2i2s                  r   detect_fake_moder    s    IJ ((**w*%%	 y*;Q?@M(#C#EFG :1a(q"4a89: $$V,K";/ N:j*-z335H!LMN )!}	5"&qrN 	LAub> i[wat;PQRPSSZ[`Zaabcebf g""'"-=ioo=N O""'"-=aggYH>	 r!   c                 ~    ddl m}  ddlm} t	        t         |                   D ]  \  }}t        ||       s|c S  y)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  rj   )r  r  r-   r  s       r   active_fake_moder    s?    
 =M(#C#EFG 1a(H r!   )r  rx  )r  r  rA   )r  r   )K
__future__r   r  dataclassesenumr   logging	threadingr  unittest.mockr  r   abcr   r   typingr   r   r   r	   r
   r   r   r   r   r   r   r   torch.utilsr   r  torch.utils._tracebackr   r   torch.utils.weakr   	getLoggerr#   r   sympytorchr   r)   Enumr0   r_   	dataclassrc   rm   rr   r   r   r   r   r   r   r   r   r   r  r  r2  r8  rR  r_  localrj  rh  r&  rk  r  rs   r  r  r  r'   r!   r   <module>r     s   "           %    * B 4 g! 
 
:
 
:
7j 
70
$)) 0
f	 	 d#  $  
 b' b' b'J CL 	 	 	 :l : : *\ * *

0WQZ 0( (4( (,	+N#?@ 	+( (,N#?@ B%O %OP<N#89 <= =(?* ?2& & y&6 6Di
 i
X + + + +8 d#B B $B< d#(F ( $()Xr!   