o
    di~                    @   s  d Z 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	m
Z
mZmZmZmZmZmZmZm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 ddlmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ e	rzddl,m-Z- e(.e/Z0e" se! se01d e" rddl2Z2ddlm3Z3 e! rddlm4Z4 e* rddl5m6Z6 ddl7m8Z8m9Z9m:Z: ee gdf Z;ee<e;f Z=dd Z>dede<de;fddZ?dee<ee<ee<df f f d e<dee<e=f fd!d"Z@d#d$ ZAd*d&d'ZBG d(d) d)ZCdS )+zModel export tasks manager.    N)partial)Path)
TYPE_CHECKINGAnyCallableDictListOptionalSetTupleTypeUnion)HfApi)HUGGINGFACE_HUB_CACHE)OfflineModeIsEnabled)version)ConnectionError)
AutoConfigPretrainedConfigis_tf_availableis_torch_available)SAFE_WEIGHTS_NAMETF2_WEIGHTS_NAMEWEIGHTS_NAMEhttp_user_agentlogging   )is_diffusers_availableis_onnx_available   )ExporterConfigzThe export tasks are only supported for PyTorch or TensorFlow. You will not be able to export models without one of these libraries installed.)PreTrainedModel)TFPreTrainedModel)DiffusionPipeline)"AUTO_IMAGE2IMAGE_PIPELINES_MAPPINGAUTO_INPAINT_PIPELINES_MAPPING!AUTO_TEXT2IMAGE_PIPELINES_MAPPINGr    c                 C   s   t  t d}||  S )N)onnxtflite)r   r   )backendbackend_availablilty r+   e/lsinfo/ai/hellotax_ai/llm_service/venv_embed/lib/python3.10/site-packages/optimum/exporters/tasks.pyis_backend_availableA   s   r-   
config_clstaskreturnc                 C   sL   d|v rt | ddst|  dt| d|ddd}|S t| |d}|S )	N
-with-pastSUPPORTS_PASTFz" does not support tasks with past.T )use_pastr/   r/   )getattr
ValueErrorr   replace)r.   r/   constructorr+   r+   r,   (make_backend_config_constructor_for_taskI   s   r:   supported_tasks.	exportersc            	      O   s~   i }|  D ]6\}}t|r<ttd| d|}i ||< | D ]}t|tr0|\}}||vr0q t||}||| |< q q|S )a  
    Generates the mapping between supported tasks and their corresponding `ExporterConfig` for a given model, for
    every backend.

    Args:
        supported_tasks (`Tuple[Union[str, Tuple[str, Tuple[str, ...]]]`):
            The names of the supported tasks.
            If some task is supported by only a subset of all the backends, it can be specified as follows:
                ```python
                >>> ("multiple-choice", ("onnx",))
                ```

            The line above means that the multiple-choice task will be supported only by the ONNX backend.

        exporters (`Dict[str, str]`):
            The export backend name -> config class name mapping. For instance:
            ```python
            >>> exporters = {  # doctest: +SKIP
            ...     "onnx": "BertOnnxConfig",
            ...     "tflite": "BertTFLiteConfig",
            ...     ...
            ... }
            ```

    Returns:
        `Dict[str, TaskNameToExportConfigDict]`: The dictionary mapping a task to an `ExporterConfig` constructor.
    zoptimum.exporters.z.model_configs)itemsr-   r6   	importlibimport_module
isinstancetupler:   )	r;   r<   mappingr)   config_cls_namer.   r/   supported_backends_for_taskconfig_constructorr+   r+   r,   supported_tasks_mappingS   s    

rF   c                  C   sP   i } dt fdtfdtffD ]\}}i | |< | D ]\}}|j| | |< qq| S )1task -> model mapping (model type -> model class)text-to-imageimage-to-image
inpainting)r&   r$   r%   r=   __name__)tasks_to_model_mapping	task_namemodel_mapping
model_typemodel_classr+   r+   r,   $get_diffusers_tasks_to_model_mapping   s   rQ   ptc                 C   s   |dkr
t d}n	|dkrt d}i }|  D ](\}}t|tr%|f}i ||< |D ]}t||d}|dur@|| |jj q+q|S )rG   rR   z&transformers.models.auto.modeling_autotfz)transformers.models.auto.modeling_tf_autoN)r>   r?   r=   r@   strr6   update_model_mapping)tasks_to_model_loader	frameworkauto_modeling_modulerL   rM   model_loadersmodel_loadermodel_loader_classr+   r+   r,   'get_transformers_tasks_to_model_mapping   s    

r]   c                   @   sb  e Zd ZdZi Zi Zi Zi Zi Zi Z	i Z
i Zi Ze r~i dddddddd	d
ddddddddddddddddddddddd d!dd"d#d$d%d&d'd(d)d*d+	Zeed,d-Zdd.iZd/d/d0Ze rwd1d2d3d4Ze Z	eeeed5Ze ri d6d7dd8dd9d:d;dd<d=d>d?d@dAdBddCddDddEddFdGdHddIddJddKdLdMdNdOiZ
dPe
iZee
dQd-Zi dRddSd:dTdUdVddWdXdYddddZdd[d=d\d]d^d?d_dd`dadbd=dcddded=dfdd?dddgdgdgdhZdidjdkdldldmdndodpZdqZdrdsiZededededGedGedGedGedGdtZdsediZeddZeddZduZi dvedddweddd?ddAddxdydzeddXd:dUd=d]d?dd{eddd|eddd?ddAdd}dyd~eddd?ddAddeddd?ddAddeddXd:dUd=d]d?ddeddXd:dUd=d]deddXd:dUd=d]deddXd:dUd?dAdeddd?ddAdddydeddLdeddLdeddeddXd:dUdedi deddd?ddAdddydedddedddedddeddeddd?ddAddedddeddddddeddd?dAdddydeddd?dAdddydedd!deddddeddddedddeddd?ddAdddydeddd6ddedi dedd
ddGdedddeddd?ddAdddyded=d]deddd?dAdeddXdd:dUdAdeddd?ddAdddydeddXd:dUd?dedd
deddXd:dUd?dAdeddXd:dUd?dAdeddXd:dUdd?deddXd:dUd?deddXd:dUd?deddedddedddi deddd?ddAddeddded:dUdeddd?dAdeddd?dAdeddd?dAdedddeddXd=d]deddddd?dAdeddXd=d]d:dUdedd?dAddedddeddXd:dUd=d]d?ddedddeddXd:dUd?dedddeddd?ddAdddyi deddd?ddAddeddddedddedddeddd?dAdeddXddadeddd?ddAdddyded:dUd?deddXd=d]dedddeddXd=d]deddddd?dAdeddNdeddNdeddXd:dUdd?dedd؃dedd؃i deddXd:dUd?dAdeddXd:dUd?deddXd:dUd?dAdeddXd:dUd?deddXd:dUdeddXd:dUdeddXd:dUdeddXd:dUd=d]deddd?deddXd:dUd?deddXd:dUd?dedddddedddedddedddeddddydeddd?ddAdddyi deddd?dAddddydeddeddeddeddddGdeddddeddddeddLdeddeddeddeddXddadedddedddeddd?ddAddedddd edddi dedddeddXd=d]dedddeddXdddeddddeddddddeddd6ddedddd	edd
edddeddedddeddddddeddddddeddddddeddXdddadeddd?ddAdddyeddd?ddAdddyedddZeeeed5Zh dZee ee B ee B ee B e Z e!	d^de"de#de$e"e%e"df ge$e&ge&f f fddZ'e(	d_de"d e"d!e)e" d"e)e" de*f
d#d$Z+e(d%e"d e"de,e" fd&d'Z-e(d%e"de.e" fd(d)Z/e(d%e"de"fd*d+Z0e(d,e"fd-d.Z1e(	,			Pd`d%e"d,e"de)e" d/e)e" d0e"de&fd1d2Z2e(d3e3dddfd4e4e"e5f d5e"d6e"d7e)e4e#e"f  d8e)e4e#e"f  d9e)e" fd:d;Z6e(d3de3dfd4e4e"e5f d5e"d9e)e" d6e"d8e)e4e#e"f  de"fd<d=Z7e!		d_d>e)e4d?  d@e)e&e4d?   de"fdAdBZ8e!d3de3ddfd4e"d5e"d9e)e" d6e"d8e)e4e#e"f  d"e)e" de"fdCdDZ9e!d3de3ddfd>e4e"dEdFdGe&f d5e"d9e)e" d6e"d8e)e4e#e"f  d"e)e" de"fdHdIZ:e!		d_d>e)e4d?  d@e)e&e4d?   fdJdKZ;e!d3de3dfd4e4e"e5f d5e"d9e)e" d6e"d8e)e4e#e"f  f
dLdMZ<e!d3de3dfd>e4e"dEdFdGe&f d5e"d9e)e" d6e"d8e)e4e#e"f  f
dNdOZ=e!	dad>e4d? d"e)e" fdPdQZ>e(dRdS Z?e(d3de3dddddfd%e"d4e4e"e5f d5e"d9e)e" d6e"d8e)e4e#e"f  d,e)e" dTe)dU dVe)e4dWe"f  d"e)e" de4d? fdXdYZ@e(						dbd e"d>e)e4dZ  d%e"de)e" d!e)e" d[e)eAe"eBf  d"e)e" deCfd\d]ZDdS (c  TasksManagerz^
    Handles the `task name -> model class` and `architecture -> configuration` mappings.
    zaudio-classificationAutoModelForAudioClassificationzaudio-frame-classification$AutoModelForAudioFrameClassificationzaudio-xvectorAutoModelForAudioXVectorautomatic-speech-recognition)AutoModelForSpeechSeq2SeqAutoModelForCTCzdepth-estimationAutoModelForDepthEstimationfeature-extraction	AutoModelz	fill-maskAutoModelForMaskedLMimage-classificationAutoModelForImageClassificationzimage-segmentation)AutoModelForImageSegmentation AutoModelForSemanticSegmentation AutoModelForInstanceSegmentation!AutoModelForUniversalSegmentationrI   AutoModelForImageToImageimage-to-text)AutoModelForVision2Seqrg   zmask-generationz	masked-imAutoModelForMaskedImageModelingzmultiple-choiceAutoModelForMultipleChoicezobject-detectionAutoModelForObjectDetectionquestion-answeringAutoModelForQuestionAnsweringreinforcement-learningrl   )AutoModelForTextToSpectrogramAutoModelForTextToWaveformAutoModelForCausalLMAutoModelForSeq2SeqLM"AutoModelForSequenceClassificationAutoModelForTokenClassification#AutoModelForVisualQuestionAnswering'AutoModelForZeroShotImageClassification#AutoModelForZeroShotObjectDetection)	semantic-segmentationtext-to-audiotext-generationtext2text-generationtext-classificationtoken-classificationvisual-question-answeringzero-shot-image-classificationzero-shot-object-detectionrR   rX   create_modelSentenceTransformer)rf   sentence-similarityAutoPipelineForImage2ImageAutoPipelineForInpaintingAutoPipelineForText2Image)rI   rJ   rH   )	diffuserssentence_transformerstimmtransformersdocument-question-answering'TFAutoModelForDocumentQuestionAnsweringTFAutoModelTFAutoModelForMaskedLMr   TFAutoModelForCausalLM!TFAutoModelForImageClassificationr   TFAutoModelForSeq2SeqLMr   $TFAutoModelForSequenceClassificationr   !TFAutoModelForTokenClassificationTFAutoModelForMultipleChoiceTFAutoModelForQuestionAnsweringTFAutoModelForImageSegmentation!TFAutoModelForMaskedImageModelingr   "TFAutoModelForSemanticSegmentationTFAutoModelForSpeechSeq2Seq!TFAutoModelForAudioClassificationTFAutoModelForVision2Seqr   )TFAutoModelForZeroShotImageClassificationr   %TFAutoModelForZeroShotObjectDetectionr   rS   z	audio-ctcz	causal-lmzcausal-lm-with-pastztext-generation-with-pastdefaultzdefault-with-pastfeature-extraction-with-pastz	masked-lmr   z
seq2seq-lmzseq2seq-lm-with-pastztext2text-generation-with-pastzsequence-classificationzspeech2seq-lmzspeech2seq-lm-with-pastz&automatic-speech-recognition-with-pastsummarizationztext-to-speechr   translationzvision2seq-lmrH   )zzero-shot-classificationzimage-feature-extractionpretrainingzstable-diffusionzstable-diffusion-xlzlatent-consistency)r   ColPaliForRetrieval)r   PatchTSMixerForPrediction)r   PatchTSTForPrediction)r   "Pix2StructForConditionalGeneration)r   VisualBertForQuestionAnswering)r   VisionEncoderDecoderModel)r   VitPoseForPoseEstimation))rR   colpalirf   )rR   patchtsmixertime-series-forecasting)rR   patchtstr   )rR   
pix2structrp   )rR   r   r   )rR   visual_bertru   )rR   vision-encoder-decoderr   )rR   vitposekeypoint-detection)rb   r   r   rp   r   r   r   zdefault-timm-config)
t5-encoder	clip-textclip-text-with-projectionflux-transformer-2dsd3-transformer-2dunet-2d-conditionvae-encodervae-decoder)cliptransformerzaudio-spectrogram-transformeralbertAlbertTFLiteConfig)r(   bartbeitbertBertTFLiteConfigrembertbig_birdbigbird_pegasus
blenderbotzblenderbot-smallbloom	camembertCamembertTFLiteConfigchinese_clipr   clip_vision_modelcodegenr   convbertConvBertTFLiteConfigconvnext
convnextv2cvtd_finezdata2vec-textzdata2vec-visionzdata2vec-audiodebertaDebertaTFLiteConfigz
deberta-v2DebertaV2TFLiteConfigdecision_transformerdeitdetrdinov2
distilbertDistilBertTFLiteConfigdonutzimage-to-text-with-pastz%document-question-answering-with-pastz
donut-swindptefficientnetelectraElectraTFLiteConfigzencoder-decoderesmfalconflaubertFlaubertTFLiteConfiggemmaglpngpt2gpt_bigcodegptjgpt_neogpt_neoxgroupvithierahubertibertimagegpt	internlm2layoutlm
layoutlmv3liltlevitlongt5
longformermarianmarkuplm
maskformermbartzmgp-strmistralmctct
mobilebertMobileBertTFLiteConfigzmegatron-bert	mobilevitmobilenet_v1mobilenet_v2
modernbert	moonshinempnetMPNetTFLiteConfigmptmt5musicgenm2m_100nystromformerowlv2owlvitoptr   r   r   qwen2qwen3	qwen3_moellamagraniteolmoolmo2pegasus	perceiverphiphi3r   r   z#visual-question-answering-with-past
poolformerpvtregnetresnetResNetTFLiteConfigrobertaRobertaTFLiteConfigroformerRoFormerTFLiteConfigrt_detr
rt_detr_v2sam	segformersewzsew-dsiglipsiglip-textsiglip-text-with-projectionsiglip_vision_modelspeech_to_textspeecht5splintersqueezebertswinswinv2swin2srt5ztable-transformertrocr	unispeechzunispeech-satr   vitvit_maevit_msnr   r   vitswavlmwav2vec2zwav2vec2-conformerwhisperxlmXLMTFLiteConfigXLMRobertaTFLiteConfig)zxlm-robertayolos>   r>  r   r   r3  r   r   r   r   r   r   r4  Fr)   overwrite_existingr0   .c                    s6   dddt dt dt dttgtf f fdd}|S )	aI  
        Creates a register function for the specified backend.

        Args:
            backend (`str`):
                The name of the backend that the register function will handle.
            overwrite_existing (`bool`, defaults to `False`):
                Whether or not the register function is allowed to overwrite an already existing config.

        Returns:
            `Callable[[str, Tuple[str, ...]], Callable[[Type], Type]]`: A decorator taking the model type and a the
            supported tasks.

        Example:
            ```python
            >>> register_for_new_backend = create_register("new-backend")

            >>> @register_for_new_backend("bert", "text-classification", "token-classification")
            >>> class BertNewBackendConfig(NewBackendConfig):
            >>>     pass
            ```
        r   library_namerO   r;   rM  r0   c                   s$   dt dt f fdd}|S )Nr.   r0   c                    s   t j }|i }| i }D ].}|dd}| vr3d }td| d| ds:||v r:qt| |||< q|| < ||< | S )Nr1   r3   , z0The TasksManager does not know the task called "z", known tasks: .)r^   !_LIBRARY_TO_SUPPORTED_MODEL_TYPESgetr8   get_all_tasksjoinr7   r:   )r.    supported_model_type_for_libraryrB   mapping_backendr/   normalized_taskknown_tasks)r)   clsrM  rO   rK  r;   r+   r,   	decorator  s$   z@TasksManager.create_register.<locals>.wrapper.<locals>.decorator)r   )rO   rM  r;   rY  r)   rX  rK  )rM  rO   r;   r,   wrapper  s    z-TasksManager.create_register.<locals>.wrapper)rT   r   r   )rX  r)   rK  r[  r+   rZ  r,   create_register  s   zTasksManager.create_registerNrO   exporter
model_namerM  c                 C   s   |du rt d i tjtjtjtj}d}ntj| }|r)|  d| dn| }d}|tjv r7tj| }| |vrY|durB|} nt	| d| dt
|  d| d	|  d

|||  vrut	| d| dt
||    d| d
||  | S )a  
        Retrieves the `task -> exporter backend config constructors` map from the model type.

        Args:
            model_type (`str`):
                The model type to retrieve the supported tasks for.
            exporter (`str`):
                The name of the exporter.
            model_name (`Optional[str]`, defaults to `None`):
                The name attribute of the model object, only used for the exception message.
            library_name (`Optional[str]`, defaults to `None`):
                The library name of the model. Can be any of "transformers", "timm", "diffusers", "sentence_transformers".

        Returns:
            `TaskNameToExportConfigDict`: The dictionary mapping each task to a corresponding `ExporterConfig`
            constructor.
        NzNot passing the argument `library_name` to `get_supported_tasks_for_model_type` is deprecated and the support will be removed in a future version of Optimum. Please specify a `library_name`. Defaulting to `"transformers`.r   z ()z is not supported yet for z. Only z are supported for the library z. If you want to support z) please propose a PR or open up an issue.z is not supported yet with the z backend. Only z' are supported. If you want to support )loggerwarningr^   _DIFFUSERS_SUPPORTED_MODEL_TYPE_TIMM_SUPPORTED_MODEL_TYPE+_SENTENCE_TRANSFORMERS_SUPPORTED_MODEL_TYPE_SUPPORTED_MODEL_TYPErP  _MODEL_TYPE_FOR_DEFAULT_CONFIGKeyErrorlistkeys)rO   r]  r^  rM  rT  model_type_and_model_namedefault_model_typer+   r+   r,   "get_supported_tasks_for_model_type  sP   



z/TasksManager.get_supported_tasks_for_model_typer/   c                    s    fddt jD }|S )zv
        Returns the list of supported architectures by the exporter for a given task. Transformers-specific.
        c                    s"   g | ]}t j|   v r|qS r+   r^   re  ).0rO   r]  r/   r+   r,   
<listcomp>Z  s
    zBTasksManager.get_supported_model_type_for_task.<locals>.<listcomp>rm  )r/   r]  supported_model_typesr+   ro  r,   !get_supported_model_type_for_taskT  s   z.TasksManager.get_supported_model_type_for_taskc                    sb    fddt j D }| fddt j D 7 }t|}z|  W |S  ty0   Y |S w )Nc                    s   g | ]
\}}| kr|qS r+   r+   rn  kvr5   r+   r,   rp  d  s    z2TasksManager.synonyms_for_task.<locals>.<listcomp>c                    s"   g | ]\}}|t  kr|qS r+   )r^   map_from_synonymrs  r5   r+   r,   rp  e  s   " )r^   _SYNONYM_TASK_MAPr=   setremoverg  )r/   synonymsr+   r5   r,   synonyms_for_taskb  s   zTasksManager.synonyms_for_taskc                 C   s   | t jv r
t j|  } | S N)r^   rw  r5   r+   r+   r,   rv  m  s   

zTasksManager.map_from_synonymrX   c                 C   sL   | dvrt d|  d| dkrt std| dkr"t s$tddS dS )	z
        Validates if the framework requested for the export is both correct and available, otherwise throws an
        exception.
        )rR   rS   z<Only two frameworks are supported for export: pt or tf, but z was provided.rR   zGCannot export model using PyTorch because no PyTorch package was found.rS   zMCannot export model using TensorFlow because no TensorFlow package was found.N)r7   r   RuntimeErrorr   r   r+   r+   r,   _validate_framework_choices  s   z'TasksManager._validate_framework_choicemodel_class_namelibraryc           	   	      s  |  dd} t| } t| ||| ftjv r,tj||| f \}}t|}t||S |dkr6tj|  ntj	|  t|}|du r|  vr\t
d|  dd fdd	 D  t |  trh |  }nS|d
kr|du rtd|  d |   d |  d  d  |  d }n/ |  D ]}t||}||jjv r|} nq|du rtd |   d| d|  dntdt||S )aH  
        Attempts to retrieve an AutoModel class from a task name.

        Args:
            task (`str`):
                The task required.
            framework (`str`, defaults to `"pt"`):
                The framework to use for the export.
            model_type (`Optional[str]`, defaults to `None`):
                The model type to retrieve the model class for. Some architectures need a custom class to be loaded,
                and can not be loaded from auto class.
            model_class_name (`Optional[str]`, defaults to `None`):
                A model class name, allowing to override the default class that would be detected for the task. This
                parameter is useful for example for "automatic-speech-recognition", that may map to
                AutoModelForSpeechSeq2Seq or to AutoModelForCTC.
            library (`str`, defaults to `transformers`):
                The library name of the model. Can be any of "transformers", "timm", "diffusers", "sentence_transformers".

        Returns:
            The AutoModel class corresponding to the task.
        r1   r3   rR   NzUnknown task: z. Possible values are: rN  c                    s    g | ]}d | d |  qS )`z` for r+   )rn  keyrW   r+   r,   rp         z9TasksManager.get_model_class_for_task.<locals>.<listcomp>r   z"No model type passed for the task z1, that may be mapped to several loading classes (z). Defaulting to r   z to load the model.z#Unrecognized configuration classes z" do not match with the model type z
 and task rO  z]For library other than transformers, the _TASKS_TO_MODEL_LOADER mapping should be one to one.)r8   r^   rv  r~  _CUSTOM_CLASSESr>   r?   r6   %_LIBRARY_TO_TASKS_TO_MODEL_LOADER_MAP(_LIBRARY_TO_TF_TASKS_TO_MODEL_LOADER_MAPrg  rS  r@   rT   r`  ra  rV   r7   NotImplementedError)	r/   rX   rO   r  r  
class_nameloaded_libraryautoclass_namemoduler+   r  r,   get_model_class_for_task  sb   










z%TasksManager.get_model_class_for_taskr3   model_name_or_path	subfolder	cache_diruse_auth_tokentokenrevisionc              
      sB  |d urt dt |d urtd|}d }t|  tt |d}  r6 fddt	 D }||fS z)t
| ts@t| } |j| d||d}dkr[fd	d|D }W ||fS W ||fS  ttfy }	 z3|j| |||d
}
t|
   r fddt	 D }n|	}W Y d }	~	||fS W Y d }	~	||fS d }	~	ww )NnThe `use_auth_token` argument is deprecated and will be removed soon. Please use the `token` argument instead.LYou cannot use both `use_auth_token` and `token` arguments at the same time.
user_agentr  c              	      4   g | ]\}}}|D ]}t jt j|| q	qS r+   ospathrelpathrS  rn  dirpath_	filenamesfilefull_model_pathr+   r,   rp        z0TasksManager.get_model_files.<locals>.<listcomp>model)	repo_typer  r  r3   c                    s*   g | ]}|  r|t d  d qS )r   N)
startswithlenrn  r  )r  r+   r,   rp    s   * )repo_idr  r  r  c              	      r  r+   r  r  r  r+   r,   rp    r  )warningswarnFutureWarningr7   r   r   r   is_dirr  walkr@   rT   list_repo_filesRequestsConnectionErrorr   snapshot_download)r  r  r  r  r  r  request_exceptionhf_api	all_filesesnapshot_pathr+   )r  r  r,   get_model_files  s`   	

"



zTasksManager.get_model_filesc           
   
      s^  t j| ||||d\}}ttjttj ttjttj fdd|D }ttjttjfdd|D }t|rGd}	nIt|rNd}	nBd|v rat fdd	|D rad}	n/d
|v rhd}	n(|durst	d| t
dttj dttj dttj dttj d	t r|	pd}	nt r|	pd}	ntdtd|	 d |	S )a  
        Determines the framework to use for the export.

        The priority is in the following order:
            1. User input via `framework`.
            2. If local checkpoint is provided, use the same framework as the checkpoint.
            3. If model repo, try to infer the framework from the cache if available, else from the Hub.
            4. If could not infer, use available framework in environment, with priority given to PyTorch.

        Args:
            model_name_or_path (`Union[str, Path]`):
                Can be either the model id of a model repo on the Hugging Face Hub, or a path to a local directory
                containing a model.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the model files are located inside a subfolder of the model directory / repo on the Hugging
                Face Hub, you can specify the subfolder name here.
            revision (`Optional[str]`,  defaults to `None`):
                Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id.
            cache_dir (`Optional[str]`, *optional*):
                Path to a directory in which a downloaded pretrained model weights have been cached if the standard cache should not be used.
            token (`Optional[Union[bool,str]]`, defaults to `None`):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `huggingface-cli login` (stored in `huggingface_hub.constants.HF_TOKEN_PATH`).

        Returns:
            `str`: The framework to use for the export.

        )r  r  r  r  c                    s4   g | ]}| r| p| o|qS r+   r  endswithr  )pt_weight_extensionpt_weight_namesafe_weight_extensionsafe_weight_namer+   r,   rp  >  s
    z4TasksManager.determine_framework.<locals>.<listcomp>c                    s    g | ]}| o| qS r+   r  r  )weight_extensionweight_namer+   r,   rp  F  r  rR   rS   model_index.jsonc                 3   s    | ]
}|  fV  qd S r|  )r  r  )r  r  r+   r,   	<genexpr>L  s    
z3TasksManager.determine_framework.<locals>.<genexpr>!config_sentence_transformers.jsonNzThe framework could not be automatically inferred. If using the command-line, please provide the argument --framework (pt,tf) Detailed error: zMCannot determine framework from given checkpoint location. There should be a *z for PyTorch or z for TensorFlow.zINeither PyTorch nor TensorFlow found in environment. Cannot export model.zFramework not specified. Using z to export the model.)r^   r  r   r   stemsuffixr   r   anyr  FileNotFoundErrorr   r   EnvironmentErrorr`  info)
r  r  r  r  r  r  r  is_pt_weight_fileis_tf_weight_filerX   r+   )r  r  r  r  r  r  r,   determine_framework  sZ   %









z TasksManager.determine_frameworkr  )r!   r"   r#   rP   c                 C   s\  |d ur|d urt d|d u r|d u rt d|d ur |jjn|j}|d ur+|jjn|j}d }|dr9| j}n|drB| j}n|drJ| j}|d urn| D ]\}}t	|t
r^|f}|D ]}||krl|    S q`qRd }	|dr|dr~| j}	n| j}	n|dr| j}	|	d ur|	 D ]\}}
|
 D ]\}}||kr|    S qqt d	)
NKEither a model or a model class must be provided, but both were given here.KEither a model or a model class must be provided, but none were given here.rg   r   AutoPipeliner   TFr   The task name could not be automatically inferred. If using the command-line, please provide the argument --task task-name. Example: `--task text-classification`.)r7   	__class__rK   
__module__r  $_TRANSFORMERS_TASKS_TO_MODEL_LOADERS'_TRANSFORMERS_TASKS_TO_TF_MODEL_LOADERS!_DIFFUSERS_TASKS_TO_MODEL_LOADERSr=   r@   rT   (_TRANSFORMERS_TASKS_TO_TF_MODEL_MAPPINGS%_TRANSFORMERS_TASKS_TO_MODEL_MAPPINGS"_DIFFUSERS_TASKS_TO_MODEL_MAPPINGS)rX  r  rP   target_class_nametarget_class_moduletasks_to_model_loadersrM   rZ   model_loader_class_namerL   rN   rO   r  r+   r+   r,   %_infer_task_from_model_or_model_classk  sN   






z2TasksManager._infer_task_from_model_or_model_classc              	   C   sX  d }t jt j||}|rtddt  d|dkr$tdztt |dj	|||d}	W n t
tfyI   tddt  dw |d u rX| j|||||d	}|d
kr_d}n|dkr|	j }
}
|	j}|
d uru| |
}n|d ur|d ur|dd d ur|d d }| j D ]\}}| D ]\}}||kr|} nq|d ur nqnp|dkrd}ni|dkr|	j}
|	j}|
d ur| |	j}nS|d ur|dd }|dd }|d ur|d }
| |
}n4|d ur|dd}| j D ]#\}}t|tr|f}|D ]}||kr|} nq|d ur nq|d u r*td| d|S )NzTCannot infer the task from a local directory yet, please specify the task manually (rN  z).r3   z_Cannot infer the task from a model repo with a subfolder yet, please specify the task manually.r  )r  r  zHugging Face Hub is not reachable and we cannot infer the task from a cached model. Make sure you are not offline, or otherwise please specify the `task` (or `--task` in command-line) argument (r  r  r  r  r   ri   r   _class_namer   rf   r   pipeline_tag
auto_modelr  z2Could not find the proper task name for the model rO  )r  r  isdirrS  r}  r^   rR  r   r   
model_infor  r   infer_library_from_modelr  configrv  rQ  r  r=   transformersInfor8   r  r@   rT   rg  )rX  r  r  r  r  r  rM  inferred_task_nameis_localr  r  model_configdiffusers_class_namerM   rN   rO   r  transformers_infotransformers_pipeline_tagtransformers_auto_modelrZ   r  r+   r+   r,   #_infer_task_from_model_name_or_path  s   








z0TasksManager._infer_task_from_model_name_or_pathr!   r"   r#   c                 C   s`   d}t |tr| j||||||d}nt|tu r | j|d}n| j|d}|du r.td|S )a  
        Infers the task from the model repo, model instance, or model class.

        Args:
            model (`Union[str, PreTrainedModel, TFPreTrainedModel, DiffusionPipeline, Type]`):
                The model to infer the task from. This can either be the name of a repo on the HuggingFace Hub, an
                instance of a model, or a model class.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the model files are located inside a subfolder of the model directory / repo on the Hugging
                Face Hub, you can specify the subfolder name here.
            revision (`Optional[str]`,  defaults to `None`):
                Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id.
            cache_dir (`Optional[str]`, *optional*):
                Path to a directory in which a downloaded pretrained model weights have been cached if the standard cache should not be used.
            token (`Optional[Union[bool,str]]`, defaults to `None`):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `huggingface-cli login` (stored in `huggingface_hub.constants.HF_TOKEN_PATH`).
            library_name (`Optional[str]`, defaults to `None`):
                The library name of the model. Can be any of "transformers", "timm", "diffusers", "sentence_transformers". See `TasksManager.infer_library_from_model` for the priority should
                none be provided.
        Returns:
            `str`: The task name automatically detected from the HF hub repo, model instance, or model class.
        N)r  r  r  r  r  rM  rP   r  r  )r@   rT   r  typer  r7   )rX  r  r  r  r  r  rM  r  r+   r+   r,   infer_task_from_model  s$   !
z"TasksManager.infer_task_from_modelc                 C   s   d }|d ur|d urt d|d u r|d u rt d|d ur"|jjn|j}|dr-d}n|dr5d}n|dr=d}n|drDd}|d u rLt d|S )Nr  r  r   r   r   r   The library name could not be automatically inferred. If using the command-line, please provide the argument --library {transformers,diffusers,timm,sentence_transformers}. Example: `--library diffusers`.)r7   r  r  r  )rX  r  rP   inferred_library_namer  r+   r+   r,   (_infer_library_from_model_or_model_class0  s&   



z5TasksManager._infer_library_from_model_or_model_classc                 C   s   d}t j|||||d\}}d|v rd}nFtdd |D s"d|v r%d}n6d	|v r[||||d
}	tj|fi |	\}
}	tj|
fi |	}t|dsNt|drQd}n
t|drYd}nd}|du rctd|S )a  
        Infers the library from the model name or path.

        Args:
            model_name_or_path (`str`):
                The model to infer the task from. This can either be the name of a repo on the HuggingFace Hub, or a path
                to a local directory containing the model.
            subfolder (`str`, defaults to `""`):
                In case the model files are located inside a subfolder of the model directory / repo on the Hugging
                Face Hub, you can specify the subfolder name here.
            revision (`Optional[str]`, *optional*, defaults to `None`):
                Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id.
            cache_dir (`Optional[str]`, *optional*):
                Path to a directory in which a downloaded pretrained model weights have been cached if the standard cache should not be used.
            token (`Optional[Union[bool,str]]`, defaults to `None`):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `huggingface-cli login` (stored in `huggingface_hub.constants.HF_TOKEN_PATH`).

        Returns:
            `str`: The library name automatically detected from the model repo.
        N)r  r  r  r  r  r   c                 s   s    | ]}| d V  qdS )	sentence_N)r  )rn  	file_pathr+   r+   r,   r  z  s    zFTasksManager._infer_library_from_model_name_or_path.<locals>.<genexpr>r  r   zconfig.jsonr  pretrained_cfgarchitecturer   _diffusers_versionr   r  )r^   r  r  r   get_config_dict	from_dicthasattrr7   )rX  r  r  r  r  r  r  r  r  kwargsconfig_dictr  r+   r+   r,   &_infer_library_from_model_name_or_pathN  s@   

z3TasksManager._infer_library_from_model_name_or_pathc                 C   sN   t |tr| j|||||d}|S t|tu r| j|d}|S | j|d}|S )a  
        Infers the library from the model repo, model instance, or model class.

        Args:
            model (`Union[str, PreTrainedModel, TFPreTrainedModel, DiffusionPipeline, Type]`):
                The model to infer the task from. This can either be the name of a repo on the HuggingFace Hub, an
                instance of a model, or a model class.
            subfolder (`str`, defaults to `""`):
                In case the model files are located inside a subfolder of the model directory / repo on the Hugging
                Face Hub, you can specify the subfolder name here.
            revision (`Optional[str]`, *optional*, defaults to `None`):
                Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id.
            cache_dir (`Optional[str]`, *optional*):
                Path to a directory in which a downloaded pretrained model weights have been cached if the standard cache should not be used.
            token (`Optional[Union[bool,str]]`, defaults to `None`):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `huggingface-cli login` (stored in `huggingface_hub.constants.HF_TOKEN_PATH`).

        Returns:
            `str`: The library name automatically detected from the model repo, model instance, or model class.
        )r  r  r  r  r  r  r  )r@   rT   r  r  r  )rX  r  r  r  r  r  rM  r+   r+   r,   r    s   
z%TasksManager.infer_library_from_modelc                 C   s  |du r	t |}|dkr8d}| j D ]\}}| D ]\}}|jj|kr*|} nq|dur1 nq||j_dS |dkrLt	|j
|_|j
d |j_dS |dkrd|d jjv re|d jj|_d|j_dS d	|d jjv rz|d jj|_d
|j_dS td|d jj ddS )a>  
        Updates the model for export. This function is suitable to make required changes to the models from different
        libraries to follow transformers style.

        Args:
            model (`Union[PreTrainedModel, TFPreTrainedModel, DiffusionPipeline]`):
                The instance of the model.

        Nr   r   r  r   Transformerr   r   CLIPr   zHThe export of a sentence_transformers model with the first module being z_ is currently not supported in Optimum. Please open an issue or submit a PR to add the support.)r^   r  r  r=   r  rK   r  export_model_typer   r  r  r  r  r7   )rX  r  rM  inferred_model_typerM   rN   rO   r  r+   r+   r,   standardize_model_attributes  s8   
z)TasksManager.standardize_model_attributesc                  C   sx   g } t  rd}tj}nd}tj}g } | D ]
}| t| 7 } qtjD ]}|d |kr3| |d  q$tt	| } | S )zq
        Retrieves all the possible tasks.

        Returns:
            `List`: all the possible tasks.
        rR   rS   r   r   )
r   r^   r  r  valuesrh  ri  r  appendrx  )tasksrX   rB   dcustom_classr+   r+   r,   rR    s   
zTasksManager.get_all_taskstorch_dtypeztorch.dtypedeviceztorch.devicec
              	   K   s(  |du rt j|||||d}|	du rt j|||||d}	| }| dkr-t j||||||	d} d}d}|||d|
}|	dkrrtj|fi |}|j}|dksQ| dkr`|dkr_|jdur_|jd }n|d	ksh| d	krr|jdurr|jd }|	d
krtj	|fi |}|
dd}t|	}t||}n
t j| ||||	d}|	dkr|d| ddd}|||}n|	dkr|
dd}|
dd}|
dd}|
dd}||
d< |durtdt |durtd|}||||||||
d}nze|dkrL||d< t|trt|}n
|du rtd}ttjtdkr?|	d
kr?| |j|fi |}W d   n	1 s9w   Y  n|j|fi ||}n	|j|fi |}W n4 ty   |dkrvtd d|d< |j|fi |}ntd  d|d!< |j|fi |}Y nw t j||	d" |S )#a	  
        Retrieves a model from its name and the task to be enabled.

        Args:
            task (`str`):
                The task required.
            model_name_or_path (`Union[str, Path]`):
                Can be either the model id of a model repo on the Hugging Face Hub, or a path to a local directory
                containing a model.
            subfolder (`str`, defaults to `""`):
                In case the model files are located inside a subfolder of the model directory / repo on the Hugging
                Face Hub, you can specify the subfolder name here.
            revision (`Optional[str]`, *optional*):
                Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id.
            cache_dir (`Optional[str]`, *optional*):
                Path to a directory in which a downloaded pretrained model weights have been cached if the standard cache should not be used.
            token (`Optional[Union[bool,str]]`, defaults to `None`):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `huggingface-cli login` (stored in `huggingface_hub.constants.HF_TOKEN_PATH`).
            framework (`Optional[str]`, *optional*):
                The framework to use for the export. See `TasksManager.determine_framework` for the priority should
                none be provided.
            torch_dtype (`Optional[torch.dtype]`, defaults to `None`):
                Data type to load the model on. PyTorch-only argument.
            device (`Optional[torch.device]`, defaults to `None`):
                Device to initialize the model on. PyTorch-only argument. For PyTorch, defaults to "cpu".
            library_name (`Optional[str]`, defaults to `None`):
                The library name of the model. Can be any of "transformers", "timm", "diffusers", "sentence_transformers". See `TasksManager.infer_library_from_model` for the priority should
                none be provided.
            model_kwargs (`Dict[str, Any]`, *optional*):
                Keyword arguments to pass to the model `.from_pretrained()` method.
            library_name (`Optional[str]`, defaults to `None`):
                The library name of the model. Can be any of "transformers", "timm", "diffusers", "sentence_transformers". See `TasksManager.infer_library_from_model` for the priority should
                none be provided.

        Returns:
            The instance of the model.

        Nr  auto)r  r  r  r  rM  )r  r  r  r   rb   r   rw   r   r  )rO   r  r  r   zhf_hub:T)
pretrained
exportabler   cache_folderr  r  trust_remote_codeFr  r  r  )r  r  r  r  r  model_kwargsrR   cpuz2.0z5Loading TensorFlow model in PyTorch before exporting.from_tfz5Loading PyTorch model in TensorFlow before exporting.from_ptrL  ) r^   r  r  r  r   from_pretrainedrO   architecturesr#   load_configrQ  r>   r?   r6   r  topopr  r  r  r7   r@   rT   torchr  r   parse__version__OSErrorr`  r  r  )r/   r  r  r  r  r  rX   r  r  rM  r  original_taskrO   r  r   r  r  r  rP   r  r  r  r  r+   r+   r,   get_model_from_task  s   6

	








"



z TasksManager.get_model_from_task)r!   r"   exporter_config_kwargsc                 C   sL  |du rt d i tjtjtjtj}d}ntj| }|du r+|du r+td|du rOt	|j
dr:|j
j}nt|j
dd}|du rItdt|d|}tj|| ||d	}||vrt|}	|	D ]
}
|
|v rm|
} nqc||vrt| d
| d|  dd|  d||vrtj| }|| |  | }|durt|fi |}|S )a  
        Gets the `ExportConfigConstructor` for a model (or alternatively for a model type) and task combination.

        Args:
            exporter (`str`):
                The exporter to use.
            model (`Optional[Union[PreTrainedModel, TFPreTrainedModel]]`, defaults to `None`):
                The instance of the model.
            task (`str`, defaults to `"feature-extraction"`):
                The task to retrieve the config for.
            model_type (`Optional[str]`, defaults to `None`):
                The model type to retrieve the config for.
            model_name (`Optional[str]`, defaults to `None`):
                The name attribute of the model object, only used for the exception message.
            exporter_config_kwargs (`Optional[Dict[str, Any]]`, defaults to `None`):
                Arguments that will be passed to the exporter config class when building the config constructor.
            library_name (`Optional[str]`, defaults to `None`):
                The library name of the model. Can be any of "transformers", "timm", "diffusers", "sentence_transformers".

        Returns:
            `ExportConfigConstructor`: The `ExporterConfig` constructor for the requested backend.
        NzPassing the argument `library_name` to `get_supported_tasks_for_model_type` is required, but got library_name=None. Defaulting to `transformers`. An error will be raised in a future version of Optimum if `library_name` is not provided.r   zNEither a model_type or model should be provided to retrieve the export config.r  rO   zKModel type cannot be inferred. Please provide the model_type for the model!name)r^  rM  z doesn't support task z	 for the z backend. Supported tasks are: rN  rO  )r`  ra  r^   rb  rc  rd  re  rP  r7   r  r  r  r6   rl  r{  rS  ri  rf  r   )r]  r  r/   rO   r^  r#  rM  rT  model_tasksrz  synonymexporter_config_constructorr+   r+   r,   get_exporter_config_constructor  s\    



z,TasksManager.get_exporter_config_constructor)F)NN)rR   NNr   r|  )Nrf   NNNN)ErK   r  __qualname____doc__r  r  _TIMM_TASKS_TO_MODEL_LOADERSr  r  r  r  r  r   r]   -_SENTENCE_TRANSFORMERS_TASKS_TO_MODEL_LOADERSr   rQ   r   r  rw  r  _ENCODER_DECODER_TASKSrf  rF   rb  rc  rd  re  rP  _UNSUPPORTED_CLI_MODEL_TYPErx  ri  _SUPPORTED_CLI_MODEL_TYPEclassmethodrT   boolr   r   r   r\  staticmethodr	   TaskNameToExportConfigDictrl  r   rr  r
   r{  rv  r~  r  r   r   r   r  r  r  r  r  r  r  r  r  rR  r"  r   r   ExportConfigConstructorr(  r+   r+   r+   r,   r^      s   	"	
	


%-5?GOWbfjmsv             $  ,  4  8  =  B  F  O  U  X  ^  b  m  q  w     	                $    ,    3    :    =    A    F    N    R    V    \    b    h    l    r    z           	                        "      &      /      7      <      @      D      J      P      Y      ^      d      g      m      u      y      }               
                                %        ,        2        8        >        F        K        R        Y        _        c        g        k        p        {                   
                                                             $          '          *          -          4          7          ;          C          H          M          Q          W          [          a          f          m          s          x          {                                                                                 "            -      
      >




"6<& 
T
;
Y4W7
H-2
	
 !r^   )rR   )Dr*  r>   r  r  	functoolsr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r   huggingface_hubr   huggingface_hub.constantsr   huggingface_hub.errorsr   	packagingr   requests.exceptionsr   r  r   r   r   r   r   transformers.utilsr   r   r   r   r   utils.import_utilsr   r   baser    
get_loggerrK   r`  ra  r  r!   r"   r   r#   !diffusers.pipelines.auto_pipeliner$   r%   r&   r4  rT   r3  r-   r:   rF   rQ   r]   r^   r+   r+   r+   r,   <module>   sX   0



/
