
    i9              
         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         Z0y)    )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y)
CacheErrorzJ
    Exception raised for errors encountered during cache operations.
    N)__name__
__module____qualname____doc__     O/var/www/html/engine/venv/lib/python3.12/site-packages/torch/_inductor/cache.pyr   r      s    r    r   c                  4    e Zd ZdZedd       Zedd       Zy)Cachezi
    Abstract base class for cache implementations.
    Provides the interface for cache operations.
    c                     y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!   getz	Cache.get*       r    c                     y)  
        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!   insertzCache.insert4   r)   r    Nr&   r   r'   r   returnzValue | Noner&   r   r'   r   r-   r   r0   bool)r   r   r   r   r   r(   r.   r   r    r!   r#   r#   $   s/    
    r    r#   c                  L    e Zd ZdZddZd	dZd
dZedd       Zedd       Z	y)InMemoryCachezL
    In-memory cache implementation using a dictionary and thread lock.
    c                0    i | _         t               | _        y)z6
        Initialize an empty in-memory cache.
        N)_cacher   _lockr&   s    r!   __init__zInMemoryCache.__init__E   s     )+6
r    c                    | j                   5  | j                  j                  |      x}|cddd       S 	 ddd       y# 1 sw Y   yxY wr%   )r7   r6   r(   r,   s      r!   r(   zInMemoryCache.getL   sJ     ZZ 	--:	 	 	 	 	s   A A  A	c                    | j                   5  || j                  v r
	 ddd       y|| j                  |<   	 ddd       y# 1 sw Y   yxY w)r+   NFT)r7   r6   r,   s      r!   r.   zInMemoryCache.insertY   sL     ZZ 	dkk!	 	  %DKK	 	 	s   ??Ac           
         |        }t        |      x}|S |j                  d      D ]  }|j                         }|s	 |j                  dd      \  }}|j                         |j                         }}	 t        |      }	 t        |      }		 t        j                  |      }
	 t        j                  |	      }|j                  |
|      r|j                  |
      |k7  st	        d|
d|j                  |
      d|d       |S # t        $ r}t	        d|d|d      |d}~ww xY w# t        t        f$ r}t	        d|d	|d
      |d}~ww xY w# t        t        f$ r}t	        d|d	|d
      |d}~ww xY w# t        j                  $ r}t	        d|d	|d      |d}~ww xY w# t        j                  $ r}t	        d|d	|d      |d}~ww xY w)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UnpicklingErrorr.   r(   )clsenv_var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   sI    g&G/L}}S) 9	GmmoG3:==a3H0 0 $$& &&( -N
(8	
*+;<ll9-
[1 LLe,599S>U3J .sg\%))C.ASSXY^Xaabc o9	v a   (>'Lmn ,  //Ag[Xno ,  12B1E\RYQ\\rs ))  //Ag[Xmn ))  12B1E\RYQ\\qrsw   D5D+EE?#F-	D(D##D(+E:EEE<$E77E<?F*F%%F*-G GGc                X    |        }|j                         s|S 	 t        |d      5 }t        j                  |      |_        ddd       t        |j                  t              st        d| d      |S # 1 sw Y   4xY w# t        j
                  $ r}t        d| d      |d}~ww xY w)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openrE   loadr6   rG   r   
isinstancedict)rH   fpathrJ   fprO   s        r!   from_file_pathzInMemoryCache.from_file_path   s     }}L	eT" /b%{{2/ %,,-8?lm  / /%% 	8?bc	s.   B A5B 5A>:B B)B$$B)Nr&   r   r0   Noner/   r1   )rI   strr0   r   )rZ   r
   r0   r   )
r   r   r   r   r9   r(   r.   classmethodrR   r\   r   r    r!   r4   r4   @   sA    "  K KZ  r    r4   c                  D    e Zd ZdZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZy)
AsyncCachezE
    Asynchronous cache implementation using ThreadPoolExecutor.
    c                :    |j                  | 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'   executors      r!   	get_asynczAsyncCache.get_async   s     txx--r    c                <    |j                  | 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.
        )rd   r.   )r&   r'   r-   re   s       r!   insert_asynczAsyncCache.insert_async   s     t{{C77r    N)r&   r   r'   r   re   r   r0   zFuture[Value | None])
r&   r   r'   r   r-   r   re   r   r0   zFuture[bool])r   r   r   r   rf   rh   r   r    r!   rb   rb      sY    ...(:.	.888%*86H8	8r    rb   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y)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versionNc                    |xs d| _         y)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&   ro   s     r!   r9   zOnDiskCache.__init__  s     +O	r    c                H    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.
        rJ   )r
   r   ro   r8   s    r!   base_dirzOnDiskCache.base_dir  s     JL!G+dii77r    c                    	 | j                   t        t        j                  |            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.)	rq   r   rE   dumps	hexdigestAttributeErrorPicklingErrorr   r   )r&   r'   rO   s      r!   _fpath_from_keyzOnDiskCache._fpath_from_key  sl    	==6&,,s*;#<#F#F#H"#MMM 4 45 	.sg5NO	s   ;> A,A''A,c                j    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_   parentro   )r&   rZ   s     r!   _flock_from_fpathzOnDiskCache._flock_from_fpath*  s1     ELL72UZZ^CDwNOOr    c                    t        t        t        j                        j	                               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_   rj   rl   encodedigestr8   s    r!   version_prefixzOnDiskCache.version_prefix9  s3     c+--.5578??A"1EEr    c                4   | j                  |      }| j                  |      }|5  |j                         s
	 ddd       yd}t        | j                        }t        |d      5 }|j                  |      | j                  k(  r|j                         }ddd       ||j                          	 ddd       y	 t        j                  |      }|cddd       S # 1 sw Y   FxY w# t        j                  $ r}t        d|d      |d}~ww xY w# 1 sw Y   yxY w)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.
        NrT   zFailed to get key z?, value is potentially corrupted (value is not un-pickle-able).)rx   r}   rU   lenr   rV   readunlinkrE   rF   rG   r   )	r&   r'   rZ   flockrQ   prefix_lengthr[   r-   rO   s	            r!   r(   zOnDiskCache.getB  s    $$S)&&u- 	==?	 	 K 3 34MeT" ,b77=)T-@-@@"$'')K, " 	 	"[1 1	 	, , ))  (/no'	 	sM   D #D#/CD7C#DC 	D#D6DDDDc                   | j                  |      }| j                  |      }|j                  j                  dd       	 |5 }t	        |d      5 }|j                  | j                         t        j                  ||       ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w# t        j                  $ r}t        d|d|d      |d}~wt        $ r Y yw xY w)	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)rx   r}   r|   mkdirrV   writer   rE   dumprw   r   FileExistsError)r&   r'   r-   rZ   r   _r[   rO   s           r!   r.   zOnDiskCache.insertl  s     $$S)&&u-4$7	  '!T%. '",,-E2&' ' ' ' '  ## 	'wl5)C^_  		sT   B+ B2BB
B+ B	BB($B+ (B+ +C >CC C )N)r&   r   ro   z
str | Noner0   r^   r&   r   r0   r
   )r&   r   r'   r   r0   r
   )r&   r   rZ   r
   r0   r   )r&   r   r0   bytesr/   r1   )r   r   r   r   rl   __annotations__r9   r   rq   rx   r}   propertyr   r   r(   r.   r   r    r!   rj   rj      sv     GS, 8 8&P F F ' 'R  r    rj   c                  6     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.
    c                $    t         |   d       y)z
        Initialize an inductor on-disk cache instance.
        Sets the cache directory name to "inductor_on_disk_cache".
        inductor_on_disk_cacheN)superr9   )r&   	__class__s    r!   r9   zInductorOnDiskCache.__init__  s    
 	12r    c                F    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_dirrJ   )%torch._inductor.runtime.runtime_utilsr   r
   ro   )r&   r   s     r!   rq   zInductorOnDiskCache.base_dir  s     	L%'$))<<r    r]   r   )r   r   r   r   r9   r   rq   __classcell__)r   s   @r!   r   r     s!    
3 = =r    r   )1
__future__r   rE   abcr   r   astr   	functoolsr   hashlibr   osr	   pathlibr
   tempfiler   	threadingr   typingr   r   r   r   typing_extensionsr   r   r   torch.utils._filelockr   concurrent.futuresr   r   r_   rk   tupler   r   rY   listr   rC   r   r#   r4   rb   rj   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    