o
    ei9                  	   @  s  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rbd 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 de*Z+G dd deee%e)f Z,G dd de,e%e)f Z-G dd de,e%e)f Z.G dd de.e%e)f Z/G d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                   @  s   e Zd ZdZdS )
CacheErrorzJ
    Exception raised for errors encountered during cache operations.
    N)__name__
__module____qualname____doc__ r   r   _/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/_inductor/cache.pyr      s    r   c                   @  s,   e Zd ZdZeddd	ZedddZdS )Cachezi
    Abstract base class for cache implementations.
    Provides the interface for cache operations.
    selfr   keyr   returnValue | Nonec                 C     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!   r   r   r   get*       z	Cache.getvaluer   boolc                 C  r$   )  
        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(   r   r   r   insert4   r'   zCache.insertNr    r   r!   r   r"   r#   r    r   r!   r   r(   r   r"   r)   )r   r   r   r   r   r&   r,   r   r   r   r   r   $   s    	r   c                   @  sJ   e Zd ZdZdddZdddZdddZedddZedddZ	dS ) InMemoryCachezL
    In-memory cache implementation using a dictionary and thread lock.
    r    r   r"   Nonec                 C  s   i | _ t | _dS )z6
        Initialize an empty in-memory cache.
        N)_cacher   _lockr    r   r   r   __init__E   s   zInMemoryCache.__init__r!   r   r#   c                 C  sT   | j  | j| }dur|W  d   S 	 W d   dS 1 s#w   Y  dS r%   )r2   r1   r&   r+   r   r   r   r&   L   s   $zInMemoryCache.getr(   r   r)   c                 C  sT   | j  || jv r	 W d   dS || j|< 	 W d   dS 1 s#w   Y  dS )r*   NFT)r2   r1   r+   r   r   r   r,   Y   s   	

$zInMemoryCache.insertenv_varstrc                 C  s  |  }t | }du r|S |dD ]}| }|sqz
|dd\}}W n ty= } ztd|d|d|d}~ww | | }}zt|}W n ttfyg } ztd|d	|d
|d}~ww zt|}	W n ttfy } ztd|d	|d
|d}~ww zt|}
W n tj	y } ztd|d	|d|d}~ww zt|	}W n tj	y } ztd|d	|d|d}~ww |
|
|s||
|krtd|
d||
d|dq|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UnpicklingErrorr,   r&   )clsr5   cacheenv_valkv_pairkey_bytes_reprvalue_bytes_reprerr	key_bytesvalue_bytesr!   r(   r   r   r   from_env_vari   s   	zInMemoryCache.from_env_varfpathr	   c              
   C  s   |  }|  s	|S zt|d}t||_W d   n1 s w   Y  W n tjy< } z	td| d|d}~ww t|jtsKt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openr?   loadr1   rA   r   
isinstancedict)rB   rL   rC   fprH   r   r   r   from_file_path   s*   

zInMemoryCache.from_file_pathNr    r   r"   r0   r-   r.   )r5   r6   r"   r   )rL   r	   r"   r   )
r   r   r   r   r4   r&   r,   classmethodrK   rT   r   r   r   r   r/   @   s    


Mr/   c                   @  s$   e Zd ZdZdd
dZdddZdS )
AsyncCachezE
    Asynchronous cache implementation using ThreadPoolExecutor.
    r    r   r!   r   executorr   r"   Future[Value | None]c                 C  s   | | 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!   rX   r   r   r   	get_async   s   zAsyncCache.get_asyncr(   r   Future[bool]c                 C  s   | | 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.
        )rZ   r,   )r    r!   r(   rX   r   r   r   insert_async   s   zAsyncCache.insert_asyncN)r    r   r!   r   rX   r   r"   rY   )
r    r   r!   r   r(   r   rX   r   r"   r\   )r   r   r   r   r[   r]   r   r   r   r   rW      s    
rW   c                   @  sv   e Zd ZU dZdZded< d$d%ddZed&ddZd'ddZ	d(ddZ
ed)ddZed*ddZed+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"   r0   c                 C  s   |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)ra   )r    ra   r   r   r   r4     s   zOnDiskCache.__init__r	   c                 C  s   t t d | j S )z
        Get the base directory for the cache.
        Returns:
            Path: The base directory path for storing cache files.
        rC   )r	   r
   ra   r3   r   r   r   base_dir  s   zOnDiskCache.base_dirr!   r   c              
   C  sT   z| j tt| dd  W S  ttjfy) } z	td|d|d}~w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.)	rd   r   r?   dumps	hexdigestAttributeErrorPicklingErrorr   r   )r    r!   rH   r   r   r   _fpath_from_key  s   
"
zOnDiskCache._fpath_from_keyrL   r   c                 C  s$   t t|jd |jdd  d 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   r6   parentra   )r    rL   r   r   r   _flock_from_fpath*  s   $zOnDiskCache._flock_from_fpathbytesc                 C  s   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.
        Nrl   )r   r6   r^   r`   encodedigestr3   r   r   r   version_prefix9  s   zOnDiskCache.version_prefixr#   c           	      C  s  |  |}| |}|n | s	 W d   dS d}t| j}t|d}||| jkr3| }W d   n1 s=w   Y  |du rS|  	 W d   dS zt	|}W n tj
yp } z	td|d|d}~ww |W  d   S 1 s}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.
        NrM   zFailed to get key z?, value is potentially corrupted (value is not un-pickle-able).)rj   rn   rN   lenrr   rO   readunlinkr?   r@   rA   r   )	r    r!   rL   flockrJ   prefix_lengthrS   r(   rH   r   r   r   r&   B  s:   



$zOnDiskCache.getr(   r   r)   c              
   C  s   |  |}| |}|jjddd zA|4}t|d}|| j t|| W d   n1 s2w   Y  W d   W dS W d   W dS 1 sLw   Y  W dS  tj	yl } zt
d|d|d|d}~w tyu   Y dS 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)rj   rn   rm   mkdirrO   writerr   r?   dumpri   r   FileExistsError)r    r!   r(   rL   rv   _rS   rH   r   r   r   r,   l  s.   

*			zOnDiskCache.insert)N)r    r   ra   rb   r"   r0   r    r   r"   r	   )r    r   r!   r   r"   r	   )r    r   rL   r	   r"   r   )r    r   r"   ro   r-   r.   )r   r   r   r   r`   __annotations__r4   r   rd   rj   rn   propertyrr   r   r&   r,   r   r   r   r   r^      s   
 		

)r^   c                      s0   e Zd ZdZd fddZedd	d
Z  ZS )InductorOnDiskCachezt
    Inductor-specific on-disk cache implementation.
    Uses a custom base directory for Inductor cache files.
    r    r   r"   r0   c                   s   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)superr4   r3   	__class__r   r   r4     s   zInductorOnDiskCache.__init__r	   c                 C  s   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_dirrC   )%torch._inductor.runtime.runtime_utilsr   r	   ra   )r    r   r   r   r   rd     s   zInductorOnDiskCache.base_dirrU   r   )r   r   r   r   r4   r   rd   __classcell__r   r   r   r   r     s
    r   )1
__future__r   r?   abcr   r   astr   	functoolsr   hashlibr   osr   pathlibr	   tempfiler
   	threadingr   typingr   r   r   r   typing_extensionsr   r   r   torch.utils._filelockr   concurrent.futuresr   r   r6   r_   tupler   ro   rR   listr   r=   r   r   r/   rW   r^   r   r   r   r   r   <module>   s2    ( ! 