"""simple docstring"""




import argparse
import glob
import inspect
import os
import re
import unittest

from get_test_info import get_test_classes

from tests.test_pipeline_mixin import pipeline_test_mapping


__lowerCamelCase									=	{}
for task, _ in pipeline_test_mapping.items():
				__lowerCamelCase									=	{"pt": None, "tf": None}


# DO **NOT** add item to this set (unless the reason is approved)
__lowerCamelCase									=	{
    "tests/models/esm/test_modeling_esmfold.py",  # The pipeline test mapping is added to `test_modeling_esm.py`
}






def 	UpperCAmelCase       (						UpperCamelCase__					):






							"""simple docstring"""





							if "ModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
														return "pt"
							elif "TFModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
														return "tf"
							elif "FlaxModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
														return "flax"
							else:
														return None






def 	UpperCAmelCase       (						UpperCamelCase__							,     UpperCamelCase__					):






							"""simple docstring"""





							if PIPELINE_TEST_MAPPING[task].get(UpperCamelCase__							,     UpperCamelCase__					) is not None:
														return PIPELINE_TEST_MAPPING[task][framework]

							A__						  =				pipeline_test_mapping[task]['test']
							A__						  =				None

							if framework == "pt":
														A__						  =				getattr(UpperCamelCase__							,     'model_mapping'							,     UpperCamelCase__					)
							elif framework == "tf":
														A__						  =				getattr(UpperCamelCase__							,     'tf_model_mapping'							,     UpperCamelCase__					)

							if mapping is not None:
														A__						  =				dict(mapping.items()					)

							# cache the results
							A__						  =				mapping
							return mapping






def 	UpperCAmelCase       (						UpperCamelCase__							,     UpperCamelCase__					):






							"""simple docstring"""





							A__						  =				get_framework(UpperCamelCase__					)
							if framework is None:
														return None
							A__						  =				get_mapping_for_task(UpperCamelCase__							,     UpperCamelCase__					)
							if mapping is None:
														return None

							A__						  =				list({model_class.config_class for model_class in test_class.all_model_classes}					)
							if len(UpperCamelCase__					) != 1:
														raise ValueError('There should be exactly one configuration class from `test_class.all_model_classes`.'					)

							# This could be a list/tuple of model classes, but it's rare.
							A__						  =				mapping.get(config_classes[0]							,     UpperCamelCase__					)
							if isinstance(UpperCamelCase__							,     (tuple, list)					):
														A__						  =				sorted(UpperCamelCase__							,     key=lambda UpperCamelCase__					: x.__name__					)

							return model_class






def 	UpperCAmelCase       (						UpperCamelCase__					):






							"""simple docstring"""





							A__						  =				[(task, get_model_for_pipeline_test(UpperCamelCase__							,     UpperCamelCase__					)) for task in pipeline_test_mapping]
							A__						  =				sorted([(task, model) for task, model in mapping if model is not None]							,     key=lambda UpperCamelCase__					: x[0]					)

							return dict(UpperCamelCase__					)






def 	UpperCAmelCase       (						UpperCamelCase__					):






							"""simple docstring"""





							A__						  =				get_framework(UpperCamelCase__					)
							if framework == "pt":
														A__						  =				'torch'
							A__						  =				'{}'

							A__						  =				get_pipeline_model_mapping(UpperCamelCase__					)
							if len(UpperCamelCase__					) == 0:
														return ""

							A__						  =				[]
							for task, model_classes in mapping.items():
														if isinstance(UpperCamelCase__							,     (tuple, list)					):
																					# A list/tuple of model classes
																					A__						  =				'(' + ', '.join([x.__name__ for x in model_classes]					) + ')'
														else:
																					# A single model class
																					A__						  =				model_classes.__name__
														texts.append(F'''"{task}": {value}'''					)
							A__						  =				'{' + ', '.join(UpperCamelCase__					) + '}'
							A__						  =				F'''pipeline_model_mapping = {text} if is_{framework}_available() else {default_value}'''

							return text






def 	UpperCAmelCase       (						UpperCamelCase__					):






							"""simple docstring"""





							A__						  =				{'ModelTesterMixin', 'TFModelTesterMixin', 'FlaxModelTesterMixin'}
							if not issubclass(UpperCamelCase__							,     unittest.TestCase					):
														return False
							return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__]					)					) > 0






def 	UpperCAmelCase       (						UpperCamelCase__					):






							"""simple docstring"""





							A__						  =				[x for x in get_test_classes(UpperCamelCase__					) if is_valid_test_class(UpperCamelCase__					)]

							A__						  =				None
							for test_class in test_classes:
														# If a test class has defined `pipeline_model_mapping`, let's take it
														if getattr(UpperCamelCase__							,     'pipeline_model_mapping'							,     UpperCamelCase__					) is not None:
																					A__						  =				test_class
																					break
    # Take the test class with the shortest name (just a heuristic)
							if target_test_class is None and len(UpperCamelCase__					) > 0:
														A__						  =				sorted(UpperCamelCase__							,     key=lambda UpperCamelCase__					: (len(x.__name__					), x.__name__)					)[0]

							return target_test_class






def 	UpperCAmelCase       (						UpperCamelCase__							,     UpperCamelCase__							,     UpperCamelCase__					):






							"""simple docstring"""





							A__						  =				start_idx
							for idx, line in enumerate(lines[start_idx:]					):
														A__						  =				len(UpperCamelCase__					) - len(line.lstrip()					)
														if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"):
																					A__						  =				start_idx + idx
														elif idx > 0 and indent <= indent_level:
																					# Outside the definition block of `pipeline_model_mapping`
																					break

							return end_idx






def 	UpperCAmelCase       (						UpperCamelCase__							,     UpperCamelCase__=False					):






							"""simple docstring"""





							if getattr(UpperCamelCase__							,     'pipeline_model_mapping'							,     UpperCamelCase__					) is not None:
														if not overwrite:
																					return "", -1

							A__						  =				get_pipeline_model_mapping_string(UpperCamelCase__					)
							if len(UpperCamelCase__					) == 0:
														return "", -1
							A__						  =				line_to_add + '\n'

							# The code defined the class `test_class`
							A__  ,	A__						  =				inspect.getsourcelines(UpperCamelCase__					)
							# `inspect` gives the code for an object, including decorator(s) if any.
							# We (only) need the exact line of the class definition.
							for idx, line in enumerate(UpperCamelCase__					):
														if line.lstrip().startswith('class '					):
																					A__						  =				class_lines[idx:]
																					class_start_line_no += idx
																					break
							A__						  =				class_start_line_no + len(UpperCamelCase__					) - 1

							# The index in `class_lines` that starts the definition of `all_model_classes`, `all_generative_model_classes` or
							# `pipeline_model_mapping`. This assumes they are defined in such order, and we take the start index of the last
							# block that appears in a `test_class`.
							A__						  =				None
							# The indent level of the line at `class_lines[start_idx]` (if defined)
							A__						  =				0
							# To record if `pipeline_model_mapping` is found in `test_class`.
							A__						  =				None
							for idx, line in enumerate(UpperCamelCase__					):
														if line.strip().startswith('all_model_classes = '					):
																					A__						  =				len(UpperCamelCase__					) - len(line.lstrip()					)
																					A__						  =				idx
														elif line.strip().startswith('all_generative_model_classes = '					):
																					A__						  =				len(UpperCamelCase__					) - len(line.lstrip()					)
																					A__						  =				idx
														elif line.strip().startswith('pipeline_model_mapping = '					):
																					A__						  =				len(UpperCamelCase__					) - len(line.lstrip()					)
																					A__						  =				idx
																					A__						  =				line
																					break

							if start_idx is None:
														return "", -1
							# Find the ending index (inclusive) of the above found block.
							A__						  =				find_block_ending(UpperCamelCase__							,     UpperCamelCase__							,     UpperCamelCase__					)

							# Extract `is_xxx_available()` from existing blocks: some models require specific libraries like `timm` and use
							# `is_timm_available()` instead of `is_torch_available()`.
							# Keep leading and trailing whitespaces
							A__						  =				re.compile(r'\s(is_\S+?_available\(\))\s'					)
							for line in class_lines[start_idx : end_idx + 1]:
														A__						  =				r.search(UpperCamelCase__					)
														if backend_condition is not None:
																					# replace the leading and trailing whitespaces to the space character " ".
																					A__						  =				' ' + backend_condition[0][1:-1] + ' '
																					A__						  =				r.sub(UpperCamelCase__							,     UpperCamelCase__					)
																					break

							if def_line is None:
														# `pipeline_model_mapping` is not defined. The target index is set to the ending index (inclusive) of
														# `all_model_classes` or `all_generative_model_classes`.
														A__						  =				end_idx
							else:
														# `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index.
														A__						  =				start_idx - 1
														# mark the lines of the currently existing `pipeline_model_mapping` to be removed.
														for idx in range(UpperCamelCase__							,     end_idx + 1					):
																					# These lines are going to be removed before writing to the test file.
																					A__						  =				None  # noqa

    # Make sure the test class is a subclass of `PipelineTesterMixin`.
							A__						  =				[x.__name__ for x in test_class.__bases__]
							if "PipelineTesterMixin" not in parent_classes:
														# Put `PipelineTesterMixin` just before `unittest.TestCase`
														A__						  =				[x for x in parent_classes if x != 'TestCase'] + ['PipelineTesterMixin']
														if "TestCase" in parent_classes:
																					# Here we **assume** the original string is always with `unittest.TestCase`.
																					_parent_classes.append('unittest.TestCase'					)
														A__						  =				', '.join(_parent_classes					)
														for idx, line in enumerate(UpperCamelCase__					):
																					# Find the ending of the declaration of `test_class`
																					if line.strip().endswith('):'					):
																												# mark the lines of the declaration of `test_class` to be removed
																												for _idx in range(idx + 1					):
																																			A__						  =				None  # noqa
																												break
        # Add the new, one-line, class declaration for `test_class`
														A__						  =				F'''class {test_class.__name__}({parent_classes}):\n'''

							# Add indentation
							A__						  =				' ' * indent_level + line_to_add
							# Insert `pipeline_model_mapping` to `class_lines`.
							# (The line at `target_idx` should be kept by definition!)
							A__						  =				class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :]
							# Remove the lines that are marked to be removed
							A__						  =				[x for x in class_lines if x is not None]

							# Move from test class to module (in order to write to the test file)
							A__						  =				inspect.getsourcelines(inspect.getmodule(UpperCamelCase__					)					)[0]
							# Be careful with the 1-off between line numbers and array indices
							A__						  =				module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:]
							A__						  =				''.join(UpperCamelCase__					)

							A__						  =				inspect.getsourcefile(UpperCamelCase__					)
							with open(UpperCamelCase__							,     'w'							,     encoding='UTF-8'							,     newline='\n'					) as fp:
														fp.write(UpperCamelCase__					)

							return line_to_add






def 	UpperCAmelCase       (						UpperCamelCase__							,     UpperCamelCase__=False					):






							"""simple docstring"""





							A__						  =				find_test_class(UpperCamelCase__					)
							if test_class:
														add_pipeline_model_mapping(UpperCamelCase__							,     overwrite=UpperCamelCase__					)


if __name__ == "__main__":
				__lowerCamelCase									=	argparse.ArgumentParser()
				parser.add_argument(
				    "--test_file", type=str, help="A path to the test file, starting with the repository's `tests` directory."
				)
				parser.add_argument(
				    "--all",
				    action="store_true",
				    help="If to check and modify all test files.",
				)
				parser.add_argument(
				    "--overwrite",
				    action="store_true",
				    help="If to overwrite a test class if it has already defined `pipeline_model_mapping`.",
				)
				__lowerCamelCase									=	parser.parse_args()

				if not args.all and not args.test_file:
								raise ValueError("Please specify either `test_file` or pass `--all` to check/modify all test files.")
				elif args.all and args.test_file:
								raise ValueError("Only one of `--test_file` and `--all` could be specified.")

				__lowerCamelCase									=	[]
				if args.test_file:
								__lowerCamelCase									=	[args.test_file]
				else:
								__lowerCamelCase									=	os.path.join("tests", "models", "**", "test_modeling_*.py")
								for test_file in glob.glob(pattern):
												# `Flax` is not concerned at this moment
												if not test_file.startswith("test_modeling_flax_"):
																test_files.append(test_file)

				for test_file in test_files:
								if test_file in TEST_FILE_TO_IGNORE:
												print(F'''[SKIPPED] {test_file} is skipped as it is in `TEST_FILE_TO_IGNORE` in the file {__file__}.''')
												continue
								add_pipeline_model_mapping_to_test_file(test_file, overwrite=args.overwrite)






"""simple docstring"""




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

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


__lowerCamelCase									=	logging.get_logger(__name__)

__lowerCamelCase									=	{
    "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json",
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}
class      UpperCamelCase__(      __A			):
						lowerCAmelCase__	:    List[str]    				=		'blenderbot'
						lowerCAmelCase__	:    Union[str, Any]    				=		['past_key_values']
						lowerCAmelCase__	:    Optional[Any]    				=		{'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}





						def __init__(							self		,__UpperCAmelCase=80_08		,__UpperCAmelCase=1_28		,__UpperCAmelCase=2		,__UpperCAmelCase=1_02_40		,__UpperCAmelCase=32		,__UpperCAmelCase=24		,__UpperCAmelCase=1_02_40		,__UpperCAmelCase=32		,__UpperCAmelCase=0.0		,__UpperCAmelCase=0.0		,__UpperCAmelCase=True		,__UpperCAmelCase=True		,__UpperCAmelCase="gelu"		,__UpperCAmelCase=25_60		,__UpperCAmelCase=0.1		,__UpperCAmelCase=0.0		,__UpperCAmelCase=0.0		,__UpperCAmelCase=0.0_2		,__UpperCAmelCase=1		,__UpperCAmelCase=False		,__UpperCAmelCase=0		,__UpperCAmelCase=1		,__UpperCAmelCase=2		,__UpperCAmelCase=3		,__UpperCAmelCase=2		,**__UpperCAmelCase		,)       ->					Any:
													A__						  =				vocab_size
													A__						  =				max_position_embeddings
													A__						  =				d_model
													A__						  =				encoder_ffn_dim
													A__						  =				encoder_layers
													A__						  =				encoder_attention_heads
													A__						  =				decoder_ffn_dim
													A__						  =				decoder_layers
													A__						  =				decoder_attention_heads
													A__						  =				dropout
													A__						  =				attention_dropout
													A__						  =				activation_dropout
													A__						  =				activation_function
													A__						  =				init_std
													A__						  =				encoder_layerdrop
													A__						  =				decoder_layerdrop
													A__						  =				use_cache
													A__						  =				encoder_layers
													A__						  =				scale_embedding  # scale factor will be sqrt(d_model) if True

													super().__init__(
													    pad_token_id=__UpperCAmelCase		,bos_token_id=__UpperCAmelCase		,eos_token_id=__UpperCAmelCase		,is_encoder_decoder=__UpperCAmelCase		,decoder_start_token_id=__UpperCAmelCase		,encoder_no_repeat_ngram_size=__UpperCAmelCase		,forced_eos_token_id=__UpperCAmelCase		,**__UpperCAmelCase		,)






class      UpperCamelCase__(      __A			):





						@property
						def 					snake_case__						(							self  )       ->					Mapping[str, Mapping[int, str]]:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				OrderedDict(
																				    [
																				        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																				        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																				    ]  )
																				if self.use_past:
																											A__						  =				{0: 'batch'}
																											A__						  =				{0: 'batch', 1: 'past_decoder_sequence + sequence'}
																				else:
																											A__						  =				{0: 'batch', 1: 'decoder_sequence'}
																											A__						  =				{0: 'batch', 1: 'decoder_sequence'}
																				if self.use_past:
																											self.fill_with_past_key_values_(__UpperCAmelCase		,direction='inputs'  )
													elif self.task == "causal-lm":
																				A__						  =				OrderedDict(
																				    [
																				        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																				        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																				    ]  )
																				if self.use_past:
																											A__  ,	A__						  =				self.num_layers
																											for i in range(__UpperCAmelCase  ):
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
													else:
																				A__						  =				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 					snake_case__						(							self  )       ->					Mapping[str, Mapping[int, str]]:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				super().outputs
													else:
																				A__						  =				super(__UpperCAmelCase		,self  ).outputs
																				if self.use_past:
																											A__  ,	A__						  =				self.num_layers
																											for i in range(__UpperCAmelCase  ):
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
													return common_outputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )
													# Generate decoder inputs
													A__						  =				seq_length if not self.use_past else 1
													A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )
													A__						  =				{f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
													A__						  =				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
																				A__  ,	A__						  =				common_inputs['input_ids'].shape
																				A__						  =				common_inputs['decoder_input_ids'].shape[1]
																				A__  ,	A__						  =				self.num_attention_heads
																				A__						  =				(
																				    batch,
																				    num_encoder_attention_heads,
																				    encoder_seq_length,
																				    self._config.hidden_size // num_encoder_attention_heads,
																				)
																				A__						  =				decoder_seq_length
																				A__						  =				(
																				    batch,
																				    num_decoder_attention_heads,
																				    decoder_past_length,
																				    self._config.hidden_size // num_decoder_attention_heads,
																				)
																				A__						  =				torch.cat(
																				    [common_inputs['decoder_attention_mask'], torch.ones(__UpperCAmelCase		,__UpperCAmelCase  )]		,dim=1  )
																				A__						  =				[]
																				A__  ,	A__						  =				self.num_layers

																				for _ in range(__UpperCAmelCase  ):
																											common_inputs["past_key_values"].append(
																											    (
																											        torch.zeros(__UpperCAmelCase  ),
																											        torch.zeros(__UpperCAmelCase  ),
																											        torch.zeros(__UpperCAmelCase  ),
																											        torch.zeros(__UpperCAmelCase  ),
																											    )  )
													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    __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
																				A__  ,	A__						  =				common_inputs['input_ids'].shape
																				A__						  =				seqlen
																				A__  ,	A__						  =				self.num_layers
																				A__  ,	A__						  =				self.num_attention_heads
																				A__						  =				(
																				    batch,
																				    num_encoder_attention_heads,
																				    past_key_values_length,
																				    self._config.hidden_size // num_encoder_attention_heads,
																				)
																				A__						  =				common_inputs['attention_mask'].dtype
																				A__						  =				torch.cat(
																				    [common_inputs['attention_mask'], torch.ones(__UpperCAmelCase		,__UpperCAmelCase		,dtype=__UpperCAmelCase  )]		,dim=1  )
																				A__						  =				[
																				    (torch.zeros(__UpperCAmelCase  ), torch.zeros(__UpperCAmelCase  )) for _ in range(__UpperCAmelCase  )
																				]
													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													# 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__						  =				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
													A__						  =				tokenizer.num_special_tokens_to_add(__UpperCAmelCase  )
													A__						  =				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
													A__						  =				[' '.join([tokenizer.unk_token]  ) * seq_length] * batch_size
													A__						  =				dict(tokenizer(__UpperCAmelCase		,return_tensors=__UpperCAmelCase  )  )
													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																				    __UpperCAmelCase		,batch_size=__UpperCAmelCase		,seq_length=__UpperCAmelCase		,is_pair=__UpperCAmelCase		,framework=__UpperCAmelCase  )

													elif self.task == "causal-lm":
																				A__						  =				self._generate_dummy_inputs_for_causal_lm(
																				    __UpperCAmelCase		,batch_size=__UpperCAmelCase		,seq_length=__UpperCAmelCase		,is_pair=__UpperCAmelCase		,framework=__UpperCAmelCase  )
													else:
																				A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
																				    __UpperCAmelCase		,batch_size=__UpperCAmelCase		,seq_length=__UpperCAmelCase		,is_pair=__UpperCAmelCase		,framework=__UpperCAmelCase  )

													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					Tuple:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				super()._flatten_past_key_values_(__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )
													else:
																				A__						  =				super(__UpperCAmelCase		,self  )._flatten_past_key_values_(
																				    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					int:
													if direction not in ["inputs", "outputs"]:
																				raise ValueError(f'''direction must either be "inputs" or "outputs", but {direction} was given'''  )

													A__						  =				'past_key_values' if direction == 'inputs' else 'present'
													A__  ,	A__						  =				self.num_layers

													A__						  =				'past_encoder_sequence'
													A__						  =				'past_decoder_sequence' if direction == 'inputs' else 'past_decoder_sequence + sequence'

													for i in range(__UpperCAmelCase  ):
																				A__						  =				{0: 'batch', 2: decoder_sequence}
																				A__						  =				{0: 'batch', 2: decoder_sequence}
																				A__						  =				{0: 'batch', 2: encoder_sequence}
																				A__						  =				{0: 'batch', 2: encoder_sequence}





