o
    Ih,                  	   @   sp  d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	m
Z
mZmZ d dlmZ d dlZd dlZd dlm  mZ d dlmZ d dlmZmZ d dlmZ d dlmZ d	d
lmZmZm Z m!Z! e"e#Z$G dd dZ%G dd dZ&de'de(e' de'de'fddZ)dedee(e' e*e'e(e' f f defddZ+G dd dZ,	d!dede'de-de,fdd Z.dS )"    N)Path)AnyIOOptionalUnion)Self)config)BuildOptionsBase
CppBuilder)reorder_kwargs)FileLike   )AOTINDUCTOR_DIRARCHIVE_VERSIONCONSTANTS_DIRCUSTOM_OBJ_FILENAME_PREFIXc                   @   sj   e Zd ZdeddfddZdefddZddd	Zd
ede	e
ef ddfddZd
ededdfddZdS )PT2ArchiveWriterarchive_pathreturnNc                 C      || _ d | _d S Nr   archive_fileselfr    r   S/var/www/vscode/kcb/lib/python3.10/site-packages/torch/_inductor/package/package.py__init__      
zPT2ArchiveWriter.__init__c                 C   sD   | j d u sJ tj| jdtjd| _ | dtt | dd | S )Nwcompressionversionarchive_formatpt2)r   zipfileZipFiler   
ZIP_STOREDwritestrstrr   r   r   r   r   	__enter__#   s   
zPT2ArchiveWriter.__enter__c                 G   s"   | j d usJ | j   d | _ d S r   r   closer   argsr   r   r   __exit__,   s   
zPT2ArchiveWriter.__exit__namedatac                 C   s    | j d usJ | j || d S r   )r   r(   )r   r1   r2   r   r   r   r(   2   s   zPT2ArchiveWriter.writestr	file_pathc                 C   s<   t | sJ | d| jdusJ | jj||d dS )z
        Copy a file into the archive.
        name: The destination file inside the archive.
        file_path: The source file on disk.
        z is not a valid file pathN)arcname)r   is_filer   write)r   r1   r3   r   r   r   
write_file6   s   zPT2ArchiveWriter.write_filer   N)__name__
__module____qualname__r   r   r   r+   r0   r)   r   bytesr(   r7   r   r   r   r   r      s    
	r   c                   @   s   e Zd ZdeddfddZdefddZddd	Zd
edefddZ	dededefddZ
deddfddZdee fddZdS )PT2ArchiveReaderr   r   Nc                 C   r   r   r   r   r   r   r   r   B   r   zPT2ArchiveReader.__init__c                 C   s   t j| jdt jd| _| S )Nrr    )r%   r&   r   r'   r   r*   r   r   r   r+   F   s   
zPT2ArchiveReader.__enter__c                 G   s   | j d ur
| j   d S r   r,   r.   r   r   r   r0   L   s   

zPT2ArchiveReader.__exit__r1   c                 C   s   | j d usJ | j |S r   )r   read)r   r1   r   r   r   r?   Q   s   zPT2ArchiveReader.readmemberpathc                 C   s   | j d usJ | j ||S r   )r   extract)r   r@   rA   r   r   r   extract_to_pathU   s   z PT2ArchiveReader.extract_to_pathc                 C   s   | j d usJ | j | d S r   )r   
extractall)r   rA   r   r   r   rD   Y   s   zPT2ArchiveReader.extractallc                 C   s   | j d usJ | j  S r   )r   namelistr*   r   r   r   get_file_names]   s   
zPT2ArchiveReader.get_file_namesr8   )r9   r:   r;   r)   r   r   r+   r0   r<   r?   rC   rD   listrF   r   r   r   r   r=   A   s    
r=   aoti_dir
aoti_filesso_pathr   c                    s  dt dt f fdd}tj| |d}tj| |d}tj|d }t|d }t|}W d    n1 s;w   Y  tdi |d	t	
 i}	t|||	d
}
|
 }|
  t|d }t|}W d    n1 srw   Y  tdi |d	t	
 i}ttj|d ||g||d}| }|  |d }| v rt|d}| }W d    n1 sw   Y  t|d}| }|dd|d    || W d    |S 1 sw   Y  |S )Nsuffixr   c                    s*    D ]}| | r|  S qtd|  )Nz Unable to find file with suffix )endswithRuntimeError)rK   filerI   r   r   get_aoti_file_with_suffixc   s
   
z-compile_so.<locals>.get_aoti_file_with_suffix.cppz.or   z_compile_flags.jsonuse_relative_path)r1   sourcesBuildOptionz_linker_flags.json)r1   rS   rT   
output_dirz_serialized_weights.binrbza+b    i @  r   )r)   osrA   joinsplitextopenjsonloadr	   r   	is_fbcoder
   get_target_file_pathbuildsplitr?   tellr6   )rH   rI   rJ   rP   cpp_fileconsts_o	file_namefcompile_flagscompile_optionsobject_builderoutput_olinker_flagslinker_options
so_builder	output_soserialized_weights_filename	f_weightsserialized_weightsf_soso_sizer   rO   r   
compile_sob   s`   

ru   r   c           
      C   s  t |tr	d|i}t |tsJ dt | tjtfr"|  r"|  s9t | tt	j
fr2t	| ds9J d|  t| s}| D ]f\}}d}d}|D ][}|dkrSqL|drh|d7 }|dkrhtd	| d
|dr}|d7 }|dkr}td| d
t	j|}|trt	jt|}	nt	jt||}	td||	 |t|	| qLqBW d   n1 sw   Y  t | tjtfr| d | S )a_  
    Saves the AOTInductor generated files to the PT2Archive format.

    Args:
        archive_file: The file name to save the package to.
        aoti_files: This can either be a singular path to a directory containing
        the AOTInductor files, or a dictionary mapping the model name to the
        path to its AOTInductor generated files.
    modelzPlease pass a list of AOTI generated files to be packaged or a dictionary mapping model names to their list of AOTI generated files. You can get this list of files through calling `torch._inductor.aot_compile(..., options={aot_inductor.package=True})`.pt2zMExpect archive file to be a file ending in .pt2, or is a buffer. Instead got r    z.sor   zMultiple .so files found in zQ. You might need to clear your cache directory before calling aoti_compile again.rQ   zMultiple .cpp files found in z.Saving AOTI generated file %s to archive in %sN)
isinstancerG   dictioIOBaser   writableseekabler)   rY   PathLikefspathrL   r   itemsrM   rA   basename
startswithr   rZ   r   r   logdebugr7   seek)
r   rI   archive_writer
model_namefilesnum_so_filesnum_cpp_filesrN   filenamenew_filepathr   r   r   package_aoti   sj   






'
r   c                   @   s   e Zd ZdZdejjjddfddZdd Z	de
eef fd	d
Zde
eejf deddfddZdee fddZdee
eef  dd fddZdS )AOTICompiledModelz8
    Callable AOT Inductor loaded model from a .pt2
    loaderr   Nc                 C   s
   || _ d S r   )r   )r   r   r   r   r   r         
zAOTICompiledModel.__init__c                 O   sd   | j  }t|d }t|d }t|t||fd }dd |D }| j |}t||S )Nr   r   c                 S   s   g | ]
}t |tjr|qS r   )ry   torchTensor).0xr   r   r   
<listcomp>   s    z.AOTICompiledModel.__call__.<locals>.<listcomp>)r   get_call_specpytreetreespec_loadstree_flattenr   	boxed_runtree_unflatten)r   r/   kwargs	call_specin_specout_specflat_inputsflat_outputsr   r   r   __call__   s   
zAOTICompiledModel.__call__c                 C   
   | j  S r   )r   get_metadatar*   r   r   r   r      r   zAOTICompiledModel.get_metadataconstants_mapcheck_full_updatec                C   s   | j |d| dS )a  
        Given a mapping of constant fqns to tensors, load the constants into the model.
        You can use ``get_constant_fqns`` to get the list of constant fqns that
        are needed in the compiled model.

        Args:
            constants_map: A mapping of constant fqns to tensors.
            check_full_update: Whether to add check to see if all the constants
            are updated and have values.
        FN)r   load_constants)r   r   r   r   r   r   r     s   z AOTICompiledModel.load_constantsc                 C   r   r   )r   get_constant_fqnsr*   r   r   r   r     r   z#AOTICompiledModel.get_constant_fqnsmemoc                 C   s   t d t| jS )NzOAOTICompiledModel deepcopy warning: AOTICompiledModel.loader is not deepcopied.)r   warningr   r   )r   r   r   r   r   __deepcopy__  s   
zAOTICompiledModel.__deepcopy__)r9   r:   r;   __doc__r   _C_aotiAOTIModelPackageLoaderr   r   rz   r)   r   r   boolr   rG   r   r   r   r   r   r   r   r   r      s    	
"r   rv   FrA   r   run_single_threadedc                 C   s   t | tjtfr|  r|  s't | ttjfr t	| 
ds'J d|  t | tjtfrftjdd)}||   | d td|j tjj|j||}t|W  d    S 1 saw   Y  t	| } tjj| ||}t|S )Nrw   zTUnable to load package. Path must be a buffer or a file ending in .pt2. Instead got )rK   r   z)Writing buffer to tmp file located at %s.)ry   r{   r|   r   readabler~   r)   rY   r   r   rL   tempfileNamedTemporaryFiler6   r?   r   r   r   r1   r   r   r   r   r   )rA   r   r   rg   r   r   r   r   load_package  s6   
 
r   )rv   F)/r{   r]   loggingrY   r   r%   pathlibr   typingr   r   r   r   typing_extensionsr   r   torch._inductortorch.utils._pytreeutils_pytreer   r   torch._inductor.cpp_builderr	   r
   torch.export._tree_utilsr   torch.typesr   pt2_archive_constantsr   r   r   r   	getLoggerr9   r   r   r=   r)   rG   ru   rz   r   r   r   r   r   r   r   r   <module>   sN    
#!;
P1