o
    Zhn                     @   sl  d dl Z d dlmZmZ d dlmZmZmZ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rFd d	lmZmZ eeZe rpd 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 rd dlm,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 e se se5d ddde6dee6 dee6eegef f fddZ7G dd dZ8dS )    N)partialreduce)TYPE_CHECKINGCallableDictOptionalTupleType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_featuresr0   returnc                 G   sz   | du rt dt}| dD ]}t||}qi }|D ]}d|v r1|dd}t|j|d||< qt|j|d||< q|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)r0   r1   Z
config_clsZ	attr_namemappingfeaturer6    r>   I/var/www/auris/lib/python3.10/site-packages/transformers/onnx/features.pysupported_features_mapping7   s   r@   c                   @   sP  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 r,eeeeeeeeed	Zi dedddddd	d
ddedddddddd	dd	de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ddedd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 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&eddd'dd(edddddd	d)dd*eddd+dd,edddddd	d-dd.eddd/dd0eddddd	d1di d2edddddd	d3dd4eddd5dd6edd7d8d9d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?dd@edddddddAddBeddddd	ddCddDeddddddEddFeddGddHedddddd	dIddJedddKddLedddddMddNedd	dddOddPedddQddRedddddSddTedddd	dddUdi dVedddddddWddXedddddddd	dYd	dZedddddd	d[dd\eddd]dd^eddd_dd`edddaddbedddddcdddedddddeddfeddgddheddddiddjedddkddleddddddd	dmddnedddoddpeddddddd	dqddreddddddd	ddsd	dtedddudvddwedddddd	dxdedddydedddddzded{d|deddd}deddd~dddeddddddd	ddeddddddd	ddedd7dddZ e!e"dd dd e # D Z$e%	dde&de'e& de(e&e)e*ge+f f fddZ,e%de&de&fddZ-e%de&fddZ.e%dde&de&de/fddZ0e%dde&de'e& de&fddZ1e%	dde&de&de'e& de'e& de2d f
ddZ3e%	dde2d de&de4e&e)f fddZ5de&de&de+fddZ6dS )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)	rB   rC   rD   rE   rF   rG   rH   rJ   rM   ZalbertrB   rC   rF   rH   rG   rJ   zmodels.albert.AlbertOnnxConfigr/   Zbartzdefault-with-pastrD   zcausal-lm-with-pastrE   zseq2seq-lm-with-pastzmodels.bart.BartOnnxConfigZbeitrK   zmodels.beit.BeitOnnxConfigZbertzmodels.bert.BertOnnxConfigzbig-birdz!models.big_bird.BigBirdOnnxConfigzbigbird-pegasusz/models.bigbird_pegasus.BigBirdPegasusOnnxConfigZ
blenderbotz&models.blenderbot.BlenderbotOnnxConfigzblenderbot-smallz1models.blenderbot_small.BlenderbotSmallOnnxConfigZbloomzmodels.bloom.BloomOnnxConfigZ	camembertz$models.camembert.CamembertOnnxConfigZclipzmodels.clip.CLIPOnnxConfigZcodegenz models.codegen.CodeGenOnnxConfigZconvbertz"models.convbert.ConvBertOnnxConfigZconvnextz"models.convnext.ConvNextOnnxConfigzdata2vec-textz&models.data2vec.Data2VecTextOnnxConfigzdata2vec-visionz(models.data2vec.Data2VecVisionOnnxConfigZdebertaz models.deberta.DebertaOnnxConfigz
deberta-v2z%models.deberta_v2.DebertaV2OnnxConfigZdeitzmodels.deit.DeiTOnnxConfigZdetrrI   rL   zmodels.detr.DetrOnnxConfigZ
distilbertz&models.distilbert.DistilBertOnnxConfigZelectraz models.electra.ElectraOnnxConfigZflaubertz"models.flaubert.FlaubertOnnxConfigZgpt2zmodels.gpt2.GPT2OnnxConfigZgptjzmodels.gptj.GPTJOnnxConfigzgpt-neozmodels.gpt_neo.GPTNeoOnnxConfigZgroupvitz"models.groupvit.GroupViTOnnxConfigZibertzmodels.ibert.IBertOnnxConfigZimagegptz"models.imagegpt.ImageGPTOnnxConfigZlayoutlmz"models.layoutlm.LayoutLMOnnxConfigZ
layoutlmv3z&models.layoutlmv3.LayoutLMv3OnnxConfigZlevitzmodels.levit.LevitOnnxConfigZlongt5zmodels.longt5.LongT5OnnxConfigZ
longformerz&models.longformer.LongformerOnnxConfigZmarianzmodels.marian.MarianOnnxConfigZmbartzmodels.mbart.MBartOnnxConfigZ
mobilebertz&models.mobilebert.MobileBertOnnxConfigzmobilenet-v1z)models.mobilenet_v1.MobileNetV1OnnxConfigzmobilenet-v2z)models.mobilenet_v2.MobileNetV2OnnxConfigZ	mobilevitz$models.mobilevit.MobileViTOnnxConfigZmt5zmodels.mt5.MT5OnnxConfigzm2m-100zmodels.m2m_100.M2M100OnnxConfigZowlvitzmodels.owlvit.OwlViTOnnxConfigZ	perceiverz$models.perceiver.PerceiverOnnxConfigZ
poolformerz&models.poolformer.PoolFormerOnnxConfigZrembertz models.rembert.RemBertOnnxConfigZresnetzmodels.resnet.ResNetOnnxConfigZrobertaz models.roberta.RobertaOnnxConfigZroformerz"models.roformer.RoFormerOnnxConfigZ	segformerrM   z$models.segformer.SegformerOnnxConfigZsqueezebertz(models.squeezebert.SqueezeBertOnnxConfigzmodels.swin.SwinOnnxConfigzmodels.t5.T5OnnxConfigrN   z<models.vision_encoder_decoder.VisionEncoderDecoderOnnxConfigzmodels.vit.ViTOnnxConfigrO   zspeech2seq-lm-with-pastz models.whisper.WhisperOnnxConfigzmodels.xlm.XLMOnnxConfigz'models.xlm_roberta.XLMRobertaOnnxConfigzmodels.yolos.YolosOnnxConfig)ZswinZt5zvision-encoder-decoderZvitZwhisperZxlmzxlm-robertaZyolosc                 C   s   | |B S Nr>   )s1s2r>   r>   r?   <lambda>*  s    zFeaturesManager.<lambda>c                 c   s    | ]}|  V  qd S rP   )keys).0vr>   r>   r?   	<genexpr>*  s    zFeaturesManager.<genexpr>N
model_type
model_namer2   c                 C   sX   |   } | tjvr'|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.)lowerrA   _SUPPORTED_MODEL_TYPEKeyErrorlistrT   )rX   rY   Zmodel_type_and_model_namer>   r>   r?   %get_supported_features_for_model_type,  s   

z5FeaturesManager.get_supported_features_for_model_typer=   c                 C   s   |  ddS )Nr4   r5   )r;   )r=   r>   r>   r?   feature_to_taskF  s   zFeaturesManager.feature_to_task	frameworkc                 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.
        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)r7   r   RuntimeErrorr   )ra   r>   r>   r?   _validate_framework_choiceJ  s   
z*FeaturesManager._validate_framework_choicerc   c                 C   sX   t | }t | |dkrt j}nt j}||vr(t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 )rA   r`   rf   _TASKS_TO_AUTOMODELS_TASKS_TO_TF_AUTOMODELSr]   r^   values)r=   ra   r6   Ztask_to_automodelr>   r>   r?   get_model_class_for_featureY  s   

z+FeaturesManager.get_model_class_for_featuremodelc                 C   s   |dur|S ddd}ddd}t j| rIt jt j| tr$d}nt jt j| tr2d}ntd	t d
t dt	d||  d nt
 rOd}n
t rUd}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   EnvironmentError)rk   ra   Zframework_mapZexporter_mapr>   r>   r?   determine_frameworkt  s0   

z#FeaturesManager.determine_framework	cache_dirr   c                 C   s   t ||}t | |}z
|j||d}W |S  tyA   |dkr1td |j|d|d}Y |S td |j|d|d}Y |S w )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   )rA   ru   rj   Zfrom_pretrainedOSErrorrr   rs   )r=   rk   ra   rv   Zmodel_classr>   r>   r?   get_model_from_feature  s   

z&FeaturesManager.get_model_from_featurec                 C   sd   | j jdd}t| dd}tj||d}||vr't| 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.

        _-namer5   )rY   z doesn't support feature z. Supported values are: )configrX   r;   r:   rA   r_   r7   r\   )rk   r=   rX   rY   Zmodel_featuresr>   r>   r?   check_supported_model_or_raise  s   z.FeaturesManager.check_supported_model_or_raisec                 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
        )rA   r\   )rX   r=   r>   r>   r?   
get_config  s   zFeaturesManager.get_configrP   )rc   )NN)rB   )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   r   r   r   r   r_   r`   rf   r	   rj   ru   r
   rx   r   r}   r~   r>   r>   r>   r?   rA   U   s4   
#-8AJS]afot}           (  2  <  E  N  V  Z  c  f  m  t  w  ~               %    *    /    4    ;    B    F    L    O    Y    ^    h    s    y     

       51 
rA   )9rl   	functoolsr   r   typingr   r   r   r   r   r	   r
   r8   r5   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@   rA   r>   r>   r>   r?   <module>   s6    $
D,
