o
    eiM                     @   s   d dl Z d dlZd dl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Zd dlmZmZmZmZ 	 edZeeZe
G d	d
 d
ee ZG dd dee ZG dd deZG dd dZdS )    N)abstractmethod)defaultdict)Callable)	dataclass)AnyGenericOptionalTypeVar)
_BackendId_DynamoCacheEntryDynamoCachePrecompileCacheEntryTc                   @   sN   e Zd ZU dZeed< eed< edefddZ	de
def dd	fd
dZd	S )BackendCacheArtifacta@  
    Represents a single serializable backend artifact from a dynamo backend.
    Each BackendCacheArtifact has a key associated with it along with some
    serializable content.

    Example implementation:

    class MyPrecompileCacheArtifact(PrecompileCacheArtifact[MySerializableType]):
        my_field: int

        def after_deserialization(self) -> MySerializableType:
            result = pickle.loads(self.content)
            # Do some extra work post deserialization
            result.my_post_deserialization_function(self.my_field)
            return result
    keycontentreturnc                 C   s   dS )z
        Code to be run after reading raw byte contents from disk.
        Generally converts self.content from raw bytes back into its original form.
        N selfr   r   j/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/_dynamo/precompile_context.pyafter_deserialization1   s   z*BackendCacheArtifact.after_deserializationedit_fn.Nc                 C   s   || j | _ dS )z4
        Edit the contents of the artifact.
        Nr   )r   r   r   r   r   edit_contents9   s   z"BackendCacheArtifact.edit_contents)__name__
__module____qualname____doc__str__annotations__r   r   r   r   r   r   r   r   r   r   r      s   
 r   c                   @   s   e Zd ZdefddZdS )EagerCacheArtifactr   c                 C   s   | j S Nr   r   r   r   r   r   A   s   z(EagerCacheArtifact.after_deserializationN)r   r   r   r   r   r   r   r   r   r!   @   s    r!   c                   @   s   e Zd ZdS )BypassDynamoCacheEntryN)r   r   r   r   r   r   r   r#   E   s    r#   c                	   @   s:  e Zd ZU dZi Zeeee f e	d< i Z
eeef e	d< edddZedee ddfd	d
ZedededdfddZedededef ddfddZededeee  fddZedeeef deeee f deeef fddZedeeef fddZedeeeef eeef f fddZdS )PrecompileContexta  
    PrecompileContext is a special CacheArtifactManager for handling precompilation
    It uses the same interface as CacheArtifactManager, but handles deserialization differently: instead
    of placing each artifact into respective caches, it will stitch all the cache artifacts for a single key
    together and place it into a global Precompile Cache.

    PrecompileContext has two main portions: dynamo_cache_entries and backend_cache_artifacts.
    When saving, PrecompileContext.serialize() will serialize all dynamo cache entries along with any PrecompileCacheArtifacts that
    are needed to save those dynamo cache entries.

    The following artifact types are supported by PrecompileContext:
     - BundledAOTAutogradCacheArtifact

    _backend_artifacts_by_key_dynamo_cache_entriesr   Nc                 C   s   | j   | j  d S r"   )r%   clearr&   )clsr   r   r   r'   b   s   
zPrecompileContext.clearartifactc                 C   sN   ddl m} |  t|| jt|j< W d   dS 1 s w   Y  dS )zQ
        Records a backend artifact to be used with dynamo cache entries
        r   )no_dispatchN)torch.utils._mode_utilsr*   copydeepcopyr%   r
   r   )r(   r)   r*   r   r   r   record_artifactg   s   "z!PrecompileContext.record_artifactcache_entryr   c                 C   s   || j |< d S r"   )r&   )r(   r/   r   r   r   r   record_dynamo_cache_entryy   s   z+PrecompileContext.record_dynamo_cache_entryr   .c                 C   s6   || j v sJ d| d| j t| }|| dS )z:
        Edit the content of an existing artifact
        zKey z not found in artifactsN)r%   r
   r   )r(   r   r   r)   r   r   r   edit_artifact   s   zPrecompileContext.edit_artifactc                 C   s   | j t|dS )zK
        Return the backend cache artifact with the associated key
        N)r%   getr
   )r(   r   r   r   r   serialize_artifact_by_key   s   z+PrecompileContext.serialize_artifact_by_keydynamo_entriesbackend_artifactsc                 C   sZ   t t}|  D ]\}}| }||d< |d | q| D ]
}|d |j q |S )z
        Return a JSON serializable debug dump of all entries in the precompile context
        Called in serialize before serialization, and in populate_caches after deserialization
        r   dynamobackends)r   listitems
debug_infoappendvaluesr   )r4   r5   r:   r   r/   infor)   r   r   r   dump_debug_info   s   
z!PrecompileContext.dump_debug_infoc                 C   s.   |   \}}| D ]
\}}t|| q
|S r"   )create_cache_entriesr9   r   write)r(   precompile_cache_entriesr:   r   entryr   r   r   save_to_dynamo_cache   s   z&PrecompileContext.save_to_dynamo_cachec                    s   | j }| j}t|}t||}t||dtjj	ddd fdddd i }|
 D ]I\}}zt||}|durA|||< W q. tyw }	 z)tjd	|d
d |	}
t|t|
d tjj	ddd  fddd W Y d}	~	q.d}	~	ww ||fS )z
        Grabs all the cache entries in the precompile context and
        stitches them together into full PrecompileCacheEntries.
        )num_entries	artifactsr)   c                   S   
   dddS )Ndynamo_cache_entriesjsonnameencodingr   r   r   r   r   <lambda>      z8PrecompileContext.create_cache_entries.<locals>.<lambda>c                          S r"   r   r   )	debug_strr   r   rL          F)metadata_fn
payload_fnexpect_trace_idNzFailed to create cache entry %sT)exc_info)r   errorc                   S   rF   )Ndynamo_cache_exceptionrH   rI   r   r   r   r   r   rL      rM   c                      rN   r"   r   r   )datar   r   rL      rP   )rQ   rR   )r&   r%   lenr$   r>   rH   dumpstorch_loggingtrace_structuredr9   r   from_cache_entry	Exceptionloggerwarningr   )r(   r4   r5   num_artifactsr:   rA   r   r/   resulterU   r   )rW   rO   r   r?      sV   


z&PrecompileContext.create_cache_entries)r   N)r   r   r   r   r%   dictr
   r   r   r    r&   r   r   classmethodr'   r.   r0   r   r1   r   r3   staticmethodr>   rC   tupler   r?   r   r   r   r   r$   I   sL   
  

r$   )r,   rH   loggingabcr   collectionsr   collections.abcr   dataclassesr   typingr   r   r   r	   rZ   torch._dynamo.packager
   r   r   r   r   	getLoggerr   r_   r   r!   r^   r#   r$   r   r   r   r   <module>   s$    
$