U
    9%ehn                     @   sj  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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/m0Z0m1Z1m2Z2m3Z3m4Z4 e s.e s.e5d dde6e6ee6eegef f d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krt dt}| dD ]}t||}qi }|D ]>}d|k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)r0   r1   Z
config_cls	attr_namemappingfeaturer6    r?   Y/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/onnx/features.pysupported_features_mapping7   s    rA   c                C   @   sH  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&dddedfZ1e%dte&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)	rC   rD   rE   rF   rG   rH   rI   rK   rN   rC   rD   rG   rI   rH   rK   zmodels.albert.AlbertOnnxConfigr/   zdefault-with-pastrE   zcausal-lm-with-pastrF   zseq2seq-lm-with-pastzmodels.bart.BartOnnxConfigrL   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.DeiTOnnxConfigrJ   rM   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.RoFormerOnnxConfigrN   z$models.segformer.SegformerOnnxConfigz(models.squeezebert.SqueezeBertOnnxConfigzmodels.swin.SwinOnnxConfigzmodels.t5.T5OnnxConfigrO   z<models.vision_encoder_decoder.VisionEncoderDecoderOnnxConfigzmodels.vit.ViTOnnxConfigrP   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 rQ   )keys).0vr?   r?   r@   	<genexpr>*  s     zFeaturesManager.<genexpr>N)
model_type
model_namer2   c                 C   sX   |   } | tjk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.)lowerrB   _SUPPORTED_MODEL_TYPEKeyErrorlistrV   )rZ   r[   Zmodel_type_and_model_namer?   r?   r@   %get_supported_features_for_model_type,  s    
z5FeaturesManager.get_supported_features_for_model_type)r>   r2   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k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.rf   zOCannot export model to ONNX using PyTorch because no PyTorch package was found.rg   zUCannot export model to ONNX using TensorFlow because no TensorFlow package was found.N)r7   r   RuntimeErrorr   rc   r?   r?   r@   _validate_framework_choiceJ  s    

z*FeaturesManager._validate_framework_choicerf   )r>   rd   r2   c                 C   sX   t | }t | |dkr$t j}nt j}||k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.
        rf   zUnknown task: z. Possible values are )rB   rb   ri   _TASKS_TO_AUTOMODELS_TASKS_TO_TF_AUTOMODELSr_   r`   values)r>   rd   r6   Ztask_to_automodelr?   r?   r@   get_model_class_for_featureY  s    

z+FeaturesManager.get_model_class_for_feature)modelrd   r2   c                 C   s   |dk	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
TensorFlowre   ZtorchZtf2onnxrf   rg   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)rn   rd   Zframework_mapZexporter_mapr?   r?   r@   determine_frameworkt  s(    

z#FeaturesManager.determine_frameworkr   )r>   rn   rd   	cache_dirr2   c                 C   s   t ||}t | |}z|j||d}W nR tk
r|   |dkr^td |j|d|d}ntd |j|d|d}Y nX |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.

        )ry   rf   z=Loading TensorFlow model in PyTorch before exporting to ONNX.T)Zfrom_tfry   z=Loading PyTorch model in TensorFlow before exporting to ONNX.)Zfrom_ptry   )rB   rx   rm   Zfrom_pretrainedOSErrorru   rv   )r>   rn   rd   ry   Zmodel_classr?   r?   r@   get_model_from_feature  s    

z&FeaturesManager.get_model_from_feature)rn   r>   r2   c                 C   sd   | j jdd}t| dd}tj||d}||k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.

        _-namer5   )r[   z doesn't support feature z. Supported values are: )configrZ   r;   r:   rB   ra   r7   r^   )rn   r>   rZ   r[   Zmodel_featuresr?   r?   r@   check_supported_model_or_raise  s    z.FeaturesManager.check_supported_model_or_raise)rZ   r>   r2   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
        )rB   r^   )rZ   r>   r?   r?   r@   
get_config  s    zFeaturesManager.get_config)N)rf   )N)NN)rC   )7__name__
__module____qualname__rj   rk   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+   rA   r^   sortedr   rl   ZAVAILABLE_FEATURESstaticmethodstrr   r   r   r   r   ra   rb   ri   r	   rm   rx   r
   r{   r   r   r   r?   r?   r?   r@   rB   U   s  	  

			
			  	

			    			  

	     

      5   1         
rB   )9ro   	functoolsr   r   typingr   r   r   r   r   r	   r
   r8   r5   r   r   r   utilsr   r   r   r   r   r   r   Z
get_loggerr   ru   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   rA   rB   r?   r?   r?   r@   <module>   s0   $
D, 