o
    hn                     @   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   	with_pastfrom_model_config)r0   r1   
config_cls	attr_namemappingfeaturer6    rB   n/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/onnx/features.pysupported_features_mapping7   s   rD   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)	rF   rG   rH   rI   rJ   rK   rL   rN   rQ   albertrF   rG   rJ   rL   rK   rN   zmodels.albert.AlbertOnnxConfigr/   bartzdefault-with-pastrH   zcausal-lm-with-pastrI   zseq2seq-lm-with-pastzmodels.bart.BartOnnxConfigbeitrO   zmodels.beit.BeitOnnxConfigbertzmodels.bert.BertOnnxConfigzbig-birdz!models.big_bird.BigBirdOnnxConfigzbigbird-pegasusz/models.bigbird_pegasus.BigBirdPegasusOnnxConfig
blenderbotz&models.blenderbot.BlenderbotOnnxConfigzblenderbot-smallz1models.blenderbot_small.BlenderbotSmallOnnxConfigbloomzmodels.bloom.BloomOnnxConfig	camembertz$models.camembert.CamembertOnnxConfigclipzmodels.clip.CLIPOnnxConfigcodegenz models.codegen.CodeGenOnnxConfigconvbertz"models.convbert.ConvBertOnnxConfigconvnextz"models.convnext.ConvNextOnnxConfigzdata2vec-textz&models.data2vec.Data2VecTextOnnxConfigzdata2vec-visionz(models.data2vec.Data2VecVisionOnnxConfigdebertaz models.deberta.DebertaOnnxConfigz
deberta-v2z%models.deberta_v2.DebertaV2OnnxConfigdeitzmodels.deit.DeiTOnnxConfigdetrrM   rP   zmodels.detr.DetrOnnxConfig
distilbertz&models.distilbert.DistilBertOnnxConfigelectraz models.electra.ElectraOnnxConfigflaubertz"models.flaubert.FlaubertOnnxConfiggpt2zmodels.gpt2.GPT2OnnxConfiggptjzmodels.gptj.GPTJOnnxConfigzgpt-neozmodels.gpt_neo.GPTNeoOnnxConfiggroupvitz"models.groupvit.GroupViTOnnxConfigibertzmodels.ibert.IBertOnnxConfigimagegptz"models.imagegpt.ImageGPTOnnxConfiglayoutlmz"models.layoutlm.LayoutLMOnnxConfig
layoutlmv3z&models.layoutlmv3.LayoutLMv3OnnxConfiglevitzmodels.levit.LevitOnnxConfiglongt5zmodels.longt5.LongT5OnnxConfig
longformerz&models.longformer.LongformerOnnxConfigmarianzmodels.marian.MarianOnnxConfigmbartzmodels.mbart.MBartOnnxConfig
mobilebertz&models.mobilebert.MobileBertOnnxConfigzmobilenet-v1z)models.mobilenet_v1.MobileNetV1OnnxConfigzmobilenet-v2z)models.mobilenet_v2.MobileNetV2OnnxConfig	mobilevitz$models.mobilevit.MobileViTOnnxConfigmt5zmodels.mt5.MT5OnnxConfigzm2m-100zmodels.m2m_100.M2M100OnnxConfigowlvitzmodels.owlvit.OwlViTOnnxConfig	perceiverz$models.perceiver.PerceiverOnnxConfig
poolformerz&models.poolformer.PoolFormerOnnxConfigrembertz models.rembert.RemBertOnnxConfigresnetzmodels.resnet.ResNetOnnxConfigrobertaz models.roberta.RobertaOnnxConfigroformerz"models.roformer.RoFormerOnnxConfig	segformerrQ   z$models.segformer.SegformerOnnxConfigsqueezebertz(models.squeezebert.SqueezeBertOnnxConfigzmodels.swin.SwinOnnxConfigzmodels.t5.T5OnnxConfigrR   z<models.vision_encoder_decoder.VisionEncoderDecoderOnnxConfigzmodels.vit.ViTOnnxConfigrS   zspeech2seq-lm-with-pastz models.whisper.WhisperOnnxConfigzmodels.xlm.XLMOnnxConfigz'models.xlm_roberta.XLMRobertaOnnxConfigzmodels.yolos.YolosOnnxConfig)swint5zvision-encoder-decodervitwhisperxlmzxlm-robertayolosc                 C   s   | |B S NrB   )s1s2rB   rB   rC   <lambda>*  s    zFeaturesManager.<lambda>c                 c   s    | ]}|  V  qd S r   )keys).0vrB   rB   rC   	<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.)lowerrE   _SUPPORTED_MODEL_TYPEKeyErrorlistr   )r   r   model_type_and_model_namerB   rB   rC   %get_supported_features_for_model_type,  s   

z5FeaturesManager.get_supported_features_for_model_typerA   c                 C   s   |  ddS )Nr4   r5   )r;   )rA   rB   rB   rC   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.r   zOCannot export model to ONNX using PyTorch because no PyTorch package was found.r   zUCannot export model to ONNX using TensorFlow because no TensorFlow package was found.N)r7   r   RuntimeErrorr   )r   rB   rB   rC   _validate_framework_choiceJ  s   
z*FeaturesManager._validate_framework_choicer   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.
        r   zUnknown task: z. Possible values are )rE   r   r   _TASKS_TO_AUTOMODELS_TASKS_TO_TF_AUTOMODELSr   r   values)rA   r   r6   task_to_automodelrB   rB   rC   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.

        NPyTorch
TensorFlowr   torchtf2onnxr   r   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)r   r   framework_mapexporter_maprB   rB   rC   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.

        )r   r   z=Loading TensorFlow model in PyTorch before exporting to ONNX.T)from_tfr   z=Loading PyTorch model in TensorFlow before exporting to ONNX.)from_ptr   )rE   r   r   from_pretrainedOSErrorr   r   )rA   r   r   r   model_classrB   rB   rC   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   )r   z doesn't support feature z. Supported values are: )configr   r;   r:   rE   r   r7   r   )r   rA   r   r   model_featuresrB   rB   rC   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
        )rE   r   )r   rA   rB   rB   rC   
get_config  s   zFeaturesManager.get_configr   )r   )NN)rF   )7__name__
__module____qualname__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+   rD   r   sortedr   r   AVAILABLE_FEATURESstaticmethodstrr   r   r   r   r   r   r   r   r	   r   r   r
   r   r   r   r   rB   rB   rB   rC   rE   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 
rE   )9r   	functoolsr   r   typingr   r   r   r   r   r	   r
   r8   r5   r   r   r   utilsr   r   r   r   r   r   r   
get_loggerr   r   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   rD   rE   rB   rB   rB   rC   <module>   s6    $
D,
