
    Wj9              
      >   d dl mZ d dlZd dlmZmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZmZmZ d dlmZmZmZ d dlmZ erd dlm Z m!Z!  ede"e#e$edf                   Z% ede"e#e$edf         e&e'eef         e(e                   Z) G d de*          Z+ G d deee%e)f                   Z, G d de,e%e)f                   Z- G d de,e%e)f                   Z. G d de.e%e)f                   Z/ G d de/e%e)f                   Z0dS )    )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                      e Zd ZdZdS )
CacheErrorzJ
    Exception raised for errors encountered during cache operations.
    N)__name__
__module____qualname____doc__     Z/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/torch/_inductor/cache.pyr   r      s           r    r   c                  B    e Zd ZdZedd            Zedd            ZdS )Cachezi
    Abstract base class for cache implementations.
    Provides the interface for cache operations.
    selfr   keyr   returnValue | Nonec                    dS 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   )r$   r%   s     r!   getz	Cache.get*         r    valuer   boolc                    dS )  
        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%   r,   s      r!   insertzCache.insert4   r+   r    Nr$   r   r%   r   r&   r'   r$   r   r%   r   r,   r   r&   r-   )r   r   r   r   r   r*   r1   r   r    r!   r#   r#   $   s^         
    ^    ^  r    r#   c                  Z    e Zd ZdZddZdd
ZddZedd            Zedd            Z	dS )InMemoryCachezL
    In-memory cache implementation using a dictionary and thread lock.
    r$   r   r&   Nonec                :    i | _         t                      | _        dS )z6
        Initialize an empty in-memory cache.
        N)_cacher   _lockr$   s    r!   __init__zInMemoryCache.__init__E   s     )+66


r    r%   r   r'   c                    | j         5  | j                            |          x}|cddd           S 	 ddd           dS # 1 swxY w Y   dS r)   )r9   r8   r*   r0   s      r!   r*   zInMemoryCache.getL   s     Z 	 	---:	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   AAAAr,   r   r-   c                    | j         5  || j        v r	 ddd           dS || j        |<   	 ddd           dS # 1 swxY w Y   dS )r/   NFT)r9   r8   r0   s      r!   r1   zInMemoryCache.insertY   s     Z 	 	dk!!	 	 	 	 	 	 	 	  %DK	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   88<<env_varstrc           
     D    |             }t          |          x}|S |                    d          D ]}|                                }|s	 |                    dd          \  }}n)# t          $ r}t	          d|d|d          |d}~ww xY w|                                |                                }}	 t          |          }n0# t          t          f$ r}t	          d|d	|d
          |d}~ww xY w	 t          |          }	n0# t          t          f$ r}t	          d|d	|d
          |d}~ww xY w	 t          j        |          }
n.# t          j	        $ r}t	          d|d	|d          |d}~ww xY w	 t          j        |	          }n.# t          j	        $ r}t	          d|d	|d          |d}~ww xY w|
                    |
|          sE|                    |
          |k    r,t	          d|
d|                    |
          d|d          |S )av  
        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UnpicklingErrorr1   r*   )clsr>   cacheenv_valkv_pairkey_bytes_reprvalue_bytes_reprerr	key_bytesvalue_bytesr%   r,   s               r!   from_env_varzInMemoryCache.from_env_vari   s    g&G/L}}S)) 9	 9	GmmooG 3:==a3H3H0 0 0    nnn'nnn  $$&& &&(( -N
(88		,    ooogooo *+;<<,    s2BssRYsss 
l9--)    nnngnnn [11)    r2BrrRYrrr  LLe,, 599S>>U3J3J cscc%))C..ccY^ccc   sx   A((
B2B		B:C

C7C22C7;DD8D33D8<EE< E77E< FG $F;;G fpathr
   c                |    |             }|                                 s|S 	 t          |d          5 }t          j        |          |_        ddd           n# 1 swxY w Y   n+# t          j        $ r}t          d| d          |d}~ww xY wt          |j        t                    st          d| d          |S )a=  
        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openrI   loadr8   rK   r   
isinstancedict)rL   rV   rM   fprR   s        r!   from_file_pathzInMemoryCache.from_file_path   s    }} 	L	eT"" /b%{2/ / / / / / / / / / / / / / /% 	 	 	cccc 	
 %,-- 	mmmm   s:   A$ AA$ AA$ A A$ $B3BBNr$   r   r&   r6   r2   r3   )r>   r?   r&   r   )rV   r
   r&   r   )
r   r   r   r   r;   r*   r1   classmethodrU   r_   r   r    r!   r5   r5   @   s         " " " "        K K K [KZ    [  r    r5   c                  "    e Zd ZdZdd
ZddZdS )
AsyncCachezE
    Asynchronous cache implementation using ThreadPoolExecutor.
    r$   r   r%   r   executorr   r&   Future[Value | None]c                8    |                     | j        |          S )a  
        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%   rd   s      r!   	get_asynczAsyncCache.get_async   s     tx---r    r,   r   Future[bool]c                :    |                     | j        ||          S )aO  
        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.
        )rg   r1   )r$   r%   r,   rd   s       r!   insert_asynczAsyncCache.insert_async   s     t{C777r    N)r$   r   r%   r   rd   r   r&   re   )
r$   r   r%   r   r,   r   rd   r   r&   ri   )r   r   r   r   rh   rk   r   r    r!   rc   rc      sF         . . . .8 8 8 8 8 8r    rc   c                      e Zd ZU dZdZded<   dddZedd            Zd dZ	d!dZ
ed"d            Zed#d            Zed$d            ZdS )%OnDiskCachea?  
    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versionNr$   r   name
str | Noner&   r6   c                    |pd| _         dS )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)rp   )r$   rp   s     r!   r;   zOnDiskCache.__init__  s     +O			r    r
   c                N    t          t                                dz  | j        z  S )z
        Get the base directory for the cache.
        Returns:
            Path: The base directory path for storing cache files.
        rM   )r
   r   rp   r:   s    r!   base_dirzOnDiskCache.base_dir  s"     JLL!!G+di77r    r%   r   c                    	 | j         t          t          j        |                                                    dd         z  S # t
          t          j        f$ r}t          d|d          |d}~ww xY w)a  
        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.)	ru   r   rI   dumps	hexdigestAttributeErrorPicklingErrorr   r   )r$   r%   rR   s      r!   _fpath_from_keyzOnDiskCache._fpath_from_key  s    	=6&,s*;*;#<#<#F#F#H#H"#MMM 45 	 	 	OsOOO 	s   AA A4A//A4rV   r   c                p    t          t          |j        dz  |j        dd         z            dz             S )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   r?   parentrp   )r$   rV   s     r!   _flock_from_fpathzOnDiskCache._flock_from_fpath*  s5     EL72UZ^CDDwNOOOr    bytesc                    t          t          t          j                                                                                            dd         S )z
        Get the version prefix for the cache.
        Returns:
            bytes: The version prefix as bytes, derived from the cache version string.
        Nr   )r   r?   rm   ro   encodedigestr:   s    r!   version_prefixzOnDiskCache.version_prefix9  s>     c+-..557788??AA"1"EEr    r'   c                   |                      |          }|                     |          }|5  |                                s	 ddd           dS d}t          | j                  }t          |d          5 }|                    |          | j        k    r|                                }ddd           n# 1 swxY w Y   |"|                                 	 ddd           dS 	 t          j	        |          }n+# t          j
        $ r}t          d|d          |d}~ww xY w|cddd           S # 1 swxY w Y   dS )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.
        NrX   zFailed to get key z?, value is potentially corrupted (value is not un-pickle-able).)r|   r   rY   lenr   rZ   readunlinkrI   rJ   rK   r   )	r$   r%   rV   flockrT   prefix_lengthr^   r,   rR   s	            r!   r*   zOnDiskCache.getB  s    $$S))&&u-- 	 	==?? 	 	 	 	 	 	 	 	 K 344MeT"" ,b77=))T-@@@"$''))K, , , , , , , , , , , , , , , " 	 	 	 	 	 	 	 	"[11)    oooo 
 1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s_   D3&D363B5)D35B9	9D3<B9	=D3%C:9D3:D"	DD""D33D7:D7r,   r   r-   c                   |                      |          }|                     |          }|j                            dd           	 |5 }t	          |d          5 }|                    | j                   t          j        ||           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   n:# t          j	        $ r}t          d|d|d          |d}~wt          $ r Y dS w xY wdS )	a  
        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   mkdirrZ   writer   rI   dumpr{   r   FileExistsError)r$   r%   r,   rV   r   _r^   rR   s           r!   r1   zOnDiskCache.insertl  s    $$S))&&u--4$777	  '!T%.. '",---E2&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' # 	 	 	___5___   	 	 	55	tsf   B: 
B.0BB.B	B.B	B."B: .B22B: 5B26B: :C1	C  C10C1)N)r$   r   rp   rq   r&   r6   r$   r   r&   r
   )r$   r   r%   r   r&   r
   )r$   r   rV   r
   r&   r   )r$   r   r&   r   r2   r3   )r   r   r   r   ro   __annotations__r;   r   ru   r|   r   propertyr   r   r*   r1   r   r    r!   rm   rm      s           G, , , , , 8 8 8 _8   &P P P P F F F XF ' ' ' X'R    X  r    rm   c                  <     e Zd ZdZd	 fdZed
d            Z xZS )InductorOnDiskCachezt
    Inductor-specific on-disk cache implementation.
    Uses a custom base directory for Inductor cache files.
    r$   r   r&   r6   c                J    t                                          d           dS )z
        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;   zInductorOnDiskCache.__init__  s$    
 	122222r    r
   c                J    ddl m} t           |            d| j                  S )z
        Get the base directory for the Inductor cache.
        Returns:
            Path: The base directory path for Inductor cache files.
        r   )default_cache_dirrM   )%torch._inductor.runtime.runtime_utilsr   r
   rp   )r$   r   s     r!   ru   zInductorOnDiskCache.base_dir  s5     	LKKKKK%%''$)<<<r    r`   r   )r   r   r   r   r;   r   ru   __classcell__)r   s   @r!   r   r     sg         
3 3 3 3 3 3 = = = _= = = = =r    r   )1
__future__r   rI   abcr   r   astr   	functoolsr   hashlibr   osr	   pathlibr
   tempfiler   	threadingr   typingr   r   r   r   typing_extensionsr   r   r   torch.utils._filelockr   concurrent.futuresr   r   r?   rn   tupler   r   r]   listr   rG   r   r#   r5   rc   rm   r   r   r    r!   <module>r      s   " " " " " "  # # # # # # # #       % % % % % %                               7 7 7 7 7 7 7 7 7 7 7 7 : : : : : : : : : : * * * * * *  >======== geS#uS#X//c5c?E4S>4PS9UU           Ce$   8U U U U UE#u*% U U Up8 8 8 8 8sEz" 8 8 8BQ Q Q Q Q*S%Z( Q Q Qh= = = = =+c5j1 = = = = =r    