o
    Zh,                  	   @   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   N/var/www/auris/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versionZarchive_formatZ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   r/   r0   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   r/   r1   r   r   r   
write_file6   s   zPT2ArchiveWriter.write_filer   N)__name__
__module____qualname__r   r   r   r)   r.   r'   r   bytesr&   r5   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   r.   L   s   

zPT2ArchiveReader.__exit__r/   c                 C   s   | j d usJ | j |S r   )r   read)r   r/   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>   r?   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   r?   r   r   r   rB   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_namesr6   )r7   r8   r9   r'   r   r   r)   r.   r:   r=   rA   rB   listrD   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)rI   filerG   r   r   get_aoti_file_with_suffixc   s
   
z-compile_so.<locals>.get_aoti_file_with_suffix.cppz.or   z_compile_flags.jsonZuse_relative_path)r/   sourcesBuildOptionz_linker_flags.json)r/   rP   rQ   
output_dirz_serialized_weights.binrbza+b    i @  r   )r'   osr?   joinsplitextopenjsonloadr	   r   Z	is_fbcoder
   Zget_target_file_pathbuildsplitr=   tellr4   )rF   rG   rH   rN   Zcpp_fileZconsts_o	file_namefZcompile_flagsZcompile_optionsZobject_builderZoutput_oZlinker_flagsZlinker_optionsZ
so_builderZ	output_soZserialized_weights_filenameZ	f_weightsZserialized_weightsZf_soZso_sizer   rM   r   
compile_sob   s`   

ra   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.rO   zMultiple .cpp files found in z.Saving AOTI generated file %s to archive in %sN)
isinstancerE   dictioIOBaser   writableseekabler'   rV   PathLikefspathrJ   r   itemsrK   r?   basename
startswithr   rW   r   r   logdebugr5   seek)
r   rG   Zarchive_writer
model_namefilesZnum_so_filesZnum_cpp_filesrL   filenameZnew_filepathr   r   r   package_aoti   sj   






'
rv   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   )rx   )r   rx   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   )re   torchTensor).0xr   r   r   
<listcomp>   s    z.AOTICompiledModel.__call__.<locals>.<listcomp>)rx   Zget_call_specpytreeZtreespec_loadsZtree_flattenr   Z	boxed_runZtree_unflatten)r   r-   kwargsZ	call_specZin_specZout_specZflat_inputsZflat_outputsr   r   r   __call__   s   
zAOTICompiledModel.__call__c                 C   
   | j  S r   )rx   get_metadatar(   r   r   r   r      ry   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)rx   load_constants)r   r   r   r   r   r   r     s   z AOTICompiledModel.load_constantsc                 C   r   r   )rx   get_constant_fqnsr(   r   r   r   r     ry   z#AOTICompiledModel.get_constant_fqnsmemoc                 C   s   t d t| jS )NzOAOTICompiledModel deepcopy warning: AOTICompiledModel.loader is not deepcopied.)rp   warningrw   rx   )r   r   r   r   r   __deepcopy__  s   
zAOTICompiledModel.__deepcopy__)r7   r8   r9   __doc__rz   _C_aotiAOTIModelPackageLoaderr   r   rf   r'   r   r{   boolr   rE   r   r   r   r   r   r   r   r   rw      s    	
"rw   rb   Fr?   rs   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 )Nrc   zTUnable to load package. Path must be a buffer or a file ending in .pt2. Instead got )rI   r   z)Writing buffer to tmp file located at %s.)re   rg   rh   r   readablerj   r'   rV   rk   rl   rJ   tempfileNamedTemporaryFiler4   r=   rr   rp   rq   r/   rz   r   r   r   rw   )r?   rs   r   r`   rx   r   r   r   load_package  s6   
 
r   )rb   F)/rg   rZ   loggingrV   r   r#   pathlibr   typingr   r   r   r   Ztyping_extensionsr   rz   Ztorch._inductorZtorch.utils._pytreeutilsZ_pytreer   r   Ztorch._inductor.cpp_builderr	   r
   Ztorch.export._tree_utilsr   Ztorch.typesr   Zpt2_archive_constantsr   r   r   r   	getLoggerr7   rp   r   r;   r'   rE   ra   rf   rv   rw   r   r   r   r   r   r   <module>   sN    
#!;
P1