o
    -i4%                     @   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
mZmZmZmZmZ d dlmZ d dlmZmZmZmZmZmZ d dlmZ d d	lmZ 	 ed
ZeeZ G dd deee Z!G dd dee Z"G dd deZ#dS )    N)abstractmethod)defaultdict)chain)AnyCallableGenericOptionalTypeVarUnion)override)_serialize_single_cacheCacheArtifactCacheArtifactFactoryCacheArtifactManagerCacheArtifactsResult	CacheInfo)AppendingByteSerializer)
OrderedSetTc                   @   sB   e Zd ZdZed
ddZedefddZede	fdd	Z
dS )PrecompileCacheArtifacta5  
    Data for each cache artifact that will be serialized and deserialized by
    PrecompileContext, rather than CacheArtifactManager.
    T represents the deserialized type of the artifact, i.e. the return type of after_deserialization

    PrecompileCacheArtifact is a frozen dataclass - you can add new serializable fields and metadata specific to your own artifacts
    as needed, and use them in after_deserialization.

    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
    returnNc                 C   s   t d)Nz1Precompile cache artifacts do not populate caches)RuntimeErrorself r   Y/home/ubuntu/LTX-2/.venv/lib/python3.10/site-packages/torch/_dynamo/precompile_context.pypopulate_cache3   s   z&PrecompileCacheArtifact.populate_cachec                 C      dS )NTr   r   r   r   r   precompile_compatible7   s   z-PrecompileCacheArtifact.precompile_compatiblec                 C   r   )z
        Code to be run after reading raw byte contents from disk.
        Generally converts self.content from raw bytes back into its original form.
        Nr   r   r   r   r   after_deserialization;   s   z-PrecompileCacheArtifact.after_deserializationr   N)__name__
__module____qualname____doc__r   r   boolr   r   r   r   r   r   r   r   r      s    r   c                   @   sV   e Zd ZdZdedededdfddZdee fd	d
Z	de
def ddfddZdS )EditablePrecompileCacheArtifactzk
    A PrecompileCacheArtifact whose content isn't encoded until we call PrecompileContext.serialize()
    artifact_typecontentkeyr   Nc                 C   s   t || _|| _|| _d S N)copydeepcopyr(   r)   r'   )r   r'   r(   r)   r   r   r   __init__I   s   
z(EditablePrecompileCacheArtifact.__init__c                 C   s0   t | j}t| j| j|}t|tsJ |S )z,
        Actually encode the object
        )	pickledumpsr(   r   encode_creater'   r)   
isinstancer   )r   r(   artifactr   r   r   real_encodeP   s   
z+EditablePrecompileCacheArtifact.real_encodeedit_fn.c                 C   s   || j | _ dS ):
        Edit the content of an existing artifact
        N)r(   )r   r4   r   r   r   edit_contents[   s   z-EditablePrecompileCacheArtifact.edit_contents)r!   r"   r#   r$   strr   r-   r   r   r3   r   r6   r   r   r   r   r&   D   s
    r&   c                       sT  e Zd ZU dZi Zeeeee	 e
f f ed< eeZeed< e Zee
 ed< eedZeeeee
 f  ed< e Zeed< ed" fd
dZee	d#dededededd	f
ddZed"ddZedededef dd	fddZ edede!e
 fddZ"ede!ee#ef  f fddZ$e%dedefddZ&ed"d d!Z'  Z(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.

    The following artifact types are supported by PrecompileContext:
     - BundledAOTAutogradCacheArtifact
     - DynamoCodeStateArtifact
     - AutotuneCacheArtifact (regular autotune results, same as Megacache)
    _new_cache_artifacts_by_key_new_cache_artifacts_seen_artifacts)serialize_fn_serializer_cache_infor   Nc                    s   | j   t   d S r*   )r9   clearsupercls	__class__r   r   r?      s   
zPrecompileContext.clearFr'   r)   r(   editablec                 C   sH   |r	t |||}nt|||}|| jv rdS | j| || j|< dS )zg
        Called from each caching operation to record the artifact in this
        "mega" list
        N)r&   r   r0   r;   addr9   )rB   r'   r)   r(   rE   r2   r   r   r   record_artifact   s   
z!PrecompileContext.record_artifactc                 C   sF   | j  D ]}t|tr| }| j|j  | q| j 	  dS )z
        We normally record artifacts by key, but serialization expects them to be organized
        by artifact type. This function transfers artifacts from _new_cache_artifacts_by_key to _new_cache_artifacts
        N)
r9   valuesr1   r&   r3   r:   rD   typeappendr?   )rB   r2   r   r   r   _save_artifacts_by_type   s
   
z)PrecompileContext._save_artifacts_by_typer4   .c                 C   sD   || j v sJ d| d| j | }t|tsJ d|| dS )r5   zKey  not found in artifactszArtifact is not editableN)r9   r1   r&   r6   )rB   r)   r4   r2   r   r   r   edit_artifact   s   

zPrecompileContext.edit_artifactc                 C   s$   | j |d}t|tr| }|S )zP
        Serialize all artifacts with the given key returned in a list.
        N)r9   getr1   r&   r3   )rB   r)   resultr   r   r   serialize_artifact_by_key   s   
z+PrecompileContext.serialize_artifact_by_keyc                    s    |    d| jvrd S t  S )Nprecompile_dynamo)rK   r:   r@   	serializerA   rC   r   r   rR      s   

zPrecompileContext.serialize	artifactsc                 C   s   t   i }t }t|   D ]}| dkr|  n|||j< || qddl	m
}m} | d D ]:}t|ts<J | }|j}i }	|D ]}
|
|v sUJ d|
 d||
 }t|ts`J ||	|
< qG|||	|j q3|S )Nautotuner   )
_BackendIdDynamoCacherQ   zBackend rL   )r8   "_ensure_cache_artifacts_registeredr   r   rH   rI   r   r)   rF   torch._dynamo.packagerU   rV   r1   r   r   backend_idswrite)rS   artifacts_by_key
cache_infor2   rU   rV   dynamo_entrycache_entrybackendsbackend_contentid_r   r   r   populate_caches   s*   


z!PrecompileContext.populate_cachesc                 C   s   ddl m} ddlm} d S )Nr   )_DynamoCacheArtifact)BundledAOTAutogradCacheArtifact)rX   rc   -torch._functorch._aot_autograd.autograd_cacherd   )rB   rc   rd   r   r   r   rW      s   z4PrecompileContext._ensure_cache_artifacts_registeredr    )F))r!   r"   r#   r$   r9   dictr7   r
   r&   objectr   __annotations__r   listr:   r   r   r;   r   r   r=   tupler   r>   classmethodr?   r   r   r%   rG   rK   r   rM   r   rP   bytesrR   staticmethodrb   rW   __classcell__r   r   rC   r   r8   b   sN   
  	 r8   )$r+   loggingr.   abcr   collectionsr   	itertoolsr   typingr   r   r   r   r	   r
   typing_extensionsr   torch.compiler._cacher   r   r   r   r   r   &torch.utils._appending_byte_serializerr   torch.utils._ordered_setr   r   	getLoggerr!   loggerr   r&   r8   r   r   r   r   <module>   s"      
&