
    7hS>                     l   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKJr  SSKJrJrJr  SSKrSSKrSSKJrJr  SSKJr  SSKJr  \R6                  " \5      r\R<                  " S	S
9 " S S5      5       r\R<                   " S S5      5       r \" S\!5      r"\" S\!5      r#\R<                   " S S5      5       r$\R<                   " S S5      5       r%\RL                   " S S\\%   5      5       r' " S S5      r(\RL                   " S S\\   5      5       r) " S S5      r*g)a  
This module provides the infrastructure for creating and managing compile package
for torch.compile. We mainly have two abstractions here:
  - CompilePackage: Overarching data structure for store and lookup a list of compiled codes.
  - CodeCacheEntry: Data structure for a single code being compiled by torch.compile.
The caching behavior is always under user control explicitly so that a stronger guarantee can
be provided about cache hit for a specific compiled model. Users can load the compile package
from a different process or host.
    N)	Generator)AnyNewTypeOptional)PrecompileCacheArtifactPrecompileContext)CacheArtifactFactory   )get_code_keysT)frozenc                      \ rS rSr% \\S'   \\S'   \\S'   \\S'   \\S'   \\S'   \\S'   \\S	4   \S
'   \\	S	4   \S'   \\	S	4   \S'   \	\S'   \	\S'   \\S'   \\	S	4   \S'   \\	S	4   \S'   Sr
\\   \S'   Sr\\	   \S'   Sr\\   \S'   Sr\\	   \S'   \\R"                  S\R&                  SS 4S j5       5       r\\R"                  SS S\R&                  4S j5       5       rSrg)SerializedCode$   co_argcountco_posonlyargcountco_kwonlyargcount
co_nlocalsco_stacksizeco_flagsco_code.	co_constsco_namesco_varnamesco_filenameco_nameco_firstlinenoco_cellvarsco_freevarsNco_linetableco_qualnameco_exceptiontable	co_lnotabcodereturnc                    ^  [        5        Vs0 s H  o"[        X5      _M     nn[        U 4S jUS    5       5      US'   T " S0 UD6$ s  snf )Nc              3      >#    U  H7  n[        U[        R                  5      (       a  TR                  U5      OUv   M9     g 7fN)
isinstancetypesCodeTypefrom_code_object.0cclss     O/var/www/fran/franai/venv/lib/python3.13/site-packages/torch/_dynamo/package.py	<genexpr>2SerializedCode.from_code_object.<locals>.<genexpr>>   s8      $
( (2!U^^'D'DC  #!K(s   ?Ar    )r   getattrtuple)r/   r#   keykwargss   `   r0   r+   SerializedCode.from_code_object:   sY     6C_E_cwt))_E# $
K($
 
{ }V} Fs   Aserialized_codec                    ^  [        5        Vs0 s H  o"[        X5      _M     nn[        U 4S jUS    5       5      US'   [        R                  " UR                  5       6 $ s  snf )Nc              3   t   >#    U  H-  n[        U[        5      (       a  TR                  U5      OUv   M/     g 7fr'   )r(   r   to_code_objectr,   s     r0   r1   0SerializedCode.to_code_object.<locals>.<genexpr>H   s4      $
( &0>%B%BCq!I(s   58r   )r   r4   r5   r)   r*   values)r/   r9   r6   r7   s   `   r0   r<   SerializedCode.to_code_objectD   sh     ANPw44P# $
K($
 
{ ~~]]_
 	
 Qs   A!r3   )__name__
__module____qualname____firstlineno__int__annotations__bytesr5   r   strr   r   r    r!   r"   classmethod	functoolscacher)   r*   r+   r<   __static_attributes__r3       r0   r   r   $   s   OMNS#XCHosCx LsCx sCx $(L(5/(!%K#%)-x-#Ix}#__ENN 7G    __
-= 
%.. 
  
rL   r   c                   .    \ rS rSr% Sr\\S'   \\S'   Srg)_GuardedCodeCacheEntryQ   z
Contains the serializable information associated with a single compilation in dynamo.
To restore an execution of compiled code, we will need to serialize the following data:
  - Dynamo bytecode for mapping Python inputs/outputs.
  - Dynamo guards.
guards_statedynamo_coder3   N)	r@   rA   rB   rC   __doc__rF   rE   r   rK   r3   rL   r0   rN   rN   Q   s     rL   rN   
_BackendId_FunctionIdc                   r    \ rS rSr% Sr\\S'   \\S'   \\	   \S'   \\
   \S'   \\\4   \S'   \\   \S'   S	rg
)_DynamoCodeCacheEntryb   aQ  
Contains the serializable information associated with a single code object
in dynamo. To restore an execution of compiled code, we will need the following
ingredients:
  1. The "original" code object, which serves as the entry point for eager
     execution, i.e. the code only executed when there's no cache entry hit.
  2. The python module name this code object belongs to, for identifying the
     enclosing global scope to inject compiled and resume functions.
  3. A list of function names that pointing to this code object. There could be
     multiple function objects pointing to the same code such as recursive functions.
  4. A list of guarded code that eval frame dispatches to.
  5. A list of imported module objects unioned from all compiled branches.
  6. A list of "backends" (compiled fx graph) unioned from all compield branches.
python_codepython_modulefunction_namesguarded_codesimport_sourcesbackend_idsr3   N)r@   rA   rB   rC   rR   r   rE   rG   listrT   rN   dictrS   rK   r3   rL   r0   rV   rV   b   sE      %%.//cN"j!!rL   rV   c                       \ rS rSr% \\   \S'   \R                  " 5       r\	\S'   \
R                  r\	\S'   \S\\   4S j5       rSrg)	_DynamoCacheEntry{   codespython_versiontorch_versionr$   c                 p    U R                    VVs1 s H  oR                    H  o"iM     M     snn$ s  snnf r'   )rc   r]   )selfr#   
backend_ids      r0   r]   _DynamoCacheEntry.backend_ids   s+    '+zzUztDTDTj
DT
zUUUs   2r3   N)r@   rA   rB   rC   r^   rV   rE   platformrd   rG   torch__version__re   propertysetrS   r]   rK   r3   rL   r0   ra   ra   {   sQ    %&&"113NC3**M3*VS_ V VrL   ra   c                   :    \ rS rSr\S\4S j5       rS\4S jrSr	g)_DynamoCacheArtifact   r$   c                      g)Nprecompile_dynamor3   r3   rL   r0   type_DynamoCacheArtifact.type   s    "rL   c                 B    [         R                  " U R                  5      $ r'   pickleloadscontentrg   s    r0   after_deserialization*_DynamoCacheArtifact.after_deserialization       ||DLL))rL   r3   N)
r@   rA   rB   rC   staticmethodrG   rt   ra   r|   rK   r3   rL   r0   rp   rp      s(    ## # #*'8 *rL   rp   c            	       *   \ rS rSrSrS%S\S\\   SS4S jjrS%S\S\\   SS4S jjr	 S%S	\
R                  S
\S\\   SS4S jjr\S\\\4   4S j5       r\R(                  S\4S j5       r\R.                  S\
R                  S\S   4S j5       rS\S\
R                  SS4S jrS	\
R                  S
\S\\   SS4S jrS\S\SS4S jrS%S\S\\   SS4S jjrS&S jrS\
R@                  S\S\SS4S jr!S&S  jr"S!\\\4   SS4S" jr#S\4S# jr$S$r%g)'CompilePackage   a|  
CompilePackage is considered a low level component and should not be directly exposed to
end users. It has the following interface:

1. `CompilePackage.__init__()` which optionally takes previously serialized dynamo states.
    a. when `dynamo` argument is None, it will construct a brand new CompilePackage object.
    b. when `dynamo` argument is not None, it will load a pre-compiled dynamo state.
2. `package.save()` which dumps the dynamo and backend states to a DynamoCacheEntry object.
3. `package.install(backends) which will handle all the side-effectful global scope
    updates with compiled functions and resume functions.
Nfndynamor$   c                     S U l         0 U l        S U l        0 U l        0 U l        U R                  X5        U R                  5         U R                  5         g r'   )_innermost_fn_codes_current_entry_installed_globals_cached_backends_initialize	uninstallvalidate)rg   r   r   s      r0   __init__CompilePackage.__init__   sL    !CE?CEG 8:$rL   c                    SSK Jn  U" U5      U l        U R                  c   eUb  [        U[        5      (       d   eUR
                  [        R
                  " 5       :w  a  [        SUR
                   35      eUR                  [        R                  :w  a  [        SUR                   35      eUR                  tpEU R                  R                  U0U l        U H.  nX`R                  [        R                  UR                   5      '   M0     g U R#                  U R                  R                  U R                  R$                  5        g )Nr
   )innermost_fnz=Compile package was created with a different Python version: z>Compile package was created with a different PyTorch version: )
eval_framer   r   r(   ra   rd   rj   RuntimeErrorre   rk   rl   rc   __code__r   r   r<   rX   _add_functionrA   )rg   r   r   r   mainrc   r#   s          r0   r   CompilePackage._initialize   s"   ,)"-!!---f&78888$$(?(?(AA"STZTiTiSjk  ##u'8'88"TU[UiUiTjk  "<<LD--66=DKOSN99$:J:JKL  ""++T-?-?-J-JrL   rX   rY   namec           	         XR                   ;  a0  [        [        R                  U5      U/ / 0 / S9nX@R                   U'   O!U R                   U   nUR                  U:X  d   eUb  UR
                  R                  U5        g g )N)rX   rY   rZ   r[   r\   r]   )r   rV   r   r+   rY   rZ   append)rg   rX   rY   r   r#   s        r0   r   CompilePackage._add_function   s     kk)(*;;KH+! !D (,KK$;;{+D%%666&&t, rL   c                     U R                   $ r'   )r   r{   s    r0   cached_backendsCompilePackage.cached_backends   s    $$$rL   c                 \   U R                   c   e[        R                  " 5       nUR                  U R                   R                  R                  5       5        UR                  [        U R                   R                  R                  5      R                  5       5        UR                  5       $ r'   )
r   hashlibsha256updaterB   encoderG   r   r   	hexdigest)rg   sha256_hashs     r0   	source_idCompilePackage.source_id   s    !!---nn&4--::AACD3t11::IIJQQST$$&&rL   r#   )NNNc              #      #    U R                   b   eU R                  U   nX l          S v   S U l         g ! S U l         f = f7fr'   )r   r   )rg   r#   entrys      r0   code_contextCompilePackage.code_context   sC     ""***D!#	'"&D$Ds   %A 4 A 	=A rP   rQ   c                     U R                   c   e[        U[        R                  U5      S9nU R                   R                  R                  U5        g )N)rP   rQ   )r   rN   r   r+   r[   r   )rg   rP   rQ   guarded_code_entrys       r0   add_guarded_codeCompilePackage.add_guarded_code   sO    
 ""...3%&77D
 	))001CDrL   c                 V    U R                  XU(       a  [        U5      5        g S 5        g r'   )r   rT   )rg   rX   rY   r   s       r0   add_resume_function"CompilePackage.add_resume_function   s&     	TD(9	
GK	
rL   aliasmodule_namec                 R    U R                   c   eX R                   R                  U'   g r'   )r   r\   )rg   r   r   s      r0   add_import_source CompilePackage.add_import_source  s(    ""...4?**51rL   rh   backendc                     U R                   c   eUR                  S5      (       d   e[        U5      nU R                   R                  R	                  U5        Ub  X R
                  U'   g g )N__compiled_fn_)r   
startswithrS   r]   r   r   )rg   rh   r   s      r0   add_backend_idCompilePackage.add_backend_id  si    ""...$$%56666
+
''..z:07!!*- rL   c                     U R                   b   eU R                  c   e[        [        U R                  5      5      U R                  R
                  L d   eg r'   )r   r   nextiterr   r   r{   s    r0   r   CompilePackage.validate  sN    ""***!!---D%&$*<*<*E*EEEErL   modulevaluec                 v    X1R                   U'   U R                  R                  U/ 5      R                  U5        g r'   )__dict__r   
setdefaultr   )rg   r   r   r   s       r0   _install_globalCompilePackage._install_global  s/     %**626==dCrL   c                    SSK Jn  U R                  c   eU R                  R	                  5        H)  u  p#U H  nUR
                  R                  U5        M      M+     0 U l        U" U R                  R                  5        g )Nr   )_reset_precompile_entries)torch._C._dynamo.eval_framer   r   r   itemsr   popr   )rg   r   r   namesr   s        r0   r   CompilePackage.uninstall  sl    I!!---!44::<MF##D)  = #%!$"4"4"="=>rL   backendsc           	      |   SSK Jn  U R                  5         U R                  R	                  5        GH  u  p4[
        R                  UR                     nUR                  R	                  5        H+  u  pgU R                  XV[        R                  " U5      5        M-     UR                   H6  n[        R                  " X5R                  U5      n	U R                  XXU	5        M8     UR                    HK  n
X;  a  [#        SU
 S35      eX   nU R                  UU
[$        R&                  R)                  U5      5        MM     GM     U R                  R	                  5        H  u  p4UR*                   H  n[,        R.                  " UR0                  5      n[3        U[$        R&                  R4                  R6                  5      (       d   e[$        R&                  R4                  R9                  UUR:                  SUR<                  S9nU" UUR>                  [@        RC                  URD                  5      5        M     M     g)a  
Sync the package states to the compiled function. This includes the following actions:
  1. Clean up the previously installed states.
  2. Install the compiled functions to global scopes.
  3. Install the precompiled cache entries to ExtraStates on the code object.
r   )_load_precompile_entryBackend # is not found in the given backendsload)guards_serialization_modeshape_code_partsN)#r   r   r   r   r   sysmodulesrY   r\   r   	importlibimport_modulerZ   r)   FunctionTyper   r]   r   rk   _dynamodisabler[   rx   ry   rP   r(   guardsGuardsStateCheckFunctionManageroutput_graphr   guard_managerr   r<   rQ   )rg   r   r   r#   r   r   r   r   function_namer   rh   r   guarded_coderP   check_fn_managers                  r0   installCompilePackage.install)  s    	G;;,,.KD[[!4!45F&+&:&:&@&@&B"$$9#:#:;#G 'C "'!5!5''oo}M$$VB? "6 $//
-&":,.QR  #.$$MM))'2 0 /*  ;;,,.KD % 3 3%||L,E,EF!,0D0D0P0PQQQQ#(==#7#7#L#L --.4%1%B%B	 $M $  '$22"11,2J2JK !4 /rL   c                 v    U R                  5         [        [        U R                  R	                  5       5      S9$ )N)rc   )r   ra   r^   r   r>   r{   s    r0   cache_entryCompilePackage.cache_entryY  s(     tDKK,>,>,@'ABBrL   )r   r   r   r   r   r'   )r$   N)&r@   rA   rB   rC   rR   r   r   ra   r   r   r)   r*   rG   rT   r   rm   r_   rS   r   rI   cached_propertyr   
contextlibcontextmanagerr   r   rF   r   r   r   r   r   
ModuleTyper   r   r   r   rK   r3   rL   r0   r   r      s   
3 1B(C t c 84E+F RV : '+	-^^- - {#	-
 
-. %j#o!6 % % '3 ' ' ' 'I>N4O ' '
E
E ^^
E 
	
E
^^
 
 sm	

 

@s @ @ @8 8x} 8PT 8F
De&6&6 Dc D# DRV D
?.Z_ 5 .$ .`C. CrL   r   c                   :    \ rS rSr\S\4S j5       rS\4S jrSr	g)EagerCacheArtifacti^  r$   c                      g)Nprecompile_eagerr3   r3   rL   r0   rt   EagerCacheArtifact.type`  s    !rL   c                 B    [         R                  " U R                  5      $ r'   rw   r{   s    r0   r|   (EagerCacheArtifact.after_deserializationd  r~   rL   r3   N)
r@   rA   rB   rC   r   rG   rt   r   r|   rK   r3   rL   r0   r   r   ^  s'    "# " "*s *rL   r   c            
           \ rS rSrSrS\SS4S jrS\S\SS4S	 jr	S\S
\
SS4S jrS\S
\
S\\\\\4   4   4S jrSrg)DynamoStoreih  z_
A DynamoStore tracks active CompilePackages, and provides methods to store and retrieve them.
packager$   Nc                     UR                  5       n[        R                  " U5      n[        R                  " [
        R                  5       UR                  US9  g)zKRecords a package to PrecompileContext, so that it can be serialized later.r6   rz   N)r   rx   dumpsr   record_artifactrp   rt   r   )rg   r   r   pickled_results       r0   record_packageDynamoStore.record_packagem  sB    ))+k2)) %%'W->->	
rL   rh   r   c                 ~    [         R                  " U5      n[        R                  " [        R                  5       XS9  g)zBRecords eager fx graphs to PrecompileContext for testing purposes.r   N)rx   r   r   r   r   rt   )rg   rh   r   r   s       r0   record_eager_backend DynamoStore.record_eager_backendu  s,    g.))##%:	
rL   pathc                 X   0 nUR                  5       nUR                   H/  n[        R                  " U5      nUc  [	        SU S35      eXcU'   M1      [        [        R                  R                  US5      S5       n[        R                  " XG5        SSS5        [        [        R                  R                  US5      S5       n[        R                  " X85        SSS5        g! , (       d  f       NX= f! , (       d  f       g= f! [         a  n	[	        SU SU	 35      U	eSn	A	ff = f)	zGSaves a package to a given path. Grabs backends from PrecompileContext.Nr   r   r   wbr   zFailed to save package to : )r   r]   r   serialize_artifact_by_keyr   openosr  joinrx   dump	Exception)
rg   r   r  backend_contentr   rh   serialized_backenddynamo_pathbackend_pathes
             r0   save_packageDynamoStore.save_package|  s    ))+%11J!2!L!LZ!X!)"zl*MN  +=J' 2	Pbggll42D9[K5 :bggll44d;|O: <; :9;; 	P!;D6A3GHaO	PsN   *D =C&2D C7D &
C40D 7
DD D 
D)D$$D)r   c                 (    [        [        R                  R                  US5      S5       n[        R
                  " U5      nSSS5        [        [        R                  R                  US5      S5       n[        R
                  " U5      nSSS5        WR                  5        H  u  pU	R                  5       Xh'   M     [        UW5      n
X4$ ! , (       d  f       N= f! , (       d  f       NY= f! [         a  n[        SU SU 35      UeSnAff = f)zULoads a package from a given path and returns it plus a list of deserialized backendsr   rbNr   z!Failed to load package from path r  )r	  r
  r  r  rx   r   r  r   r   r|   r   )rg   r   r  r  r   r  r  r  rh   r   r   s              r0   load_packageDynamoStore.load_package  s    	Wbggll42D9[$kk+6 :bggll44d;|"(++l"; < $3#8#8#:J*1*G*G*IO' $; [1'' :9;; 	W!B4&1#NOUVV	WsL   *C0 C2C0 5CC0 
CC0 
C-)C0 -C0 0
D:DDr3   )r@   rA   rB   rC   rR   r   r   rS   r   r  rG   r  r5   r_   r  rK   r3   rL   r0   r   r   h  s    
n 
 

z 
C 
D 
PN P# P$ P&(( (	~tJO44	5(rL   r   )+rR   r   dataclassesrI   r   r   loggingr
  rx   rj   r   r)   collections.abcr   typingr   r   r   rk   torch._inductor.package torch._dynamo.precompile_contextr   r   torch.compiler._cacher	   bytecode_transformationr   	getLoggerr@   logger	dataclassr   rN   rG   rS   rT   rV   ra   registerrp   r   r   r   r3   rL   r0   <module>r%     s^         	   
  % ) )   W 6 2 
		8	$ d#)
 )
 $)
X 	  	  	  \3'
mS) " " "0 V V V *23DE * *KC KC\ *05 * *5( 5(rL   