
    ghn                        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rd d	lmZmZ  ej        e          Z e            r"d 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5                    d           ddde6de6dee6eegef         f         fdZ7 G 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_featuresr1   returnc                 .   | t          d          t          }|                     d          D ]}t          ||          }i }|D ]O}d|v r0|                    dd          }t          |j        |          ||<   6t          |j        |          ||<   P|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)r1   r2   
config_cls	attr_namemappingfeaturer8   s          V/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/onnx/features.pysupported_features_mappingrE   7   s     >???J$**3// 4 4	Z33

G% S S7""??<44D&z';$GGGGG&z'C'RRRGGN    c                   T
   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 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/          d0 eddddd	d1          i d2 edddddd	d3          d4 eddd5          d6 edd7d8d9          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dA          dB eddddd	ddC          dD eddddddE          dF eddG          dH edddddd	dI          dJ edddK          dL edddddM          dN edd	dddO          dP edddQ          dR edddddS          dT edddd	dddU          i dV edddddddW          dX edddddddd	dY	  	        dZ edddddd	d[          d\ eddd]          d^ eddd_          d` eddda          db edddddc          dd eddddde          df eddg          dh eddddi          dj edddk          dl eddddddd	dm          dn edddo          dp eddddddd	dq          dr eddddddd	dds	  	        dt edddudv          dw edddddd	dx           edddy           edddddz           ed{d|           e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           edd7d          dZ  e! e"d d e #                                D                                 Z$e%	 dde&de'e&         de(e&e)e*ge+f         f         fd            Z,e%de&de&fd            Z-e%de&fd            Z.e%dde&de&de/fd            Z0e%dde&de&de&fd            Z1e%	 dde&de&de&de&de2d         f
d            Z3e%	 dde2d         de&de4e&e)f         fd            Z5de&de&de+fd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)	rI   rJ   rK   rL   rM   rN   rO   rQ   rT   albertrI   rJ   rM   rO   rN   rQ   zmodels.albert.AlbertOnnxConfigr0   bartzdefault-with-pastrK   zcausal-lm-with-pastrL   zseq2seq-lm-with-pastzmodels.bart.BartOnnxConfigbeitrR   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detrrP   rS   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	segformerrT   z$models.segformer.SegformerOnnxConfigsqueezebertz(models.squeezebert.SqueezeBertOnnxConfigzmodels.swin.SwinOnnxConfigzmodels.t5.T5OnnxConfigrU   z<models.vision_encoder_decoder.VisionEncoderDecoderOnnxConfigzmodels.vit.ViTOnnxConfigrV   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                     | |z  S N )s1s2s     rD   <lambda>zFeaturesManager.<lambda>*  s
    b2g rF   c              #   >   K   | ]}|                                 V  d S r   )keys).0vs     rD   	<genexpr>zFeaturesManager.<genexpr>*  s*      ?q?qQ?q?q?q?q?q?qrF   N
model_type
model_namer3   c                    |                                  } | t          j        vrM|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.)lowerrH   _SUPPORTED_MODEL_TYPEKeyErrorlistr   )r   r   model_type_and_model_names      rD   %get_supported_features_for_model_typez5FeaturesManager.get_supported_features_for_model_type,  s       %%''
_BBBJT(d:(F(F(F(F(F(FZd%, ` `_BGGIIJJ` `*4` ` `  
 4Z@@rF   rC   c                 .    |                      dd          S )Nr6   r7   )r=   )rC   s    rD   feature_to_taskzFeaturesManager.feature_to_taskF  s    |R000rF   	frameworkc                     | 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)r9   r   RuntimeErrorr   )r   s    rD   _validate_framework_choicez*FeaturesManager._validate_framework_choiceJ  s     L((mT]mmm   $'9';';pqqq$'8'8vwww rF   r   c           	      <   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 )rH   r   r   _TASKS_TO_AUTOMODELS_TASKS_TO_TF_AUTOMODELSr   r   values)rC   r   r8   task_to_automodels       rD   get_model_class_for_featurez+FeaturesManager.get_model_class_for_featureY  s     ..w77229=== / D / G(((uuu_EiEpEpErEr@s@suu   !&&rF   modelc                    ||S ddd}ddd}t           j                            |           rt           j                            t           j                            | t
                              rd}net           j                            t           j                            | t                              rd}n t          d	t
           d
t           d          t          	                    d||          d           n1t                      rd}n t                      rd}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_maps       rD   determine_frameworkz#FeaturesManager.determine_frameworkt  s^   (  (==%Y777== 	vw~~bgll5,??@@ 	 		U4D E EFF  		'>*6> >+> > >  
 KKHy!9HHHIIII!## v 		 "" v 		&'tuuubl96MbbbcccrF   	cache_dirr   c                    t                               ||          }t                               | |          }	 |                    ||          }n{# t          $ rn |dk    r3t
                              d           |                    |d|          }n2t
                              d           |                    |d|          }Y nw xY w|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.

        )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   )rH   r   r   from_pretrainedOSErrorr   r   )rC   r   r   r   model_classs        rD   get_model_from_featurez&FeaturesManager.get_model_from_feature  s    ( $77yII	%AA'9UU	^///KKEE 	^ 	^ 	^D  [\\\#33E4S\3]][\\\#33E4S\3]]	^ s   A A5CCc                 .   | j         j                            dd          }t          | dd          }t                              ||          }||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.

        _-namer7   )r   z doesn't support feature z. Supported values are: )configr   r=   r<   rH   r   r9   r   )r   rC   r   r   model_featuress        rD   check_supported_model_or_raisez.FeaturesManager.check_supported_model_or_raise  s     \,44S#>>
UFB//
(NNzfpNqq.((<*vvWvvftvv   |&(Mj(YZa(bbbrF   c                 2    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
        )rH   r   )r   rC   s     rD   
get_configzFeaturesManager.get_config  s     4Z@IIrF   r   )r   )NN)rI   )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,   rE   r   sortedr   r   AVAILABLE_FEATURESstaticmethodstrr   r   r   r   r   r   r   r   r
   r   r   r   r   r	   r   r   r   rF   rD   rH   rH   U   sp         
 --/'I$C9 ;"?$C"?8%E36 
  
"  
"//1'K$E;"A%G
#
 
#
p,,%" <
 
 
p 	**!"% 8

 

 

p, 	**-?[
 
 
-p2 	**%" 8	
 	
 	
3pF 	..%" ?	
 	
 	
GpZ 	55!"% M

 

 

[pp 	00!"D
 
 
qpB 	66!"O
 
 
CpT 	++!%":
 
 
Upf 	//%" B	
 	
 	
gpz 	**8
 
 
{pB 	-->
 
 
CpL 	..%" @
 
 
Mp^ 	.."@
 
 
_ph 	33%" D
 
 
ipz 	55" G
 
 
{pH 	--%" >
 
 
Ip pX 	00%" C
 
 
Ypj 	**-?[
 
 
kpp 	** 8	
 
 
qp| 	00%" D
 
 
}pN 	--%" >	
 	
 	
Opb 	..%" @	
 	
 	
cpv 	**!%"8
 
 
wpH 	**! %8
 
 
IpZ 	--!%=
 
 
[pj 	..@
 
 
kpr 	++%" :
 
 
spD 	..-?c
 
 
EpJ 	..%"@
 
 
KpX 	00 %"D
 
 
Ypf 	++-?]
 
 
gpl 	,,"<
 
 
mpz 	00 %"D
 
 
{p p pL 	,,"!<
 
 
Mp^ 	++!"% :

 

 

_pt 	00%" D
 
 
upF	 	22"G
 
 
G	pP	 	22"G
 
 
Q	pZ	 	//"B
 
 
[	pd	 	))"6
 
 
e	pr	 	--"=
 
 
s	p@
 	,,<
 
 
A
pH
 	//"%B	
 
 
I
pT
 	00-?g
 
 
U
pZ
 	--%" >	
 	
 	
[
pn
 	,,"<
 
 
o
px
 	--%" >	
 	
 	
y
pL 	..%" "@

 

 

Mpb 	//"#B	
 
 
cpn 	11%" F
 
 
op p@ +*-?[
 
 
 )("4
 
 
 #="<-k#
 #
 #
 *)-?Y
 
 
 .-%>
 
 
 *)%" 6	
 	
 	
 21%" E	
 	
 	
 ,+:
 
 
Wp p pd  '='=?q?qRgRnRnRpRp?q?q?q r rss59A AA%-c]A	c8-.
:;;	<A A A \A2 1 1 1 1 1 \1 xc x x x \x ' 'S 'S 'D ' ' ' \'4 / /3 /3 /# / / / \/b JN  -0DG	5	6   \@ MVc c;<cGJc	sH}	c c c \c0Js JS JZ J J J J J JrF   rH   )9r   	functoolsr   r   typingr   r   r   r   r	   r
   r   r:   r7   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   rE   rH   r   rF   rD   <module>r      s   				 % % % % % % % % N N N N N N N N N N N N N N N N N N     D D D D D D D D D D ; ; ; ; ; ; ; ; ; ;        @???????? 
	H	%	%                                  " ? 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  OO$5$5 
NN	5   6:  /2	#x)*J67
78   <X
J X
J X
J X
J X
J X
J X
J X
J X
J X
JrF   