
    ȅi9              
         S SK Jr  S SKrS SKJrJr  S SKJr  S SKJ	r	  S SK
Jr  S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJrJrJrJr  S SKJrJrJr  S SKJr  \(       a  S SKJ r J!r!  \" S\"\#\$\S4   5      r%\" S\"\#\$\S4   \&\'\\4   \(\   5      r) " S S\*5      r+ " S S\\\%\)4   5      r, " S S\,\%\)4   5      r- " S S\,\%\)4   5      r. " S S\.\%\)4   5      r/ " S S\/\%\)4   5      r0g)    )annotationsN)ABCabstractmethod)literal_eval)cached_property)sha256)getenv)Path)
gettempdir)Lock)AnyGenericTYPE_CHECKINGTypeVar)assert_neveroverrideSelf)FileLock)FutureThreadPoolExecutorKey.Valuec                      \ rS rSrSrSrg)
CacheError   zB
Exception raised for errors encountered during cache operations.
 N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       O/home/james-whalen/.local/lib/python3.13/site-packages/torch/_inductor/cache.pyr   r      s    r#   r   c                  @    \ rS rSrSr\SS j5       r\SS j5       rSrg)	Cache$   z]
Abstract base class for cache implementations.
Provides the interface for cache operations.
c                    gz
Retrieve a value from the cache.
Args:
    key (Key): The key to look up.
Returns:
    Value | None: The cached value if present, else None.
Nr   )selfkeys     r$   get	Cache.get*       r#   c                    g)
Insert a value into the cache.
Args:
    key (Key): The key to insert.
    value (Value): The value to associate with the key.
Returns:
    bool: True if the value was inserted, False if the key already exists.
Nr   r*   r+   values      r$   insertCache.insert4   r.   r#   r   Nr*   r   r+   r   returnzValue | Noner*   r   r+   r   r2   r   r6   bool)	r   r   r   r    r!   r   r,   r3   r"   r   r#   r$   r&   r&   $   s/    
    r#   r&   c                  ^    \ rS rSrSrS
S jrSS jrSS jr\SS j5       r	\SS j5       r
Srg	)InMemoryCache@   zD
In-memory cache implementation using a dictionary and thread lock.
c                0    0 U l         [        5       U l        g)z&
Initialize an empty in-memory cache.
N)_cacher   _lockr*   s    r$   __init__InMemoryCache.__init__E   s     )+6
r#   c                    U R                      U R                  R                  U5      =nb  UsSSS5        $  SSS5        g! , (       d  f       g= fr)   )r>   r=   r,   r1   s      r$   r,   InMemoryCache.getL   s<     ZZ--: Z  ZZs    AA
Ac                    U R                      XR                  ;   a
   SSS5        gX R                  U'    SSS5        g! , (       d  f       g= f)r0   NFT)r>   r=   r1   s      r$   r3   InMemoryCache.insertY   s:     ZZkk! Z  %KK ZZs   ??
Ac           
        U " 5       n[        U5      =nc  U$ UR                  S5       H  nUR                  5       nU(       d  M   UR                  SS5      u  pVUR                  5       UR                  5       pe [        U5      n [        U5      n	 [        R                  " U5      n
 [        R                  " U	5      nUR                  X5      (       a  M  UR                  U
5      U:w  d  M  [	        SU
< SUR                  U
5      < SU< S35      e   U$ ! [         a  n[	        SU< SU< S35      UeSnAff = f! [        [        4 a  n[	        SU< S	U< S
35      UeSnAff = f! [        [        4 a  n[	        SU< S	U< S
35      UeSnAff = f! [        R                   a  n[	        SU< S	U< S35      UeSnAff = f! [        R                   a  n[	        SU< S	U< S35      UeSnAff = f)a6  
Create an in-memory cache from an environment variable.
Args:
    env_var (str): Name of the environment variable containing cache data.
Returns:
    InMemoryCache: An instance populated from the environment variable.
Raises:
    CacheError: If the environment variable is malformed or contains invalid data.
N;,   zMalformed kv_pair z from env_var z!, likely missing comma separator.zMalformed key_bytes_repr z in kv_pair z, encoding is invalid.zMalformed value_bytes_repr z, not un-pickle-able.zMultiple values for key z found, got z and .)r	   splitstrip
ValueErrorr   r   SyntaxErrorpickleloadsUnpicklingErrorr3   r,   )clsenv_varcacheenv_valkv_pairkey_bytes_reprvalue_bytes_reprerr	key_bytesvalue_bytesr+   r2   s               r$   from_env_varInMemoryCache.from_env_vari   s@    g&G/L}}S)GmmoG3:==a3H0 $$& &&( -
(8	
*+;<ll9-
[1 LL,,599S>U3J .sg\%))C.ASSXY^Xaabc o *v a   (>'Lmn ,  //Ag[Xno ,  12B1E\RYQ\\rs ))  //Ag[Xmn ))  12B1E\RYQ\\qrsx   D:E E-F)G
D=#D88D= E*E%%E*-F=FFG.GGG9G44G9c                z   U " 5       nUR                  5       (       d  U$  [        US5       n[        R                  " U5      Ul        SSS5        [        UR                  [        5      (       d  [        SU S35      eU$ ! , (       d  f       N>= f! [        R
                   a  n[        SU S35      UeSnAff = f)z
Create an in-memory cache from a file path.
Args:
    fpath (Path): Path to the file containing pickled cache data.
Returns:
    InMemoryCache: An instance populated from the file.
Raises:
    CacheError: If the file is not a valid pickled dictionary.
rbNz&Failed to create cache from file path z#, file contents are un-pickle-able.z-, file contents not pickled dict[Key, Value].)	is_fileopenrO   loadr=   rQ   r   
isinstancedict)rR   fpathrT   fprY   s        r$   from_file_pathInMemoryCache.from_file_path   s     }}L	eT"b%{{2 # %,,--8?lm   #"%% 	8?bc	s4   B B B  
B
B B B:%B55B:)r=   r>   Nr*   r   r6   Noner5   r7   )rS   strr6   r   )re   r
   r6   r   )r   r   r   r    r!   r@   r,   r3   classmethodr\   rg   r"   r   r#   r$   r:   r:   @   sA    "  K KZ  r#   r:   c                  P    \ rS rSrSr        SS jr          SS jrSrg)	
AsyncCache   z=
Asynchronous cache implementation using ThreadPoolExecutor.
c                :    UR                  U R                  U5      $ )z
Retrieve a value from the cache asynchronously.
Args:
    key (Key): The key to look up.
    executor (ThreadPoolExecutor): Executor for async execution.
Returns:
    Future[Value | None]: Future for the cached value or None.
)submitr,   )r*   r+   executors      r$   	get_asyncAsyncCache.get_async   s     txx--r#   c                :    UR                  U R                  X5      $ )a  
Insert a value into the cache asynchronously.
Args:
    key (Key): The key to insert.
    value (Value): The value to associate with the key.
    executor (ThreadPoolExecutor): Executor for async execution.
Returns:
    Future[bool]: Future for the result of insertion.
)rq   r3   )r*   r+   r2   rr   s       r$   insert_asyncAsyncCache.insert_async   s     t{{C77r#   r   N)r*   r   r+   r   rr   r   r6   zFuture[Value | None])
r*   r   r+   r   r2   r   rr   r   r6   zFuture[bool])r   r   r   r    r!   rs   rv   r"   r   r#   r$   rn   rn      sY    ...(:.	.888%*86H8	8r#   rn   c                      \ rS rSr% SrSrS\S'   SSS jjr\SS j5       r	SS	 jr
SS
 jr\SS j5       r\SS j5       r\SS j5       rSrg)OnDiskCache   a#  
On-disk cache implementation using files and file locks.
Stores cache data in files on disk, with atomic operations and versioning.
Supports custom cache directory names.
Attributes:
    version (int): The version used for cache versioning.
    name (str): The name of the cache directory.
r   intversionNc                $    U=(       d    SU l         g)z
Initialize an on-disk cache instance.
Args:
    name (str | None, optional): The name of the cache directory. If None,
        defaults to "on_disk_cache".
on_disk_cacheNname)r*   r   s     r$   r@   OnDiskCache.__init__  s     +O	r#   c                H    [        [        5       5      S-  U R                  -  $ )zk
Get the base directory for the cache.
Returns:
    Path: The base directory path for storing cache files.
rT   )r
   r   r   r?   s    r$   base_dirOnDiskCache.base_dir  s     JL!G+dii77r#   c                     U R                   [        [        R                  " U5      5      R	                  5       SS -  $ ! [
        [        R                  4 a  n[        SU< S35      UeSnAff = f)z
Get the file path for a given key.
Args:
    key (Key): The key to convert to a file path.
Returns:
    Path: The file path for the key.
Raises:
    CacheError: If the key is not pickle-able.
N    zFailed to get fpath for key z, key is not pickle-able.)	r   r   rO   dumps	hexdigestAttributeErrorPicklingErrorr   r   )r*   r+   rY   s      r$   _fpath_from_keyOnDiskCache._fpath_from_key  sl    	==6&,,s*;#<#F#F#H"#MMM 4 45 	.sg5NO	s   <? A/A**A/c                j    [        [        UR                  S-  UR                  SS -  5      S-   5      $ )z
Get a file lock for a given file path.
Args:
    fpath (Path): The file path.
Returns:
    FileLock: The file lock for the path.
locksN   z.lock)r   rk   parentr   )r*   re   s     r$   _flock_from_fpathOnDiskCache._flock_from_fpath*  s1     ELL72UZZ^CDwNOOr#   c                    [        [        [        R                  5      R	                  5       5      R                  5       SS $ )z
Get the version prefix for the cache.
Returns:
    bytes: The version prefix as bytes, derived from the cache version string.
Nr   )r   rk   ry   r|   encodedigestr?   s    r$   version_prefixOnDiskCache.version_prefix9  s3     c+--.5578??A"1EEr#   c                \   U R                  U5      nU R                  U5      nU   UR                  5       (       d
   SSS5        gSn[        U R                  5      n[        US5       nUR                  U5      U R                  :X  a  UR                  5       nSSS5        Uc  UR                  5          SSS5        g [        R                  " U5      nUsSSS5        $ ! , (       d  f       NM= f! [        R                   a  n[        SU< S35      UeSnAff = f! , (       d  f       g= f)a>  
Retrieve a value from the cache.
Args:
    key (Key): The key to look up.
Returns:
    Value | None: The cached value if present and version matches, else None.
Raises:
    CacheError: If the value is corrupted or cannot be unpickled.
Side Effects:
    Removes stale cache files if the version prefix does not match.
Nr_   zFailed to get key z?, value is potentially corrupted (value is not un-pickle-able).)r   r   r`   lenr   ra   readunlinkrO   rP   rQ   r   )	r*   r+   re   flockr[   prefix_lengthrf   r2   rY   s	            r$   r,   OnDiskCache.getB  s    $$S)&&u-==?? U K 3 34MeT"b77=)T-@-@@"$'')K # "  U"[1 1 U #" ))  (/no' UsM   D#D(0CD>C0D
C-	)D0DDDD
D+c                   U R                  U5      nU R                  U5      nUR                  R                  SSS9   U n[	        US5       nUR                  U R                  5        [        R                  " X&5        SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f! [        R                   a  n[        SU< SU< S35      UeSnAf[         a     gf = f)	aQ  
Insert a value into the cache.
Args:
    key (Key): The key to insert.
    value (Value): The value to associate with the key.
Returns:
    bool: True if the value was inserted, False if the key already exists.
Raises:
    CacheError: If the value is not pickle-able.
Side Effects:
    Creates the cache directory if it does not exist.
T)parentsexist_okxbNzFailed to insert key z with value z, value is not pickle-able.F)r   r   r   mkdirra   writer   rO   dumpr   r   FileExistsError)r*   r+   r2   re   r   _rf   rY   s           r$   r3   OnDiskCache.insertl  s     $$S)&&u-4$7	 !T%.",,-E& /  /.  ## 	'wl5)C^_  		sS   B2  B!2B?B!B2 
B	B!!
B/+B2 /B2 2C+CC+*C+r   )N)r*   r   r   z
str | Noner6   rj   r*   r   r6   r
   )r*   r   r+   r   r6   r
   )r*   r   re   r
   r6   r   )r*   r   r6   bytesr5   r7   )r   r   r   r    r!   r|   __annotations__r@   r   r   r   r   propertyr   r   r,   r3   r"   r   r#   r$   ry   ry      sv     GS, 8 8&P F F ' 'R  r#   ry   c                  D   ^  \ rS rSrSrSU 4S jjr\SS j5       rSrU =r	$ )InductorOnDiskCachei  zh
Inductor-specific on-disk cache implementation.
Uses a custom base directory for Inductor cache files.
c                $   > [         TU ]  S5        g)zk
Initialize an inductor on-disk cache instance.
Sets the cache directory name to "inductor_on_disk_cache".
inductor_on_disk_cacheN)superr@   )r*   	__class__s    r$   r@   InductorOnDiskCache.__init__  s    
 	12r#   c                F    SSK Jn  [        U" 5       SU R                  5      $ )zu
Get the base directory for the Inductor cache.
Returns:
    Path: The base directory path for Inductor cache files.
r   )default_cache_dirrT   )%torch._inductor.runtime.runtime_utilsr   r
   r   )r*   r   s     r$   r   InductorOnDiskCache.base_dir  s     	L%'$))<<r#   r   ri   r   )
r   r   r   r    r!   r@   r   r   r"   __classcell__)r   s   @r$   r   r     s!    
3 = =r#   r   )1
__future__r   rO   abcr   r   astr   	functoolsr   hashlibr   osr	   pathlibr
   tempfiler   	threadingr   typingr   r   r   r   typing_extensionsr   r   r   torch.utils._filelockr   concurrent.futuresr   r   rk   r{   tupler   r   rd   listr   rM   r   r&   r:   rn   ry   r   r   r#   r$   <module>r      s    "  #  %      7 7 : : * = eS#uS#X/c5c?E4S>4PS9U Ce$ 8UE#u*% Up8sEz" 8BQ*S%Z( Qh=+c5j1 =r#   