
    (ti "                       d dl mZ d dlZd dlZd dlmZ d dlZd dlm	Z	 d dl
mZ ddlmZmZmZmZ  e       rd dlZ ej&                  e      Zej,                  ej.                  ej0                  ej2                  ej4                  ej6                  ej8                  ej:                  ej<                  ej>                  ej@                  ejB                  dZ" G d	 d
      Z#y)    )annotationsN)Path)hf_hub_download)validate_hf_hub_args   )ONNX_EXTERNAL_WEIGHTS_NAMEONNX_WEIGHTS_NAMEis_onnx_availablelogging)ztensor(bool)ztensor(int8)ztensor(uint8)ztensor(int16)ztensor(uint16)ztensor(int32)ztensor(uint32)ztensor(int64)ztensor(uint64)ztensor(float16)ztensor(float)ztensor(double)c                      e Zd Zd	dZd Zed
dd       Zd	ddZ	 	 ddZe	e
	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd              Ze	e
	 	 	 d	 	 	 	 	 	 	 dd              Zy)OnnxRuntimeModelNc                    t         j                  d       || _        |j                  dd       | _        |j                  dt
              | _        y )NzL`diffusers.OnnxRuntimeModel` is experimental and might change in the future.model_save_dirlatest_model_name)loggerinfomodelgetr   r	   r   )selfr   kwargss      m/Volumes/fast/ai/experiments/MLX_z-image/.venv/lib/python3.12/site-packages/diffusers/pipelines/onnx_utils.py__init__zOnnxRuntimeModel.__init__5   s?    bc
$jj)94@!',?AR!S    c                    |j                         D ci c]  \  }}|t        j                  |       }}}| j                  j	                  d |      S c c}}w N)itemsnparrayr   run)r   r   kvinputss        r   __call__zOnnxRuntimeModel.__call__;   sF    -3\\^<^TQ!RXXa[.^<zz~~dF++ =s    Ac                    |t         j                  d       d}|g }nt        |t              s|g}t	        j
                  | |g||      S )au  
        Loads an ONNX Inference session with an ExecutionProvider. Default provider is `CPUExecutionProvider`

        Arguments:
            path (`str` or `Path`):
                Directory from which to load
            provider(`str`, *optional*):
                Onnxruntime execution provider to use for loading the model, defaults to `CPUExecutionProvider`
        z=No onnxruntime provider specified, using CPUExecutionProviderCPUExecutionProvider)	providerssess_optionsprovider_options)r   r   
isinstancelistortInferenceSession)pathproviderr'   r(   s       r   
load_modelzOnnxRuntimeModel.load_model?   s[     KKWX-H#!,d3 01##XJ\Td
 	
r   c                   ||nt         }| j                  j                  | j                        }t	        |      j                  |      }	 t        j                  ||       | j                  j                  t              }|j                         r6t	        |      j                  t              }	 t        j                  ||       yy# t
        j                  $ r Y {w xY w# t
        j                  $ r Y yw xY w)a?  
        Save a model and its configuration file to a directory, so that it can be re-loaded using the
        [`~optimum.onnxruntime.modeling_ort.ORTModel.from_pretrained`] class method. It will always save the
        latest_model_name.

        Arguments:
            save_directory (`str` or `Path`):
                Directory where to save the model file.
            file_name(`str`, *optional*):
                Overwrites the default model file name from `"model.onnx"` to `file_name`. This allows you to save the
                model with a different name.
        N)
r	   r   joinpathr   r   shutilcopyfileSameFileErrorr   exists)r   save_directory	file_namer   model_file_namesrc_pathdst_paths          r   _save_pretrainedz!OnnxRuntimeModel._save_pretrainedW   s     (1'<)BS&&//0F0FG'00A	OOHh/
 &&//0JK??N+445OPH(3  ## 		 '' s$   C /C  CC C65C6c                    t         j                  j                  |      rt        j	                  d| d       yt        j
                  |d        | j                  |fi | y)a$  
        Save a model to a directory, so that it can be re-loaded using the [`~OnnxModel.from_pretrained`] class
        method.:

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to which to save. Will be created if it doesn't exist.
        zProvided path (z#) should be a directory, not a fileNT)exist_ok)osr-   isfiler   errormakedirsr;   )r   r6   r   s      r   save_pretrainedz OnnxRuntimeModel.save_pretrainedv   sS     77>>.)LL?>*::]^_
NT2 	n77r   c	                   ||nt         }
t        j                  j                  |      rOt        j                  t        ||
      j                         |||	j                  d            }t        |      |	d<   nit        ||
||||      }t        |      j                  |	d<   t        |      j                  |	d<   t        j                  ||||	j                  d            } | dd|i|	S )a;  
        Load a model from a directory or the HF Hub.

        Arguments:
            model_id (`str` or `Path`):
                Directory from which to load
            token (`str` or `bool`):
                Is needed to load models from a private or gated repository
            revision (`str`):
                Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id
            cache_dir (`str | Path`, *optional*):
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            file_name(`str`):
                Overwrites the default model file name from `"model.onnx"` to `file_name`. This allows you to load
                different model files from the same repository or directory.
            provider(`str`):
                The ONNX runtime provider, e.g. `CPUExecutionProvider` or `CUDAExecutionProvider`.
            kwargs (`Dict`, *optional*):
                kwargs will be passed to the model during initialization
        r(   )r.   r'   r(   r   )repo_idfilenametokenrevision	cache_dirforce_downloadr   r    )r	   r>   r-   isdirr   r/   r   as_posixpopr   parentname)clsmodel_idrF   rG   rI   rH   r7   r.   r'   r   r8   r   model_cache_paths                r   _from_pretrainedz!OnnxRuntimeModel._from_pretrained   s    L (1'<)BS77=="$//X/88:!)!',>!?	 0 E (,H~F#$  / (!#-  (,,<'='D'DF#$*./?*@*E*EF&'$// !)!',>!?	 0 E ))&))r   c           	         d }t        t        |      j                  d            dk(  r|j                  d      \  }} | j                  d|||||d|S )N@r   )rQ   rG   rH   rI   rF   rJ   )lenstrsplitrS   )rP   rQ   rI   rF   rH   model_kwargsrG   s          r   from_pretrainedz OnnxRuntimeModel.from_pretrained   sk     s8}""3'(A-!)!4Hh#s## 
)
 
 	
r   r   )NNN)r-   
str | Path)r6   r[   r7   
str | None)r6   zstr | os.PathLike)NNFNNNN)rQ   r[   rF   zbool | str | None | NonerG   zstr | None | NonerI   boolrH   r\   r7   r\   r.   r\   r'   z'ort.SessionOptions' | None)TNN)rQ   r[   rI   r]   rF   r\   rH   r\   )__name__
__module____qualname__r   r#   staticmethodr/   r;   rB   classmethodr   rS   rZ   rJ   r   r   r   r   4   s   T, 
 
.>8)8,  +/&*$ $ $#48A*A* (A* $	A*
 A* A* A* A* 2A*  A*F   $  $

 
 	

 
  
r   r   )$
__future__r   r>   r2   pathlibr   numpyr   huggingface_hubr   huggingface_hub.utilsr   utilsr   r	   r
   r   onnxruntimer+   
get_loggerr^   r   bool_int8uint8int16uint16int32uint32int64uint64float16float32float64ORT_TO_NP_TYPEr   rJ   r   r   <module>rx      s   " # 	    + 6 ] ]  
		H	% HHGGXXXXiiXXiiXXiizzZZjj r
 r
r   