



import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

lowercase_													=      logging.getLogger(__name__)






@dataclass
class     __a			:
	SCREAMING_SNAKE_CASE  	=							field(
	    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}					)
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "Pretrained config name or path if not the same as model_name"}					)
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}					)
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default="main"						,     metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={
	        "help": (
	            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
	            "with private models)."
	        )
	    }						,     )






@dataclass
class     __a			:
	SCREAMING_SNAKE_CASE  	=							field(default=SCREAMING_SNAKE_CASE						,     metadata={"help": "The input training data file (a text file)."}					)
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "Overwrite the cached training and evaluation sets"}					)
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={"help": "The number of processes to use for the preprocessing."}						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={
	        "help": (
	            "The maximum total input sequence length after tokenization. If passed, sequences longer "
	            "than this will be truncated, sequences shorter will be padded."
	        )
	    }						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={
	        "help": (
	            "Whether to pad all samples to the maximum sentence length. "
	            "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
	            "efficient on GPU but very bad for TPU."
	        )
	    }						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of training examples to this "
	            "value if set."
	        )
	    }						,     )
	SCREAMING_SNAKE_CASE  	=							field(
	    default=SCREAMING_SNAKE_CASE						,     metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
	            "value if set."
	        )
	    }						,     )



	def 		UpperCamelCase				(    self				:     Dict)->				Tuple:
						if self.train_file is not None:
											__lowerCAmelCase						 =self.train_file.split(""".""")[-1]
											assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
						if self.validation_file is not None:
											__lowerCAmelCase						 =self.validation_file.split(""".""")[-1]
											assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."






@dataclass
class     __a			:
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							True
	SCREAMING_SNAKE_CASE  	=							None
	SCREAMING_SNAKE_CASE  	=							None



	def __call__(    self				:     List[str]					,						snake_case_				:     Optional[Any])->				str:
						__lowerCAmelCase						 ="""label""" if """label""" in features[0].keys() else """labels"""
						__lowerCAmelCase						 =[feature.pop(snake_case_) for feature in features]
						__lowerCAmelCase						 =len(snake_case_)
						__lowerCAmelCase						 =len(features[0]["""input_ids"""])
						__lowerCAmelCase						 =[
						    [{k: v[i] for k, v in feature.items()} for i in range(snake_case_)] for feature in features
						]
						__lowerCAmelCase						 =list(chain(*snake_case_))

						__lowerCAmelCase						 =self.tokenizer.pad(
						    snake_case_					,						padding=self.padding					,						max_length=self.max_length					,						pad_to_multiple_of=self.pad_to_multiple_of					,						return_tensors="""pt"""					,						)

						# Un-flatten
						__lowerCAmelCase						 ={k: v.view(snake_case_					,						snake_case_					,						-1) for k, v in batch.items()}
						# Add back labels
						__lowerCAmelCase						 =torch.tensor(snake_case_					,						dtype=torch.intaa)
						return batch






def        __lowerCAmelCase		(	)	->    List[Any]:
					# See all possible arguments in src/transformers/training_args.py
					# or by passing the --help flag to this script.
					# We now keep distinct sets of args, for a cleaner separation of concerns.

					__lowerCAmelCase						 =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
					if len(sys.argv						) == 2 and sys.argv[1].endswith(""".json"""						):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
					else:
										__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =parser.parse_args_into_dataclasses()

					# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
					# information sent is the one passed as arguments along with your Python/PyTorch versions.
					send_example_telemetry("""run_swag"""					, __lowerCamelCase					, __lowerCamelCase						)

					# Setup logging
					logging.basicConfig(
					    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""					, datefmt="""%m/%d/%Y %H:%M:%S"""					, handlers=[logging.StreamHandler(sys.stdout						)]					, )

					if training_args.should_log:
										# The default of training_args.log_level is passive, so we set log level at info here to have that default.
										transformers.utils.logging.set_verbosity_info()

					__lowerCAmelCase						 =training_args.get_process_log_level()
					logger.setLevel(__lowerCamelCase						)
					datasets.utils.logging.set_verbosity(__lowerCamelCase						)
					transformers.utils.logging.set_verbosity(__lowerCamelCase						)
					transformers.utils.logging.enable_default_handler()
					transformers.utils.logging.enable_explicit_format()

					# Log on each process the small summary:
					logger.warning(
					    f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
					    + f"""distributed training: {bool(training_args.local_rank != -1						)}, 16-bits training: {training_args.fpaa}"""						)
					logger.info(f"""Training/evaluation parameters {training_args}"""						)

					# Detecting last checkpoint.
					__lowerCAmelCase						 =None
					if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
										__lowerCAmelCase						 =get_last_checkpoint(training_args.output_dir						)
										if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
															raise ValueError(
															    f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
															    """Use --overwrite_output_dir to overcome."""						)
										elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
															logger.info(
															    f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
															    """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""						)

    # Set seed before initializing model.
					set_seed(training_args.seed						)

					# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
					# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
					# (the dataset will be downloaded automatically from the datasets Hub).

					# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
					# 'text' is found. You can easily tweak this behavior (see below).

					# In distributed training, the load_dataset function guarantee that only one local process can concurrently
					# download the dataset.
					if data_args.train_file is not None or data_args.validation_file is not None:
										__lowerCAmelCase						 ={}
										if data_args.train_file is not None:
															__lowerCAmelCase						 =data_args.train_file
										if data_args.validation_file is not None:
															__lowerCAmelCase						 =data_args.validation_file
										__lowerCAmelCase						 =data_args.train_file.split("""."""						)[-1]
										__lowerCAmelCase						 =load_dataset(
										    __lowerCamelCase					, data_files=__lowerCamelCase					, cache_dir=model_args.cache_dir					, use_auth_token=True if model_args.use_auth_token else None					, )
					else:
										# Downloading and loading the swag dataset from the hub.
										__lowerCAmelCase						 =load_dataset(
										    """swag"""					, """regular"""					, cache_dir=model_args.cache_dir					, use_auth_token=True if model_args.use_auth_token else None					, )
					# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
					# https://huggingface.co/docs/datasets/loading_datasets.html.

					# Load pretrained model and tokenizer

					# Distributed training:
					# The .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.
					__lowerCAmelCase						 =AutoConfig.from_pretrained(
					    model_args.config_name if model_args.config_name else model_args.model_name_or_path					, cache_dir=model_args.cache_dir					, revision=model_args.model_revision					, use_auth_token=True if model_args.use_auth_token else None					, )
					__lowerCAmelCase						 =AutoTokenizer.from_pretrained(
					    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path					, cache_dir=model_args.cache_dir					, use_fast=model_args.use_fast_tokenizer					, revision=model_args.model_revision					, use_auth_token=True if model_args.use_auth_token else None					, )
					__lowerCAmelCase						 =AutoModelForMultipleChoice.from_pretrained(
					    model_args.model_name_or_path					, from_tf=bool(""".ckpt""" in model_args.model_name_or_path						)					, config=__lowerCamelCase					, cache_dir=model_args.cache_dir					, revision=model_args.model_revision					, use_auth_token=True if model_args.use_auth_token else None					, )

					# When using your own dataset or a different dataset from swag, you will probably need to change this.
					__lowerCAmelCase						 =[f"""ending{i}""" for i in range(4						)]
					__lowerCAmelCase						 ="""sent1"""
					__lowerCAmelCase						 ="""sent2"""

					if data_args.max_seq_length is None:
										__lowerCAmelCase						 =tokenizer.model_max_length
										if max_seq_length > 1024:
															logger.warning(
															    """The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value"""
															    """ of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can"""
															    """ override this default with `--block_size xxx`."""						)
															__lowerCAmelCase						 =1024
					else:
										if data_args.max_seq_length > tokenizer.model_max_length:
															logger.warning(
															    f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
															    f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""						)
										__lowerCAmelCase						 =min(data_args.max_seq_length					, tokenizer.model_max_length						)

					# Preprocessing the datasets.
					def preprocess_function(__lowerCamelCase						:     int						):
										__lowerCAmelCase						 =[[context] * 4 for context in examples[context_name]]
										__lowerCAmelCase						 =examples[question_header_name]
										__lowerCAmelCase						 =[
										    [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(__lowerCamelCase						)
										]

										# Flatten out
										__lowerCAmelCase						 =list(chain(*__lowerCamelCase						)						)
										__lowerCAmelCase						 =list(chain(*__lowerCamelCase						)						)

										# Tokenize
										__lowerCAmelCase						 =tokenizer(
										    __lowerCamelCase					, __lowerCamelCase					, truncation=__lowerCamelCase					, max_length=__lowerCamelCase					, padding="""max_length""" if data_args.pad_to_max_length else False					, )
										# Un-flatten
										return {k: [v[i : i + 4] for i in range(0					, len(__lowerCamelCase						)					, 4						)] for k, v in tokenized_examples.items()}

					if training_args.do_train:
										if "train" not in raw_datasets:
															raise ValueError("""--do_train requires a train dataset"""						)
										__lowerCAmelCase						 =raw_datasets["""train"""]
										if data_args.max_train_samples is not None:
															__lowerCAmelCase						 =min(len(__lowerCamelCase						)					, data_args.max_train_samples						)
															__lowerCAmelCase						 =train_dataset.select(range(__lowerCamelCase						)						)
										with training_args.main_process_first(desc="""train dataset map pre-processing"""						):
															__lowerCAmelCase						 =train_dataset.map(
															    __lowerCamelCase					, batched=__lowerCamelCase					, num_proc=data_args.preprocessing_num_workers					, load_from_cache_file=not data_args.overwrite_cache					, )

					if training_args.do_eval:
										if "validation" not in raw_datasets:
															raise ValueError("""--do_eval requires a validation dataset"""						)
										__lowerCAmelCase						 =raw_datasets["""validation"""]
										if data_args.max_eval_samples is not None:
															__lowerCAmelCase						 =min(len(__lowerCamelCase						)					, data_args.max_eval_samples						)
															__lowerCAmelCase						 =eval_dataset.select(range(__lowerCamelCase						)						)
										with training_args.main_process_first(desc="""validation dataset map pre-processing"""						):
															__lowerCAmelCase						 =eval_dataset.map(
															    __lowerCamelCase					, batched=__lowerCamelCase					, num_proc=data_args.preprocessing_num_workers					, load_from_cache_file=not data_args.overwrite_cache					, )

    # Data collator
					__lowerCAmelCase						 =(
					    default_data_collator
					    if data_args.pad_to_max_length
					    else DataCollatorForMultipleChoice(tokenizer=__lowerCamelCase					, pad_to_multiple_of=8 if training_args.fpaa else None						)
					)

					# Metric
					def compute_metrics(__lowerCamelCase						:     Tuple						):
										__lowerCAmelCase ,						__lowerCAmelCase						 =eval_predictions
										__lowerCAmelCase						 =np.argmax(__lowerCamelCase					, axis=1						)
										return {"accuracy": (preds == label_ids).astype(np.floataa						).mean().item()}

					# Initialize our Trainer
					__lowerCAmelCase						 =Trainer(
					    model=__lowerCamelCase					, args=__lowerCamelCase					, train_dataset=train_dataset if training_args.do_train else None					, eval_dataset=eval_dataset if training_args.do_eval else None					, tokenizer=__lowerCamelCase					, data_collator=__lowerCamelCase					, compute_metrics=__lowerCamelCase					, )

					# Training
					if training_args.do_train:
										__lowerCAmelCase						 =None
										if training_args.resume_from_checkpoint is not None:
															__lowerCAmelCase						 =training_args.resume_from_checkpoint
										elif last_checkpoint is not None:
															__lowerCAmelCase						 =last_checkpoint
										__lowerCAmelCase						 =trainer.train(resume_from_checkpoint=__lowerCamelCase						)
										trainer.save_model()  # Saves the tokenizer too for easy upload
										__lowerCAmelCase						 =train_result.metrics

										__lowerCAmelCase						 =(
										    data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCamelCase						)
										)
										__lowerCAmelCase						 =min(__lowerCamelCase					, len(__lowerCamelCase						)						)

										trainer.log_metrics("""train"""					, __lowerCamelCase						)
										trainer.save_metrics("""train"""					, __lowerCamelCase						)
										trainer.save_state()

					# Evaluation
					if training_args.do_eval:
										logger.info("""*** Evaluate ***"""						)

										__lowerCAmelCase						 =trainer.evaluate()
										__lowerCAmelCase						 =data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCamelCase						)
										__lowerCAmelCase						 =min(__lowerCamelCase					, len(__lowerCamelCase						)						)

										trainer.log_metrics("""eval"""					, __lowerCamelCase						)
										trainer.save_metrics("""eval"""					, __lowerCamelCase						)

					__lowerCAmelCase						 ={
					    """finetuned_from""": model_args.model_name_or_path,
					    """tasks""": """multiple-choice""",
					    """dataset_tags""": """swag""",
					    """dataset_args""": """regular""",
					    """dataset""": """SWAG""",
					    """language""": """en""",
					}

					if training_args.push_to_hub:
										trainer.push_to_hub(**__lowerCamelCase						)
					else:
										trainer.create_model_card(**__lowerCamelCase						)






def        __lowerCAmelCase		(	__lowerCamelCase						:     Tuple						)	->    List[Any]:
					# For xla_spawn (TPUs)
					main()


if __name__ == "__main__":
				main()









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

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


lowercase_													=      logging.get_logger(__name__)

lowercase_													=      {
    '''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''',
    # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}






class     __a			(  SCREAMING_SNAKE_CASE					):
	SCREAMING_SNAKE_CASE  	=							"gpt_neo"
	SCREAMING_SNAKE_CASE  	=							["past_key_values"]
	SCREAMING_SNAKE_CASE  	=							{"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}



	def __init__(    self				:     Optional[int]					,						snake_case_				:     int=5_02_57					,						snake_case_				:     Tuple=20_48					,						snake_case_				:     Optional[int]=20_48					,						snake_case_				:     int=24					,						snake_case_				:     List[Any]=[[["global", "local"], 12]]					,						snake_case_				:     Tuple=16					,						snake_case_				:     Optional[int]=None					,						snake_case_				:     Dict=2_56					,						snake_case_				:     List[str]="gelu_new"					,						snake_case_				:     List[Any]=0.0					,						snake_case_				:     Tuple=0.0					,						snake_case_				:     Tuple=0.0					,						snake_case_				:     str=0.1					,						snake_case_				:     Union[str, Any]=1e-5					,						snake_case_				:     str=0.0_2					,						snake_case_				:     Union[str, Any]=True					,						snake_case_				:     Optional[int]=5_02_56					,						snake_case_				:     Tuple=5_02_56					,						**snake_case_				:     Optional[int]					,						)->				Tuple:
						__lowerCAmelCase						 =vocab_size
						__lowerCAmelCase						 =max_position_embeddings
						__lowerCAmelCase						 =hidden_size
						__lowerCAmelCase						 =num_layers
						__lowerCAmelCase						 =num_heads
						__lowerCAmelCase						 =intermediate_size
						__lowerCAmelCase						 =window_size
						__lowerCAmelCase						 =activation_function
						__lowerCAmelCase						 =resid_dropout
						__lowerCAmelCase						 =embed_dropout
						__lowerCAmelCase						 =attention_dropout
						__lowerCAmelCase						 =classifier_dropout
						__lowerCAmelCase						 =layer_norm_epsilon
						__lowerCAmelCase						 =initializer_range
						__lowerCAmelCase						 =use_cache

						__lowerCAmelCase						 =bos_token_id
						__lowerCAmelCase						 =eos_token_id

						__lowerCAmelCase						 =attention_types
						__lowerCAmelCase						 =self.expand_attention_types_params(snake_case_)

						if len(self.attention_layers) != self.num_layers:
											raise ValueError(
											    """Configuration for convolutional module is incorrect. """
											    """It is required that `len(config.attention_layers)` == `config.num_layers` """
											    F"""but is `len(config.attention_layers) = {len(self.attention_layers)}`, """
											    F"""`config.num_layers = {self.num_layers}`. """
											    """`config.attention_layers` is prepared using `config.attention_types`. """
											    """Please verify the value of `config.attention_types` argument.""")

						super().__init__(bos_token_id=snake_case_					,						eos_token_id=snake_case_					,						**snake_case_)



	@staticmethod
	def 		UpperCamelCase				(    snake_case_				:     Optional[int])->				Any:
						__lowerCAmelCase						 =[]
						for item in attention_types:
											for _ in range(item[1]):
																attentions.extend(item[0])
						return attentions






def        __lowerCAmelCase		(	__lowerCamelCase						:     Any					, __lowerCamelCase						:     List[str]					, __lowerCamelCase						:     Optional[Any]					, __lowerCamelCase						:     int						)	->    int:
					import torch

					__lowerCAmelCase						 =input.size()
					__lowerCAmelCase						 =len(__lowerCamelCase						)
					__lowerCAmelCase						 =shape[dimension]

					__lowerCAmelCase						 =torch.arange(0					, __lowerCamelCase					, __lowerCamelCase						)
					__lowerCAmelCase						 =torch.div(sizedim - size					, __lowerCamelCase					, rounding_mode="""floor"""						) + 1
					__lowerCAmelCase						 =torch.arange(__lowerCamelCase						) + low_indices[:min_length][:, None]

					__lowerCAmelCase						 =[slice(__lowerCamelCase						)] * rank
					__lowerCAmelCase						 =indices
					__lowerCAmelCase						 =input[s]

					__lowerCAmelCase						 =list(range(0					, rank + 1						)						)
					perm.append(perm.pop(dimension + 1						)						)

					return sliced.permute(__lowerCamelCase						)






def        __lowerCAmelCase		(	__lowerCamelCase						:     Optional[Any]					, __lowerCamelCase						:     Any						)	->    List[str]:
					import torch

					__lowerCAmelCase						 =torch.arange(1					, __lowerCamelCase						)
					__lowerCAmelCase						 =torch.remainder(__lowerCamelCase					, __lowerCamelCase						)
					__lowerCAmelCase						 =remainders == 0
					__lowerCAmelCase						 =candidates[divisor_indices]
					__lowerCAmelCase						 =torch.max(__lowerCamelCase						)
					return largest_divisor, torch.div(__lowerCamelCase					, __lowerCamelCase					, rounding_mode="""floor"""						)






class     __a			(  SCREAMING_SNAKE_CASE					):



	@property
	def 		UpperCamelCase				(    self				:     Union[str, Any])->				Mapping[str, Mapping[int, str]]:
						__lowerCAmelCase						 =OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}})
						if self.use_past:
											self.fill_with_past_key_values_(snake_case_					,						direction="""inputs""")
											__lowerCAmelCase						 ={0: """batch""", 1: """past_sequence + sequence"""}
						else:
											__lowerCAmelCase						 ={0: """batch""", 1: """sequence"""}

						return common_inputs



	@property
	def 		UpperCamelCase				(    self				:     Optional[int])->				int:
						return self._config.num_heads



	def 		UpperCamelCase				(    self				:     int					,						snake_case_				:     PreTrainedTokenizer					,						snake_case_				:     int = -1					,						snake_case_				:     int = -1					,						snake_case_				:     bool = False					,						snake_case_				:     Optional[TensorType] = None					,						)->				Mapping[str, Any]:
						__lowerCAmelCase						 =super(snake_case_					,						self).generate_dummy_inputs(
						    snake_case_					,						batch_size=snake_case_					,						seq_length=snake_case_					,						is_pair=snake_case_					,						framework=snake_case_)

						# We need to order the input in the way they appears in the forward()
						__lowerCAmelCase						 =OrderedDict({"""input_ids""": common_inputs["""input_ids"""]})

						# Need to add the past_keys
						if self.use_past:
											if not is_torch_available():
																raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""")
											else:
																import torch

																__lowerCAmelCase ,						__lowerCAmelCase						 =common_inputs["""input_ids"""].shape
																# Not using the same length for past_key_values
																__lowerCAmelCase						 =seqlen + 2
																__lowerCAmelCase						 =(
																    batch,
																    self.num_attention_heads,
																    past_key_values_length,
																    self._config.hidden_size // self.num_attention_heads,
																)
																__lowerCAmelCase						 =[
																    (torch.zeros(snake_case_), torch.zeros(snake_case_)) for _ in range(self.num_layers)
																]

						__lowerCAmelCase						 =common_inputs["""attention_mask"""]
						if self.use_past:
											__lowerCAmelCase						 =ordered_inputs["""attention_mask"""].dtype
											__lowerCAmelCase						 =torch.cat(
											    [ordered_inputs["""attention_mask"""], torch.ones(snake_case_					,						snake_case_					,						dtype=snake_case_)]					,						dim=1)

						return ordered_inputs



	@property
	def 		UpperCamelCase				(    self				:     Union[str, Any])->				int:
						return 13




