a
    htn                     @   sb  d dl Z d dlmZmZ d dlmZmZmZmZ d dl	Z	ddl
mZmZmZ ddlmZmZmZ ddlmZ erd d	l	mZmZ eeZe rd d
lmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( e rd dlm)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 e s"e s"e2d dde3ee3 e4e3eegef f dddZ5G dd dZ6dS )    N)partialreduce)TYPE_CHECKINGCallableOptionalUnion   )PretrainedConfigis_tf_availableis_torch_available)TF2_WEIGHTS_NAMEWEIGHTS_NAMElogging   )
OnnxConfigPreTrainedModelTFPreTrainedModel)	AutoModelAutoModelForCausalLMAutoModelForImageClassificationAutoModelForImageSegmentationAutoModelForMaskedImageModelingAutoModelForMaskedLMAutoModelForMultipleChoiceAutoModelForObjectDetectionAutoModelForQuestionAnswering AutoModelForSemanticSegmentationAutoModelForSeq2SeqLM"AutoModelForSequenceClassificationAutoModelForSpeechSeq2SeqAutoModelForTokenClassificationAutoModelForVision2Seq)	TFAutoModelTFAutoModelForCausalLMTFAutoModelForMaskedLMTFAutoModelForMultipleChoiceTFAutoModelForQuestionAnswering"TFAutoModelForSemanticSegmentationTFAutoModelForSeq2SeqLM$TFAutoModelForSequenceClassification!TFAutoModelForTokenClassificationzThe ONNX export features are only supported for PyTorch or TensorFlow. You will not be able to export models without one of these libraries installed.onnx_config_cls)supported_featuresr-   returnc                 G   sz   | du rt dt}| dD ]}t||}qi }|D ]>}d|v rb|dd}t|j|d||< q6t|j|d||< q6|S )ac  
    Generate the mapping between supported the features and their corresponding OnnxConfig for a given model.

    Args:
        *supported_features: The names of the supported features.
        onnx_config_cls: The OnnxConfig full name corresponding to the model.

    Returns:
        The dictionary mapping a feature to an OnnxConfig constructor.
    Nz#A OnnxConfig class must be provided.
-with-past )task)
ValueErrortransformerssplitgetattrreplacer   Z	with_pastZfrom_model_config)r-   r.   Z
config_cls	attr_namemappingfeaturer3    r<   V/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/onnx/features.pysupported_features_mapping7   s    r>   c                C   @   sT  e Zd Zi Zi Ze r:eeee	e
eeeeeeeeeedZe rXeeeeeeeeed	Zeddddddd	d
edddddddddd
	edddd
eddddddddd
eddddddddd
edddddddddd
	edddddddd
edddddddd
edddddddd
eddddddddd
eddd
edddd
edddddddd
edddd
edddddddd
edddd
edddddd d
eddddddd!d
eddd"d
edd#d$d%d
eddddddd&d
edddddddd'd
edddddddd(d
eddddddd)d
eddddddd*d
edddddd+d
edd,d
eddddddd-d
eddd.d
eddddd/d
eddddd0d
eddd1d
eddddd2d
eddddddd3d
eddddddd4d
eddddddddd5d
	eddddddd6d
eddd7d
eddd8d
eddd9d
eddddd:d
eddddd;d
edd<d
edddd=d
eddd>d
edddddddd?d
eddd@d
eddddddddAd
edddddddddBd
	edddCdDd
edddddddEd
edddFd
edddddGd
edHdId
edddJd
edddKdLdMd
eddddddddNd
eddddddddOd
edd#dPd
dQ;Z e!e"dRdS dTdU e # D Z$e%dqe&e'e& e(e&e)e*ge+f f dWdXdYZ,e%e&e&dZd[d\Z-e%e&d]d^d_Z.e%dre&e&e/dadbdcZ0e%dse&e'e& e&dddedfZ1e%dte&e&e'e& e'e& e2dg dhdidjZ3e%due2dg e&e4e&e)f dkdldmZ5e&e&e+dndodpZ6dVS )vFeaturesManager)default	masked-lm	causal-lm
seq2seq-lmsequence-classificationtoken-classificationmultiple-choiceobject-detectionquestion-answeringimage-classificationimage-segmentationz	masked-imsemantic-segmentationvision2seq-lmspeech2seq-lm)	r@   rA   rB   rC   rD   rE   rF   rH   rK   r@   rA   rD   rF   rE   rH   zmodels.albert.AlbertOnnxConfigr,   zdefault-with-pastrB   zcausal-lm-with-pastrC   zseq2seq-lm-with-pastzmodels.bart.BartOnnxConfigrI   zmodels.beit.BeitOnnxConfigzmodels.bert.BertOnnxConfigz!models.big_bird.BigBirdOnnxConfigz/models.bigbird_pegasus.BigBirdPegasusOnnxConfigz&models.blenderbot.BlenderbotOnnxConfigz1models.blenderbot_small.BlenderbotSmallOnnxConfigzmodels.bloom.BloomOnnxConfigz$models.camembert.CamembertOnnxConfigzmodels.clip.CLIPOnnxConfigz models.codegen.CodeGenOnnxConfigz"models.convbert.ConvBertOnnxConfigz"models.convnext.ConvNextOnnxConfigz&models.data2vec.Data2VecTextOnnxConfigz(models.data2vec.Data2VecVisionOnnxConfigz models.deberta.DebertaOnnxConfigz%models.deberta_v2.DebertaV2OnnxConfigzmodels.deit.DeiTOnnxConfigrG   rJ   zmodels.detr.DetrOnnxConfigz&models.distilbert.DistilBertOnnxConfigz models.electra.ElectraOnnxConfigz"models.flaubert.FlaubertOnnxConfigzmodels.gpt2.GPT2OnnxConfigzmodels.gptj.GPTJOnnxConfigzmodels.gpt_neo.GPTNeoOnnxConfigz"models.groupvit.GroupViTOnnxConfigzmodels.ibert.IBertOnnxConfigz"models.imagegpt.ImageGPTOnnxConfigz"models.layoutlm.LayoutLMOnnxConfigz&models.layoutlmv3.LayoutLMv3OnnxConfigzmodels.levit.LevitOnnxConfigzmodels.longt5.LongT5OnnxConfigz&models.longformer.LongformerOnnxConfigzmodels.marian.MarianOnnxConfigzmodels.mbart.MBartOnnxConfigz&models.mobilebert.MobileBertOnnxConfigz)models.mobilenet_v1.MobileNetV1OnnxConfigz)models.mobilenet_v2.MobileNetV2OnnxConfigz$models.mobilevit.MobileViTOnnxConfigzmodels.mt5.MT5OnnxConfigzmodels.m2m_100.M2M100OnnxConfigzmodels.owlvit.OwlViTOnnxConfigz$models.perceiver.PerceiverOnnxConfigz&models.poolformer.PoolFormerOnnxConfigz models.rembert.RemBertOnnxConfigzmodels.resnet.ResNetOnnxConfigz models.roberta.RobertaOnnxConfigz"models.roformer.RoFormerOnnxConfigrK   z$models.segformer.SegformerOnnxConfigz(models.squeezebert.SqueezeBertOnnxConfigzmodels.swin.SwinOnnxConfigzmodels.t5.T5OnnxConfigrL   z<models.vision_encoder_decoder.VisionEncoderDecoderOnnxConfigzmodels.vit.ViTOnnxConfigrM   zspeech2seq-lm-with-pastz models.whisper.WhisperOnnxConfigzmodels.xlm.XLMOnnxConfigz'models.xlm_roberta.XLMRobertaOnnxConfigzmodels.yolos.YolosOnnxConfig);ZalbertZbartZbeitZbertzbig-birdzbigbird-pegasusZ
blenderbotzblenderbot-smallZbloomZ	camembertZclipZcodegenZconvbertZconvnextzdata2vec-textzdata2vec-visionZdebertaz
deberta-v2ZdeitZdetrZ
distilbertZelectraZflaubertZgpt2Zgptjzgpt-neoZgroupvitZibertZimagegptZlayoutlmZ
layoutlmv3ZlevitZlongt5Z
longformerZmarianZmbartZ
mobilebertzmobilenet-v1zmobilenet-v2Z	mobilevitZmt5zm2m-100ZowlvitZ	perceiverZ
poolformerZrembertZresnetZrobertaZroformerZ	segformerZsqueezebertZswinZt5zvision-encoder-decoderZvitZwhisperZxlmzxlm-robertaZyolosc                 C   s   | |B S Nr<   )s1s2r<   r<   r=   <lambda>*      zFeaturesManager.<lambda>c                 c   s   | ]}|  V  qd S rN   )keys).0vr<   r<   r=   	<genexpr>*  rR   zFeaturesManager.<genexpr>N)
model_type
model_namer/   c                 C   sX   |   } | tjvrN|r&|  d| dn| }t| dttj  d|  dtj|  S )a  
        Tries to retrieve the feature -> OnnxConfig constructor map from the model type.

        Args:
            model_type (`str`):
                The model type to retrieve the supported features for.
            model_name (`str`, *optional*):
                The name attribute of the model object, only used for the exception message.

        Returns:
            The dictionary mapping each feature to a corresponding OnnxConfig constructor.
        z ()z is not supported yet. Only z' are supported. If you want to support z) please propose a PR or open up an issue.)lowerr?   _SUPPORTED_MODEL_TYPEKeyErrorlistrS   )rW   rX   Zmodel_type_and_model_namer<   r<   r=   %get_supported_features_for_model_type,  s    
z5FeaturesManager.get_supported_features_for_model_type)r;   r/   c                 C   s   |  ddS )Nr1   r2   )r8   )r;   r<   r<   r=   feature_to_taskF  s    zFeaturesManager.feature_to_task	frameworkc                 C   sL   | dvrt d|  dn.| dkr2t s2tdn| dkrHt sHtddS )	z
        Validates if the framework requested for the export is both correct and available, otherwise throws an
        exception.
        pttfzAOnly two frameworks are supported for ONNX export: pt or tf, but z was provided.rc   zOCannot export model to ONNX using PyTorch because no PyTorch package was found.rd   zUCannot export model to ONNX using TensorFlow because no TensorFlow package was found.N)r4   r   RuntimeErrorr
   r`   r<   r<   r=   _validate_framework_choiceJ  s    

z*FeaturesManager._validate_framework_choicerc   )r;   ra   r/   c                 C   sX   t | }t | |dkr$t j}nt j}||vrPtd|  dtt j  || S )ad  
        Attempts to retrieve an AutoModel class from a feature name.

        Args:
            feature (`str`):
                The feature required.
            framework (`str`, *optional*, defaults to `"pt"`):
                The framework to use for the export.

        Returns:
            The AutoModel class corresponding to the feature.
        rc   zUnknown task: z. Possible values are )r?   r_   rf   _TASKS_TO_AUTOMODELS_TASKS_TO_TF_AUTOMODELSr\   r]   values)r;   ra   r3   Ztask_to_automodelr<   r<   r=   get_model_class_for_featureY  s    

z+FeaturesManager.get_model_class_for_feature)modelra   r/   c                 C   s   |dur|S ddd}ddd}t j| rt jt j| trHd}n2t jt j| trdd}ntd	t d
t dt	d||  d n t
 rd}nt rd}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. Available framework in environment, with priority given to PyTorch

        Args:
            model (`str`):
                The name of the model to export.
            framework (`str`, *optional*, defaults to `None`):
                The framework to use for the export. See above for priority if none provided.

        Returns:
            The framework to use for the export.

        NZPyTorchZ
TensorFlowrb   ZtorchZtf2onnxrc   rd   zMCannot determine framework from given checkpoint location. There should be a z for PyTorch or z for TensorFlow.zLocal z model found.zKNeither PyTorch nor TensorFlow found in environment. Cannot export to ONNX.zFramework not requested. Using z to export to ONNX.)ospathisdirisfilejoinr   r   FileNotFoundErrorloggerinfor   r
   OSError)rk   ra   Zframework_mapZexporter_mapr<   r<   r=   determine_frameworkt  s0    

z#FeaturesManager.determine_frameworkr   )r;   rk   ra   	cache_dirr/   c                 C   s   t ||}t | |}z|j||d}W nP tyz   |dkr\td |j|d|d}ntd |j|d|d}Y n0 |S )a  
        Attempts to retrieve a model from a model's name and the feature to be enabled.

        Args:
            feature (`str`):
                The feature required.
            model (`str`):
                The name of the model to export.
            framework (`str`, *optional*, defaults to `None`):
                The framework to use for the export. See `FeaturesManager.determine_framework` for the priority should
                none be provided.

        Returns:
            The instance of the model.

        )rv   rc   z=Loading TensorFlow model in PyTorch before exporting to ONNX.T)Zfrom_tfrv   z=Loading PyTorch model in TensorFlow before exporting to ONNX.)Zfrom_ptrv   )r?   ru   rj   Zfrom_pretrainedrt   rr   rs   )r;   rk   ra   rv   Zmodel_classr<   r<   r=   get_model_from_feature  s    

z&FeaturesManager.get_model_from_feature)rk   r;   r/   c                 C   sd   | j jdd}t| dd}tj||d}||vrNt| j j d| d| | j jtj| | fS )aR  
        Check whether or not the model has the requested features.

        Args:
            model: The model to export.
            feature: The name of the feature to check if it is available.

        Returns:
            (str) The type of the model (OnnxConfig) The OnnxConfig instance holding the model export properties.

        _-namer2   )rX   z doesn't support feature z. Supported values are: )configrW   r8   r7   r?   r^   r4   r[   )rk   r;   rW   rX   Zmodel_featuresr<   r<   r=   check_supported_model_or_raise  s    z.FeaturesManager.check_supported_model_or_raise)rW   r;   r/   c                 C   s   t j|  | S )aU  
        Gets the OnnxConfig for a model_type and feature combination.

        Args:
            model_type (`str`):
                The model type to retrieve the config for.
            feature (`str`):
                The feature to retrieve the config for.

        Returns:
            `OnnxConfig`: config for the combination
        )r?   r[   )rW   r;   r<   r<   r=   
get_config  s    zFeaturesManager.get_config)N)rc   )N)NN)r@   )7__name__
__module____qualname__rg   rh   r   r   r   r   r   r   r!   r   r   r   r   r   r   r   r"   r    r
   r#   r%   r$   r)   r*   r+   r&   r'   r(   r>   r[   sortedr   ri   ZAVAILABLE_FEATURESstaticmethodstrr   dictr   r	   r   r^   r_   rf   typerj   ru   r   rw   tupler|   r}   r<   r<   r<   r=   r?   U   s  	

			
				

						

	

      5  1   
r?   )7rl   	functoolsr   r   typingr   r   r   r   r5   r2   r	   r
   r   utilsr   r   r   r{   r   r   r   Z
get_loggerr~   rr   Ztransformers.models.autor   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   warningr   r   r>   r?   r<   r<   r<   r=   <module>   s.   
D,