






'''simple docstring'''







import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
_A     :      Any   					=logging.getLogger(__name__)

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

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-classification/requirements.txt''')

_A     :      Optional[int]   					=list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
_A     :      List[str]   					=tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase				)				->	List[Any]:
       with open(lowerCAmelCase_    ,      """rb"""				) as f:
              lowerCamelCase__ :     Optional[Any]	  =	Image.open(lowerCAmelCase_				)
              return im.convert("""RGB"""				)

@dataclass
class _lowercase     :
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={
               """help""": """Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."""
           }    ,				)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}		)
       a    				=	field(default=_UpperCamelCase    ,				metadata={"""help""": """A folder containing the training data."""}		)
       a    				=	field(default=_UpperCamelCase    ,				metadata={"""help""": """A folder containing the validation data."""}		)
       a    				=	field(
           default=0.15    ,				metadata={"""help""": """Percent to split off of train for validation."""}		)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={
               """help""": (
                   """For debugging purposes or quicker training, truncate the number of training examples to this """
                   """value if set."""
               )
           }    ,				)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={
               """help""": (
                   """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
                   """value if set."""
               )
           }    ,				)




       def 		lowerCamelCase_    (							self:    int					):
              if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
                     raise ValueError(
                         """You must specify either a dataset name from the hub or a train and/or validation directory."""					)



@dataclass
class _lowercase     :
       a    				=	field(
           default="""google/vit-base-patch16-224-in21k"""    ,				metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}    ,				)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(_UpperCamelCase		)}    ,				)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}		)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""}		)
       a    				=	field(
           default="""main"""    ,				metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}    ,				)
       a    				=	field(default=_UpperCamelCase    ,				metadata={"""help""": """Name or path of preprocessor config."""}		)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={
               """help""": (
                   """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
                   """with private models)."""
               )
           }    ,				)
       a    				=	field(
           default=_UpperCamelCase    ,				metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}    ,				)





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase				)				->	Dict:
       lowerCamelCase__ :     Tuple	  =	torch.stack([example["""pixel_values"""] for example in examples]				)
       lowerCamelCase__ :     Tuple	  =	torch.tensor([example["""labels"""] for example in examples]				)
       return {"pixel_values": pixel_values, "labels": labels}





def 			SCREAMING_SNAKE_CASE_	()				->	int:
       # 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__ :     Tuple	  =	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__ :     str	  =	parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
       else:
              lowerCamelCase__ :     List[str]	  =	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_image_classification"""    ,      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__ :     Optional[Any]	  =	training_args.get_process_log_level()
       logger.setLevel(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__ :     Tuple	  =	None
       if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
              lowerCamelCase__ :     Any	  =	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				)

       # Initialize our dataset and prepare it for the 'image-classification' task.
       if data_args.dataset_name is not None:
              lowerCamelCase__ :     List[Any]	  =	load_dataset(
                  data_args.dataset_name    ,      data_args.dataset_config_name    ,      cache_dir=model_args.cache_dir    ,      task="""image-classification"""    ,      use_auth_token=True if model_args.use_auth_token else None    ,      )
       else:
              lowerCamelCase__ :     Any	  =	{}
              if data_args.train_dir is not None:
                     lowerCamelCase__ :     int	  =	os.path.join(data_args.train_dir    ,      """**"""				)
              if data_args.validation_dir is not None:
                     lowerCamelCase__ :     int	  =	os.path.join(data_args.validation_dir    ,      """**"""				)
              lowerCamelCase__ :     Any	  =	load_dataset(
                  """imagefolder"""    ,      data_files=lowerCAmelCase_    ,      cache_dir=model_args.cache_dir    ,      task="""image-classification"""    ,      )

       # If we don't have a validation split, split off a percentage of train as validation.
       lowerCamelCase__ :     Any	  =	None if 'validation' in dataset.keys() else data_args.train_val_split
       if isinstance(data_args.train_val_split    ,      lowerCAmelCase_				) and data_args.train_val_split > 0.0:
              lowerCamelCase__ :     Union[str, Any]	  =	dataset['train'].train_test_split(data_args.train_val_split				)
              lowerCamelCase__ :     List[Any]	  =	split['train']
              lowerCamelCase__ :     int	  =	split['test']

       # Prepare label mappings.
       # We'll include these in the model's config to get human readable labels in the Inference API.
       lowerCamelCase__ :     Union[str, Any]	  =	dataset['train'].features['labels'].names
       lowerCamelCase__ :     Any	  =	{}, {}
       for i, label in enumerate(lowerCAmelCase_				):
              lowerCamelCase__ :     List[str]	  =	str(lowerCAmelCase_				)
              lowerCamelCase__ :     Any	  =	label

       # Load the accuracy metric from the datasets package
       lowerCamelCase__ :     List[Any]	  =	evaluate.load("""accuracy"""				)

       # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
       # predictions and label_ids field) and has to return a dictionary string to float.
       def compute_metrics(UpperCamelCase				):
              return metric.compute(predictions=np.argmax(p.predictions    ,      axis=1				)    ,      references=p.label_ids				)

       lowerCamelCase__ :     Optional[int]	  =	AutoConfig.from_pretrained(
           model_args.config_name or model_args.model_name_or_path    ,      num_labels=len(lowerCAmelCase_				)    ,      labelaid=lowerCAmelCase_    ,      idalabel=lowerCAmelCase_    ,      finetuning_task="""image-classification"""    ,      cache_dir=model_args.cache_dir    ,      revision=model_args.model_revision    ,      use_auth_token=True if model_args.use_auth_token else None    ,      )
       lowerCamelCase__ :     Optional[int]	  =	AutoModelForImageClassification.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    ,      ignore_mismatched_sizes=model_args.ignore_mismatched_sizes    ,      )
       lowerCamelCase__ :     List[Any]	  =	AutoImageProcessor.from_pretrained(
           model_args.image_processor_name or 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    ,      )

       # Define torchvision transforms to be applied to each image.
       if "shortest_edge" in image_processor.size:
              lowerCamelCase__ :     str	  =	image_processor.size['shortest_edge']
       else:
              lowerCamelCase__ :     Union[str, Any]	  =	(image_processor.size['height'], image_processor.size['width'])
       lowerCamelCase__ :     Any	  =	Normalize(mean=image_processor.image_mean    ,      std=image_processor.image_std				)
       lowerCamelCase__ :     Dict	  =	Compose(
           [
               RandomResizedCrop(lowerCAmelCase_				),
               RandomHorizontalFlip(),
               ToTensor(),
               normalize,
           ]				)
       lowerCamelCase__ :     Union[str, Any]	  =	Compose(
           [
               Resize(lowerCAmelCase_				),
               CenterCrop(lowerCAmelCase_				),
               ToTensor(),
               normalize,
           ]				)

       def train_transforms(UpperCamelCase				):
              lowerCamelCase__ :     Any	  =	[
                  _train_transforms(pil_img.convert("""RGB"""				)				) for pil_img in example_batch['image']
              ]
              return example_batch

       def val_transforms(UpperCamelCase				):
              lowerCamelCase__ :     Dict	  =	[_val_transforms(pil_img.convert("""RGB"""				)				) for pil_img in example_batch['image']]
              return example_batch

       if training_args.do_train:
              if "train" not in dataset:
                     raise ValueError("""--do_train requires a train dataset"""				)
              if data_args.max_train_samples is not None:
                     lowerCamelCase__ :     Tuple	  =	(
                         dataset['train'].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
                     )
              # Set the training transforms
              dataset["train"].set_transform(lowerCAmelCase_				)

       if training_args.do_eval:
              if "validation" not in dataset:
                     raise ValueError("""--do_eval requires a validation dataset"""				)
              if data_args.max_eval_samples is not None:
                     lowerCamelCase__ :     Any	  =	(
                         dataset['validation'].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
                     )
              # Set the validation transforms
              dataset["validation"].set_transform(lowerCAmelCase_				)

       # Initalize our trainer
       lowerCamelCase__ :     str	  =	Trainer(
           model=lowerCAmelCase_    ,      args=lowerCAmelCase_    ,      train_dataset=dataset["""train"""] if training_args.do_train else None    ,      eval_dataset=dataset["""validation"""] if training_args.do_eval else None    ,      compute_metrics=lowerCAmelCase_    ,      tokenizer=lowerCAmelCase_    ,      data_collator=lowerCAmelCase_    ,      )

       # Training
       if training_args.do_train:
              lowerCamelCase__ :     Optional[Any]	  =	None
              if training_args.resume_from_checkpoint is not None:
                     lowerCamelCase__ :     Dict	  =	training_args.resume_from_checkpoint
              elif last_checkpoint is not None:
                     lowerCamelCase__ :     Optional[Any]	  =	last_checkpoint
              lowerCamelCase__ :     Optional[Any]	  =	trainer.train(resume_from_checkpoint=lowerCAmelCase_				)
              trainer.save_model()
              trainer.log_metrics("""train"""    ,      train_result.metrics				)
              trainer.save_metrics("""train"""    ,      train_result.metrics				)
              trainer.save_state()

       # Evaluation
       if training_args.do_eval:
              lowerCamelCase__ :     List[str]	  =	trainer.evaluate()
              trainer.log_metrics("""eval"""    ,      lowerCAmelCase_				)
              trainer.save_metrics("""eval"""    ,      lowerCAmelCase_				)

       # Write model card and (optionally) push to hub
       lowerCamelCase__ :     Tuple	  =	{
           'finetuned_from': model_args.model_name_or_path,
           'tasks': 'image-classification',
           'dataset': data_args.dataset_name,
           'tags': ['image-classification', 'vision'],
       }
       if training_args.push_to_hub:
              trainer.push_to_hub(**lowerCAmelCase_				)
       else:
              trainer.create_model_card(**lowerCAmelCase_				)


if __name__ == "__main__":
   main()









'''simple docstring'''







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


_A     :      Optional[Any]   					=logging.get_logger(__name__)

_A     :      List[str]   					={
    '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''',
    # See all Marian models at https://huggingface.co/models?filter=marian
}

class _lowercase     (    _lowercase		):
							a    				=	"""marian"""
							a    				=	["""past_key_values"""]
							a    				=	{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




							def __init__(							self:    Tuple      ,							UpperCamelCase__:    Optional[Any]=58_101      ,							UpperCamelCase__:    Optional[int]=None      ,							UpperCamelCase__:    Union[str, Any]=1_024      ,							UpperCamelCase__:    Any=12      ,							UpperCamelCase__:    Optional[int]=4_096      ,							UpperCamelCase__:    Tuple=16      ,							UpperCamelCase__:    Dict=12      ,							UpperCamelCase__:    Optional[Any]=4_096      ,							UpperCamelCase__:    Any=16      ,							UpperCamelCase__:    List[str]=0.0      ,							UpperCamelCase__:    Tuple=0.0      ,							UpperCamelCase__:    str=True      ,							UpperCamelCase__:    Optional[int]=True      ,							UpperCamelCase__:    Optional[int]="gelu"      ,							UpperCamelCase__:    Union[str, Any]=1_024      ,							UpperCamelCase__:    Optional[int]=0.1      ,							UpperCamelCase__:    Optional[Any]=0.0      ,							UpperCamelCase__:    Optional[Any]=0.0      ,							UpperCamelCase__:    Optional[int]=0.02      ,							UpperCamelCase__:    str=58_100      ,							UpperCamelCase__:    Tuple=False      ,							UpperCamelCase__:    Optional[Any]=58_100      ,							UpperCamelCase__:    int=0      ,							UpperCamelCase__:    Union[str, Any]=0      ,							UpperCamelCase__:    List[str]=True      ,							**UpperCamelCase__:    str      ,							):
														lowerCamelCase__ :     int	  =	vocab_size
														lowerCamelCase__ :     Tuple	  =	decoder_vocab_size or vocab_size
														lowerCamelCase__ :     List[str]	  =	max_position_embeddings
														lowerCamelCase__ :     Optional[Any]	  =	d_model
														lowerCamelCase__ :     int	  =	encoder_ffn_dim
														lowerCamelCase__ :     Union[str, Any]	  =	encoder_layers
														lowerCamelCase__ :     Dict	  =	encoder_attention_heads
														lowerCamelCase__ :     Optional[int]	  =	decoder_ffn_dim
														lowerCamelCase__ :     List[str]	  =	decoder_layers
														lowerCamelCase__ :     Dict	  =	decoder_attention_heads
														lowerCamelCase__ :     int	  =	dropout
														lowerCamelCase__ :     str	  =	attention_dropout
														lowerCamelCase__ :     Dict	  =	activation_dropout
														lowerCamelCase__ :     List[str]	  =	activation_function
														lowerCamelCase__ :     Union[str, Any]	  =	init_std
														lowerCamelCase__ :     str	  =	encoder_layerdrop
														lowerCamelCase__ :     Any	  =	decoder_layerdrop
														lowerCamelCase__ :     List[str]	  =	use_cache
														lowerCamelCase__ :     List[str]	  =	encoder_layers
														lowerCamelCase__ :     int	  =	scale_embedding  # scale factor will be sqrt(d_model) if True
														lowerCamelCase__ :     str	  =	share_encoder_decoder_embeddings
														super().__init__(
														    pad_token_id=UpperCamelCase__      ,							eos_token_id=UpperCamelCase__      ,							is_encoder_decoder=UpperCamelCase__      ,							decoder_start_token_id=UpperCamelCase__      ,							forced_eos_token_id=UpperCamelCase__      ,							**UpperCamelCase__      ,							)



class _lowercase     (    _lowercase		):




							@property
							# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
							def 		lowerCamelCase_    (							self:    Union[str, Any]					):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     List[str]	  =	OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					    ]					)

																					if self.use_past:
																												lowerCamelCase__ :     Dict	  =	{0: """batch"""}
																												lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 1: """past_decoder_sequence + sequence"""}
																					else:
																												lowerCamelCase__ :     Any	  =	{0: """batch""", 1: """decoder_sequence"""}
																												lowerCamelCase__ :     Dict	  =	{0: """batch""", 1: """decoder_sequence"""}

																					if self.use_past:
																												self.fill_with_past_key_values_(UpperCamelCase__      ,							direction="""inputs"""					)
														elif self.task == "causal-lm":
																					# TODO: figure this case out.
																					lowerCamelCase__ :     Union[str, Any]	  =	OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					    ]					)
																					if self.use_past:
																												lowerCamelCase__  ,		lowerCamelCase__ :     Tuple	  =	self.num_layers
																												for i in range(UpperCamelCase__					):
																																			lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 2: """past_sequence + sequence"""}
																																			lowerCamelCase__ :     List[str]	  =	{0: """batch""", 2: """past_sequence + sequence"""}
														else:
																					lowerCamelCase__ :     int	  =	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
							# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     Dict	  =	super().outputs
														else:
																					lowerCamelCase__ :     Any	  =	super(UpperCamelCase__      ,							self					).outputs
																					if self.use_past:
																												lowerCamelCase__  ,		lowerCamelCase__ :     str	  =	self.num_layers
																												for i in range(UpperCamelCase__					):
																																			lowerCamelCase__ :     Tuple	  =	{0: """batch""", 2: """past_sequence + sequence"""}
																																			lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 2: """past_sequence + sequence"""}
														return common_outputs




							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														lowerCamelCase__ :     Union[str, Any]	  =	self._generate_dummy_inputs_for_encoder_and_decoder(
														    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)

														# Generate decoder inputs
														lowerCamelCase__ :     Any	  =	seq_length if not self.use_past else 1
														lowerCamelCase__ :     Optional[Any]	  =	self._generate_dummy_inputs_for_encoder_and_decoder(
														    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
														lowerCamelCase__ :     str	  =	{F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
														lowerCamelCase__ :     Optional[int]	  =	dict(**UpperCamelCase__      ,							**UpperCamelCase__					)

														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__ :     Optional[Any]	  =	common_inputs["""input_ids"""].shape
																					lowerCamelCase__ :     Tuple	  =	common_inputs["""decoder_input_ids"""].shape[1]
																					lowerCamelCase__  ,		lowerCamelCase__ :     List[str]	  =	self.num_attention_heads
																					lowerCamelCase__ :     Any	  =	(
																					    batch,
																					    num_encoder_attention_heads,
																					    encoder_seq_length,
																					    self._config.hidden_size // num_encoder_attention_heads,
																					)
																					lowerCamelCase__ :     Tuple	  =	decoder_seq_length + 3
																					lowerCamelCase__ :     int	  =	(
																					    batch,
																					    num_decoder_attention_heads,
																					    decoder_past_length,
																					    self._config.hidden_size // num_decoder_attention_heads,
																					)

																					lowerCamelCase__ :     Optional[int]	  =	torch.cat(
																					    [common_inputs["""decoder_attention_mask"""], torch.ones(UpperCamelCase__      ,							UpperCamelCase__					)]      ,							dim=1					)

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

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




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														lowerCamelCase__ :     Any	  =	self._generate_dummy_inputs_for_encoder_and_decoder(
														    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)

														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__ :     Any	  =	common_inputs["""input_ids"""].shape
																					# Not using the same length for past_key_values
																					lowerCamelCase__ :     Optional[Any]	  =	seqlen + 2
																					lowerCamelCase__  ,		lowerCamelCase__ :     Dict	  =	self.num_layers
																					lowerCamelCase__  ,		lowerCamelCase__ :     Dict	  =	self.num_attention_heads
																					lowerCamelCase__ :     Optional[Any]	  =	(
																					    batch,
																					    num_encoder_attention_heads,
																					    past_key_values_length,
																					    self._config.hidden_size // num_encoder_attention_heads,
																					)

																					lowerCamelCase__ :     Optional[Any]	  =	common_inputs["""attention_mask"""].dtype
																					lowerCamelCase__ :     int	  =	torch.cat(
																					    [common_inputs["""attention_mask"""], torch.ones(UpperCamelCase__      ,							UpperCamelCase__      ,							dtype=UpperCamelCase__					)]      ,							dim=1					)
																					lowerCamelCase__ :     int	  =	[
																					    (torch.zeros(UpperCamelCase__					), torch.zeros(UpperCamelCase__					)) for _ in range(UpperCamelCase__					)
																					]
														return common_inputs




							def 		lowerCamelCase_    (							self:    Optional[int]      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = 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
														lowerCamelCase__ :     List[Any]	  =	compute_effective_axis_dimension(
														    UpperCamelCase__      ,							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
														lowerCamelCase__ :     Union[str, Any]	  =	tokenizer.num_special_tokens_to_add(UpperCamelCase__					)
														lowerCamelCase__ :     Any	  =	compute_effective_axis_dimension(
														    UpperCamelCase__      ,							fixed_dimension=OnnxConfig.default_fixed_sequence      ,							num_token_to_add=UpperCamelCase__					)

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




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     Dict	  =	self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																					    UpperCamelCase__      ,							batch_size=UpperCamelCase__      ,							seq_length=UpperCamelCase__      ,							is_pair=UpperCamelCase__      ,							framework=UpperCamelCase__					)

														else:
																					lowerCamelCase__ :     Tuple	  =	self._generate_dummy_inputs_for_causal_lm(
																					    UpperCamelCase__      ,							batch_size=UpperCamelCase__      ,							seq_length=UpperCamelCase__      ,							is_pair=UpperCamelCase__      ,							framework=UpperCamelCase__					)

														return common_inputs




							def 		lowerCamelCase_    (							self:    Union[str, Any]      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    List[Any]      ,							UpperCamelCase__:    Dict      ,							UpperCamelCase__:    Optional[Any]					):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     Dict	  =	super()._flatten_past_key_values_(UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
														else:
																					lowerCamelCase__ :     List[Any]	  =	super(UpperCamelCase__      ,							self					)._flatten_past_key_values_(
																					    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)




							@property
							def 		lowerCamelCase_    (							self:    Union[str, Any]					):
														return 1e-4

