



'''simple docstring'''




import argparse
import os

from . import (
    ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AlbertConfig,
    BartConfig,
    BertConfig,
    CamembertConfig,
    CTRLConfig,
    DistilBertConfig,
    DPRConfig,
    ElectraConfig,
    FlaubertConfig,
    GPTaConfig,
    LayoutLMConfig,
    LxmertConfig,
    OpenAIGPTConfig,
    RobertaConfig,
    TaConfig,
    TFAlbertForPreTraining,
    TFBartForConditionalGeneration,
    TFBartForSequenceClassification,
    TFBertForPreTraining,
    TFBertForQuestionAnswering,
    TFBertForSequenceClassification,
    TFCamembertForMaskedLM,
    TFCTRLLMHeadModel,
    TFDistilBertForMaskedLM,
    TFDistilBertForQuestionAnswering,
    TFDPRContextEncoder,
    TFDPRQuestionEncoder,
    TFDPRReader,
    TFElectraForPreTraining,
    TFFlaubertWithLMHeadModel,
    TFGPTaLMHeadModel,
    TFLayoutLMForMaskedLM,
    TFLxmertForPreTraining,
    TFLxmertVisualFeatureEncoder,
    TFOpenAIGPTLMHeadModel,
    TFRobertaForCausalLM,
    TFRobertaForMaskedLM,
    TFRobertaForSequenceClassification,
    TFTaForConditionalGeneration,
    TFTransfoXLLMHeadModel,
    TFWavaVecaModel,
    TFXLMRobertaForMaskedLM,
    TFXLMWithLMHeadModel,
    TFXLNetLMHeadModel,
    TransfoXLConfig,
    WavaVecaConfig,
    WavaVecaModel,
    XLMConfig,
    XLMRobertaConfig,
    XLNetConfig,
    is_torch_available,
    load_pytorch_checkpoint_in_tfa_model,
)
from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging


if is_torch_available():
						import numpy as np
						import torch

						from . import (
						    AlbertForPreTraining,
						    BartForConditionalGeneration,
						    BertForPreTraining,
						    BertForQuestionAnswering,
						    BertForSequenceClassification,
						    CamembertForMaskedLM,
						    CTRLLMHeadModel,
						    DistilBertForMaskedLM,
						    DistilBertForQuestionAnswering,
						    DPRContextEncoder,
						    DPRQuestionEncoder,
						    DPRReader,
						    ElectraForPreTraining,
						    FlaubertWithLMHeadModel,
						    GPTaLMHeadModel,
						    LayoutLMForMaskedLM,
						    LxmertForPreTraining,
						    LxmertVisualFeatureEncoder,
						    OpenAIGPTLMHeadModel,
						    RobertaForMaskedLM,
						    RobertaForSequenceClassification,
						    TaForConditionalGeneration,
						    TransfoXLLMHeadModel,
						    XLMRobertaForMaskedLM,
						    XLMWithLMHeadModel,
						    XLNetLMHeadModel,
						)


logging.set_verbosity_info()

lowerCamelCase							:Optional[int]       = {
    '''bart''': (
        BartConfig,
        TFBartForConditionalGeneration,
        TFBartForSequenceClassification,
        BartForConditionalGeneration,
        BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''bert''': (
        BertConfig,
        TFBertForPreTraining,
        BertForPreTraining,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-base-cased-finetuned-mrpc''': (
        BertConfig,
        TFBertForSequenceClassification,
        BertForSequenceClassification,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''dpr''': (
        DPRConfig,
        TFDPRQuestionEncoder,
        TFDPRContextEncoder,
        TFDPRReader,
        DPRQuestionEncoder,
        DPRContextEncoder,
        DPRReader,
        DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''gpt2''': (
        GPTaConfig,
        TFGPTaLMHeadModel,
        GPTaLMHeadModel,
        GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlnet''': (
        XLNetConfig,
        TFXLNetLMHeadModel,
        XLNetLMHeadModel,
        XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlm''': (
        XLMConfig,
        TFXLMWithLMHeadModel,
        XLMWithLMHeadModel,
        XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlm-roberta''': (
        XLMRobertaConfig,
        TFXLMRobertaForMaskedLM,
        XLMRobertaForMaskedLM,
        XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''transfo-xl''': (
        TransfoXLConfig,
        TFTransfoXLLMHeadModel,
        TransfoXLLMHeadModel,
        TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''openai-gpt''': (
        OpenAIGPTConfig,
        TFOpenAIGPTLMHeadModel,
        OpenAIGPTLMHeadModel,
        OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''roberta''': (
        RobertaConfig,
        TFRobertaForCausalLM,
        TFRobertaForMaskedLM,
        RobertaForMaskedLM,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''layoutlm''': (
        LayoutLMConfig,
        TFLayoutLMForMaskedLM,
        LayoutLMForMaskedLM,
        LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''roberta-large-mnli''': (
        RobertaConfig,
        TFRobertaForSequenceClassification,
        RobertaForSequenceClassification,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''camembert''': (
        CamembertConfig,
        TFCamembertForMaskedLM,
        CamembertForMaskedLM,
        CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''flaubert''': (
        FlaubertConfig,
        TFFlaubertWithLMHeadModel,
        FlaubertWithLMHeadModel,
        FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''distilbert''': (
        DistilBertConfig,
        TFDistilBertForMaskedLM,
        DistilBertForMaskedLM,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''distilbert-base-distilled-squad''': (
        DistilBertConfig,
        TFDistilBertForQuestionAnswering,
        DistilBertForQuestionAnswering,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''lxmert''': (
        LxmertConfig,
        TFLxmertForPreTraining,
        LxmertForPreTraining,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''lxmert-visual-feature-encoder''': (
        LxmertConfig,
        TFLxmertVisualFeatureEncoder,
        LxmertVisualFeatureEncoder,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''ctrl''': (
        CTRLConfig,
        TFCTRLLMHeadModel,
        CTRLLMHeadModel,
        CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''albert''': (
        AlbertConfig,
        TFAlbertForPreTraining,
        AlbertForPreTraining,
        ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''t5''': (
        TaConfig,
        TFTaForConditionalGeneration,
        TaForConditionalGeneration,
        T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''electra''': (
        ElectraConfig,
        TFElectraForPreTraining,
        ElectraForPreTraining,
        ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''wav2vec2''': (
        WavaVecaConfig,
        TFWavaVecaModel,
        WavaVecaModel,
        WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
}



def      a      (			lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__=False						,				lowerCamelCase__=True   ):
			'''simple docstring'''





			if model_type not in MODEL_CLASSES:
						raise ValueError(f'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys()   )}.'   )

			A_,   A_,   A_,   A_     :						Tuple     =					MODEL_CLASSES[model_type]

			# Initialise TF model
			if config_file in aws_config_map:
						A_     :						Tuple     =					cached_file(lowerCamelCase__						,				lowerCamelCase__						,				force_download=not use_cached_models   )
			A_     :						Dict     =					config_class.from_json_file(lowerCamelCase__   )
			A_     :						List[Any]     =					True
			A_     :						Tuple     =					True
			print(f'Building TensorFlow model from configuration: {config}'   )
			A_     :						Union[str, Any]     =					model_class(lowerCamelCase__   )

			# Load weights from tf checkpoint
			if pytorch_checkpoint_path in aws_config_map.keys():
						A_     :						List[str]     =					cached_file(
						    lowerCamelCase__						,				lowerCamelCase__						,				force_download=not use_cached_models   )
			# Load PyTorch checkpoint in tf2 model:
			A_     :						Optional[Any]     =					load_pytorch_checkpoint_in_tfa_model(lowerCamelCase__						,				lowerCamelCase__   )

			if compare_with_pt_model:
						A_     :						str     =					tf_model(tf_model.dummy_inputs						,				training=lowerCamelCase__   )  # build the network

						A_     :						List[Any]     =					torch.load(lowerCamelCase__						,				map_location="""cpu"""   )
						A_     :						List[Any]     =					pt_model_class.from_pretrained(
						    pretrained_model_name_or_path=lowerCamelCase__						,				config=lowerCamelCase__						,				state_dict=lowerCamelCase__   )

						with torch.no_grad():
									A_     :						List[Any]     =					pt_model(**pt_model.dummy_inputs   )

						A_     :						Optional[int]     =					pto[0].numpy()
						A_     :						str     =					tfo[0].numpy()
						A_     :						Union[str, Any]     =					np.amax(np.abs(np_pt - np_tf   )   )
						print(f'Max absolute difference between models outputs {diff}'   )
						assert diff <= 2E-2, f'Error, model absolute difference is >2e-2: {diff}'

			# Save pytorch-model
			print(f'Save TensorFlow model to {tf_dump_path}'   )
			tf_model.save_weights(lowerCamelCase__						,				save_format="""h5"""   )



def      a      (			lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__=None						,				lowerCamelCase__=None						,				lowerCamelCase__=False						,				lowerCamelCase__=False						,				lowerCamelCase__=False						,				lowerCamelCase__=False						,				):
			'''simple docstring'''





			if args_model_type is None:
						A_     :						List[str]     =					list(MODEL_CLASSES.keys()   )
			else:
						A_     :						Dict     =					[args_model_type]

			for j, model_type in enumerate(lowerCamelCase__						,				start=1   ):
						print("""=""" * 1_00   )
						print(f' Converting model type {j}/{len(lowerCamelCase__   )}: {model_type}'   )
						print("""=""" * 1_00   )
						if model_type not in MODEL_CLASSES:
									raise ValueError(f'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys()   )}.'   )

						A_,   A_,   A_,   A_,   A_     :						List[Any]     =					MODEL_CLASSES[model_type]

						if model_shortcut_names_or_path is None:
									A_     :						Tuple     =					list(aws_model_maps.keys()   )
						if config_shortcut_names_or_path is None:
									A_     :						int     =					model_shortcut_names_or_path

						for i, (model_shortcut_name, config_shortcut_name) in enumerate(
						    zip(lowerCamelCase__						,				lowerCamelCase__   )						,				start=1   ):
									print("""-""" * 1_00   )
									if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name:
												if not only_convert_finetuned_models:
															print(f'    Skipping finetuned checkpoint {model_shortcut_name}'   )
															continue
												A_     :						Optional[int]     =					model_shortcut_name
									elif only_convert_finetuned_models:
												print(f'    Skipping not finetuned checkpoint {model_shortcut_name}'   )
												continue
									print(
									    f'    Converting checkpoint {i}/{len(lowerCamelCase__   )}: {model_shortcut_name} - model_type {model_type}'   )
									print("""-""" * 1_00   )

									if config_shortcut_name in aws_config_map:
												A_     :						int     =					cached_file(lowerCamelCase__						,				lowerCamelCase__						,				force_download=not use_cached_models   )
									else:
												A_     :						int     =					config_shortcut_name

									if model_shortcut_name in aws_model_maps:
												A_     :						List[Any]     =					cached_file(lowerCamelCase__						,				lowerCamelCase__						,				force_download=not use_cached_models   )
									else:
												A_     :						Optional[int]     =					model_shortcut_name

									if os.path.isfile(lowerCamelCase__   ):
												A_     :						Optional[int]     =					"""converted_model"""

									convert_pt_checkpoint_to_tf(
									    model_type=lowerCamelCase__						,				pytorch_checkpoint_path=lowerCamelCase__						,				config_file=lowerCamelCase__						,				tf_dump_path=os.path.join(lowerCamelCase__						,				model_shortcut_name + """-tf_model.h5"""   )						,				compare_with_pt_model=lowerCamelCase__						,				)
									if remove_cached_files:
												os.remove(lowerCamelCase__   )
												os.remove(lowerCamelCase__   )


if __name__ == "__main__":
						lowerCamelCase							:List[str]       = argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '''--tf_dump_path''', default=None, type=str, required=True, help='''Path to the output Tensorflow dump file.'''
						)
						parser.add_argument(
						    '''--model_type''',
						    default=None,
						    type=str,
						    help=(
						        F"Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and "
						        '''convert all the models from AWS.'''
						    ),
						)
						parser.add_argument(
						    '''--pytorch_checkpoint_path''',
						    default=None,
						    type=str,
						    help=(
						        '''Path to the PyTorch checkpoint path or shortcut name to download from AWS. '''
						        '''If not given, will download and convert all the checkpoints from AWS.'''
						    ),
						)
						parser.add_argument(
						    '''--config_file''',
						    default=None,
						    type=str,
						    help=(
						        '''The config json file corresponding to the pre-trained model. \n'''
						        '''This specifies the model architecture. If not given and '''
						        '''--pytorch_checkpoint_path is not given or is a shortcut name '''
						        '''use the configuration associated to the shortcut name on the AWS'''
						    ),
						)
						parser.add_argument(
						    '''--compare_with_pt_model''', action='''store_true''', help='''Compare Tensorflow and PyTorch model predictions.'''
						)
						parser.add_argument(
						    '''--use_cached_models''',
						    action='''store_true''',
						    help='''Use cached models if possible instead of updating to latest checkpoint versions.''',
						)
						parser.add_argument(
						    '''--remove_cached_files''',
						    action='''store_true''',
						    help='''Remove pytorch models after conversion (save memory when converting in batches).''',
						)
						parser.add_argument('''--only_convert_finetuned_models''', action='''store_true''', help='''Only convert finetuned models.''')
						lowerCamelCase							:Optional[Any]       = parser.parse_args()

						# if args.pytorch_checkpoint_path is not None:
						#     convert_pt_checkpoint_to_tf(args.model_type.lower(),
						#                                 args.pytorch_checkpoint_path,
						#                                 args.config_file if args.config_file is not None else args.pytorch_checkpoint_path,
						#                                 args.tf_dump_path,
						#                                 compare_with_pt_model=args.compare_with_pt_model,
						#                                 use_cached_models=args.use_cached_models)
						# else:
						convert_all_pt_checkpoints_to_tf(
						    args.model_type.lower() if args.model_type is not None else None,
						    args.tf_dump_path,
						    model_shortcut_names_or_path=[args.pytorch_checkpoint_path]
						    if args.pytorch_checkpoint_path is not None
						    else None,
						    config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None,
						    compare_with_pt_model=args.compare_with_pt_model,
						    use_cached_models=args.use_cached_models,
						    remove_cached_files=args.remove_cached_files,
						    only_convert_finetuned_models=args.only_convert_finetuned_models,
						)




'''simple docstring'''




import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


lowerCamelCase							:Dict       = logging.get_logger(__name__)

lowerCamelCase							:Any       = {
    '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/config.json''',
    # See all BART models at https://huggingface.co/models?filter=bart
}







class      _lowerCAmelCase							(      __UpperCAmelCase			):
	__SCREAMING_SNAKE_CASE       :		List[Any]		      = 'bart'
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = ['past_key_values']
	__SCREAMING_SNAKE_CASE       :		Dict		      = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}


	def __init__(self	,				lowercase=50265	,				lowercase=1024	,				lowercase=12	,				lowercase=4096	,				lowercase=16	,				lowercase=12	,				lowercase=4096	,				lowercase=16	,				lowercase=0.0	,				lowercase=0.0	,				lowercase="gelu"	,				lowercase=1024	,				lowercase=0.1	,				lowercase=0.0	,				lowercase=0.0	,				lowercase=0.02	,				lowercase=0.0	,				lowercase=False	,				lowercase=True	,				lowercase=3	,				lowercase=1	,				lowercase=0	,				lowercase=2	,				lowercase=True	,				lowercase=2	,				lowercase=2	,				**lowercase	,				):
				A_     :						Optional[int]     =					vocab_size
				A_     :						Dict     =					max_position_embeddings
				A_     :						Dict     =					d_model
				A_     :						Any     =					encoder_ffn_dim
				A_     :						Dict     =					encoder_layers
				A_     :						Optional[int]     =					encoder_attention_heads
				A_     :						Tuple     =					decoder_ffn_dim
				A_     :						List[str]     =					decoder_layers
				A_     :						int     =					decoder_attention_heads
				A_     :						Dict     =					dropout
				A_     :						List[str]     =					attention_dropout
				A_     :						int     =					activation_dropout
				A_     :						Dict     =					activation_function
				A_     :						List[Any]     =					init_std
				A_     :						Dict     =					encoder_layerdrop
				A_     :						Tuple     =					decoder_layerdrop
				A_     :						Optional[int]     =					classifier_dropout
				A_     :						Union[str, Any]     =					use_cache
				A_     :						Dict     =					encoder_layers
				A_     :						Dict     =					scale_embedding  # scale factor will be sqrt(d_model) if True

				super().__init__(
				    num_labels=lowercase	,				pad_token_id=lowercase	,				bos_token_id=lowercase	,				eos_token_id=lowercase	,				is_encoder_decoder=lowercase	,				decoder_start_token_id=lowercase	,				forced_eos_token_id=lowercase	,				**lowercase	,				)

				# ensure backward compatibility for BART CNN models
				if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated"""	,				lowercase							):
							A_     :						List[str]     =					self.bos_token_id
							warnings.warn(
							    F'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. '
							    """The config can simply be saved and uploaded again to be fixed."""							)







class      _lowerCAmelCase							(      __UpperCAmelCase			):


	@property
	def    _a     (self							):
				if self.task in ["default", "seq2seq-lm"]:
							A_     :						List[Any]     =					OrderedDict(
							    [
							        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
							        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
							    ]							)

							if self.use_past:
										A_     :						Union[str, Any]     =					{0: """batch"""}
										A_     :						List[Any]     =					{0: """batch""", 1: """past_decoder_sequence + sequence"""}
							else:
										A_     :						Optional[int]     =					{0: """batch""", 1: """decoder_sequence"""}
										A_     :						List[str]     =					{0: """batch""", 1: """decoder_sequence"""}

							if self.use_past:
										self.fill_with_past_key_values_(lowercase	,				direction="""inputs"""							)
				elif self.task == "causal-lm":
							# TODO: figure this case out.
							A_     :						List[Any]     =					OrderedDict(
							    [
							        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
							        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
							    ]							)
							if self.use_past:
										A_,   A_     :						Optional[int]     =					self.num_layers
										for i in range(lowercase							):
													A_     :						List[str]     =					{0: """batch""", 2: """past_sequence + sequence"""}
													A_     :						List[str]     =					{0: """batch""", 2: """past_sequence + sequence"""}
				else:
							A_     :						Union[str, Any]     =					OrderedDict(
							    [
							        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
							        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
							        ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
							        ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
							    ]							)

				return common_inputs


	@property
	def    _a     (self							):
				if self.task in ["default", "seq2seq-lm"]:
							A_     :						int     =					super().outputs
				else:
							A_     :						int     =					super(lowercase	,				self							).outputs
							if self.use_past:
										A_,   A_     :						Union[str, Any]     =					self.num_layers
										for i in range(lowercase							):
													A_     :						List[str]     =					{0: """batch""", 2: """past_sequence + sequence"""}
													A_     :						Optional[int]     =					{0: """batch""", 2: """past_sequence + sequence"""}
				return common_outputs


	def    _a     (self	,				lowercase	,				lowercase = -1	,				lowercase = -1	,				lowercase = False	,				lowercase = None	,				):
				A_     :						Optional[int]     =					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase							)

				# Generate decoder inputs
				A_     :						int     =					seq_length if not self.use_past else 1
				A_     :						int     =					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase							)
				A_     :						Optional[int]     =					{F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
				A_     :						Dict     =					dict(**lowercase	,				**lowercase							)

				if self.use_past:
							if not is_torch_available():
										raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
							else:
										import torch
							A_,   A_     :						Union[str, Any]     =					common_inputs["""input_ids"""].shape
							A_     :						Optional[Any]     =					common_inputs["""decoder_input_ids"""].shape[1]
							A_,   A_     :						str     =					self.num_attention_heads
							A_     :						Tuple     =					(
							    batch,
							    num_encoder_attention_heads,
							    encoder_seq_length,
							    self._config.hidden_size // num_encoder_attention_heads,
							)
							A_     :						Tuple     =					decoder_seq_length + 3
							A_     :						Tuple     =					(
							    batch,
							    num_decoder_attention_heads,
							    decoder_past_length,
							    self._config.hidden_size // num_decoder_attention_heads,
							)

							A_     :						List[str]     =					torch.cat(
							    [common_inputs["""decoder_attention_mask"""], torch.ones(lowercase	,				lowercase							)]	,				dim=1							)

							A_     :						Union[str, Any]     =					[]
							# If the number of encoder and decoder layers are present in the model configuration, both are considered
							A_,   A_     :						Optional[int]     =					self.num_layers
							A_     :						List[Any]     =					min(lowercase	,				lowercase							)
							A_     :						Tuple     =					max(lowercase	,				lowercase							) - min_num_layers
							A_     :						List[str]     =					"""encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

							for _ in range(lowercase							):
										common_inputs["past_key_values"].append(
										    (
										        torch.zeros(lowercase							),
										        torch.zeros(lowercase							),
										        torch.zeros(lowercase							),
										        torch.zeros(lowercase							),
										    )							)
							# TODO: test this.
							A_     :						List[Any]     =					encoder_shape if remaining_side_name == """encoder""" else decoder_shape
							for _ in range(lowercase	,				lowercase							):
										common_inputs["past_key_values"].append((torch.zeros(lowercase							), torch.zeros(lowercase							))							)
				return common_inputs


	def    _a     (self	,				lowercase	,				lowercase = -1	,				lowercase = -1	,				lowercase = False	,				lowercase = None	,				):
				A_     :						Dict     =					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase							)

				if self.use_past:
							if not is_torch_available():
										raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
							else:
										import torch
							A_,   A_     :						List[str]     =					common_inputs["""input_ids"""].shape
							# Not using the same length for past_key_values
							A_     :						Optional[Any]     =					seqlen + 2
							A_,   A_     :						str     =					self.num_layers
							A_,   A_     :						Optional[int]     =					self.num_attention_heads
							A_     :						str     =					(
							    batch,
							    num_encoder_attention_heads,
							    past_key_values_length,
							    self._config.hidden_size // num_encoder_attention_heads,
							)

							A_     :						Union[str, Any]     =					common_inputs["""attention_mask"""].dtype
							A_     :						int     =					torch.cat(
							    [common_inputs["""attention_mask"""], torch.ones(lowercase	,				lowercase	,				dtype=lowercase							)]	,				dim=1							)
							A_     :						int     =					[
							    (torch.zeros(lowercase							), torch.zeros(lowercase							)) for _ in range(lowercase							)
							]
				return common_inputs


	def    _a     (self	,				lowercase	,				lowercase = -1	,				lowercase = -1	,				lowercase = False	,				lowercase = None	,				):
				# Copied from OnnxConfig.generate_dummy_inputs
				# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
				# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
				A_     :						List[Any]     =					compute_effective_axis_dimension(
				    lowercase	,				fixed_dimension=OnnxConfig.default_fixed_batch	,				num_token_to_add=0							)

				# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
				A_     :						Union[str, Any]     =					tokenizer.num_special_tokens_to_add(lowercase							)
				A_     :						List[Any]     =					compute_effective_axis_dimension(
				    lowercase	,				fixed_dimension=OnnxConfig.default_fixed_sequence	,				num_token_to_add=lowercase							)

				# Generate dummy inputs according to compute batch and sequence
				A_     :						str     =					[""" """.join([tokenizer.unk_token]							) * seq_length] * batch_size
				A_     :						Tuple     =					dict(tokenizer(lowercase	,				return_tensors=lowercase							)							)
				return common_inputs


	def    _a     (self	,				lowercase	,				lowercase = -1	,				lowercase = -1	,				lowercase = False	,				lowercase = None	,				):
				if self.task in ["default", "seq2seq-lm"]:
							A_     :						Union[str, Any]     =					self._generate_dummy_inputs_for_default_and_seqaseq_lm(
							    lowercase	,				batch_size=lowercase	,				seq_length=lowercase	,				is_pair=lowercase	,				framework=lowercase							)

				elif self.task == "causal-lm":
							A_     :						List[str]     =					self._generate_dummy_inputs_for_causal_lm(
							    lowercase	,				batch_size=lowercase	,				seq_length=lowercase	,				is_pair=lowercase	,				framework=lowercase							)
				else:
							A_     :						Optional[Any]     =					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    lowercase	,				batch_size=lowercase	,				seq_length=lowercase	,				is_pair=lowercase	,				framework=lowercase							)

				return common_inputs


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase	,				lowercase							):
				if self.task in ["default", "seq2seq-lm"]:
							A_     :						Optional[Any]     =					super()._flatten_past_key_values_(lowercase	,				lowercase	,				lowercase	,				lowercase							)
				else:
							A_     :						List[Any]     =					super(lowercase	,				self							)._flatten_past_key_values_(
							    lowercase	,				lowercase	,				lowercase	,				lowercase							)