





'''simple docstring'''


import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


lowerCAmelCase      :  Tuple      							=get_logger(__name__)

# Datasets
lowerCAmelCase      :  List[Any]      							='''https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets'''
lowerCAmelCase      :  Optional[int]      							='''https://cdn-datasets.huggingface.co/datasets/datasets'''
lowerCAmelCase      :  Optional[Any]      							='''https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}'''

# Metrics
lowerCAmelCase      :  List[Any]      							='''https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics'''
lowerCAmelCase      :  Any      							='''https://cdn-datasets.huggingface.co/datasets/metric'''
lowerCAmelCase      :  List[Any]      							='''https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}'''

# Hub
lowerCAmelCase      :  Optional[Any]      							=os.environ.get('''HF_ENDPOINT''', '''https://huggingface.co''')
lowerCAmelCase      :  Dict      							=HF_ENDPOINT + '''/datasets/{repo_id}/resolve/{revision}/{path}'''
lowerCAmelCase      :  str      							='''main'''

lowerCAmelCase      :  Dict      							=version.parse(platform.python_version())

if PY_VERSION < version.parse('''3.8'''):
 import importlib_metadata
else:
 import importlib.metadata as importlib_metadata

# General environment variables accepted values for booleans
lowerCAmelCase      :  Any      							={'''1''', '''ON''', '''YES''', '''TRUE'''}
lowerCAmelCase      :  Optional[Any]      							=ENV_VARS_TRUE_VALUES.union({'''AUTO'''})


# Imports
lowerCAmelCase      :  int      							=version.parse(importlib_metadata.version('''dill'''))
lowerCAmelCase      :  Optional[Any]      							=version.parse(importlib_metadata.version('''pandas'''))
lowerCAmelCase      :  Dict      							=version.parse(importlib_metadata.version('''pyarrow'''))

lowerCAmelCase      :  Dict      							=os.environ.get('''USE_TF''', '''AUTO''').upper()
lowerCAmelCase      :  Optional[Any]      							=os.environ.get('''USE_TORCH''', '''AUTO''').upper()
lowerCAmelCase      :  str      							=os.environ.get('''USE_JAX''', '''AUTO''').upper()

lowerCAmelCase      :  List[str]      							='''N/A'''
lowerCAmelCase      :  List[str]      							=False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
 lowerCAmelCase      :  int      							=importlib.util.find_spec('''torch''') is not None
 if TORCH_AVAILABLE:
  try:
   lowerCAmelCase      :  Union[str, Any]      							=version.parse(importlib_metadata.version('''torch'''))
   logger.info(F'''PyTorch version {TORCH_VERSION} available.''')
  except importlib_metadata.PackageNotFoundError:
   pass
else:
 logger.info('''Disabling PyTorch because USE_TF is set''')

lowerCAmelCase      :  Union[str, Any]      							='''N/A'''
lowerCAmelCase      :  Optional[Any]      							=False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
 lowerCAmelCase      :  str      							=importlib.util.find_spec('''tensorflow''') is not None
 if TF_AVAILABLE:
  # For the metadata, we have to look for both tensorflow and tensorflow-cpu
  for package in [
      "tensorflow",
      "tensorflow-cpu",
      "tensorflow-gpu",
      "tf-nightly",
      "tf-nightly-cpu",
      "tf-nightly-gpu",
      "intel-tensorflow",
      "tensorflow-rocm",
      "tensorflow-macos",
  ]:
   try:
    lowerCAmelCase      :  Any      							=version.parse(importlib_metadata.version(package))
   except importlib_metadata.PackageNotFoundError:
    continue
   else:
    break
  else:
   lowerCAmelCase      :  Any      							=False
 if TF_AVAILABLE:
  if TF_VERSION.major < 2:
   logger.info(F'''TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.''')
   lowerCAmelCase      :  Any      							=False
  else:
   logger.info(F'''TensorFlow version {TF_VERSION} available.''')
else:
 logger.info('''Disabling Tensorflow because USE_TORCH is set''')


lowerCAmelCase      :  str      							='''N/A'''
lowerCAmelCase      :  List[str]      							=False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
 lowerCAmelCase      :  Optional[Any]      							=importlib.util.find_spec('''jax''') is not None and importlib.util.find_spec('''jaxlib''') is not None
 if JAX_AVAILABLE:
  try:
   lowerCAmelCase      :  Union[str, Any]      							=version.parse(importlib_metadata.version('''jax'''))
   logger.info(F'''JAX version {JAX_VERSION} available.''')
  except importlib_metadata.PackageNotFoundError:
   pass
else:
 logger.info('''Disabling JAX because USE_JAX is set to False''')


lowerCAmelCase      :  List[Any]      							=os.environ.get('''USE_BEAM''', '''AUTO''').upper()
lowerCAmelCase      :  List[str]      							='''N/A'''
lowerCAmelCase      :  Dict      							=False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
 try:
  lowerCAmelCase      :  Union[str, Any]      							=version.parse(importlib_metadata.version('''apache_beam'''))
  lowerCAmelCase      :  Optional[Any]      							=True
  logger.info(F'''Apache Beam version {BEAM_VERSION} available.''')
 except importlib_metadata.PackageNotFoundError:
  pass
else:
 logger.info('''Disabling Apache Beam because USE_BEAM is set to False''')


# Optional tools for data loading
lowerCAmelCase      :  List[str]      							=importlib.util.find_spec('''sqlalchemy''') is not None

# Optional tools for feature decoding
lowerCAmelCase      :  List[str]      							=importlib.util.find_spec('''PIL''') is not None
lowerCAmelCase      :  int      							=importlib.util.find_spec('''soundfile''') is not None and version.parse(
    importlib.import_module('''soundfile''').__libsndfile_version__
) >= version.parse('''1.0.31''')
lowerCAmelCase      :  str      							=importlib.util.find_spec('''soundfile''') is not None and version.parse(
    importlib.import_module('''soundfile''').__libsndfile_version__
) >= version.parse('''1.1.0''')

# Optional compression tools
lowerCAmelCase      :  Dict      							=importlib.util.find_spec('''rarfile''') is not None
lowerCAmelCase      :  int      							=importlib.util.find_spec('''zstandard''') is not None
lowerCAmelCase      :  Dict      							=importlib.util.find_spec('''lz4''') is not None
lowerCAmelCase      :  str      							=importlib.util.find_spec('''py7zr''') is not None


# Cache location
lowerCAmelCase      :  Union[str, Any]      							='''~/.cache'''
lowerCAmelCase      :  Union[str, Any]      							=os.getenv('''XDG_CACHE_HOME''', DEFAULT_XDG_CACHE_HOME)
lowerCAmelCase      :  Optional[int]      							=os.path.join(XDG_CACHE_HOME, '''huggingface''')
lowerCAmelCase      :  Optional[Any]      							=os.path.expanduser(os.getenv('''HF_HOME''', DEFAULT_HF_CACHE_HOME))

lowerCAmelCase      :  Tuple      							=os.path.join(HF_CACHE_HOME, '''datasets''')
lowerCAmelCase      :  Optional[Any]      							=Path(os.getenv('''HF_DATASETS_CACHE''', DEFAULT_HF_DATASETS_CACHE))

lowerCAmelCase      :  int      							=os.path.join(HF_CACHE_HOME, '''metrics''')
lowerCAmelCase      :  Dict      							=Path(os.getenv('''HF_METRICS_CACHE''', DEFAULT_HF_METRICS_CACHE))

lowerCAmelCase      :  int      							=os.path.join(HF_CACHE_HOME, '''modules''')
lowerCAmelCase      :  Tuple      							=Path(os.getenv('''HF_MODULES_CACHE''', DEFAULT_HF_MODULES_CACHE))

lowerCAmelCase      :  Optional[int]      							='''downloads'''
lowerCAmelCase      :  int      							=os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
lowerCAmelCase      :  List[str]      							=Path(os.getenv('''HF_DATASETS_DOWNLOADED_DATASETS_PATH''', DEFAULT_DOWNLOADED_DATASETS_PATH))

lowerCAmelCase      :  Dict      							='''extracted'''
lowerCAmelCase      :  int      							=os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
lowerCAmelCase      :  int      							=Path(os.getenv('''HF_DATASETS_EXTRACTED_DATASETS_PATH''', DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
lowerCAmelCase      :  Tuple      							=(
    os.environ.get('''HF_UPDATE_DOWNLOAD_COUNTS''', '''AUTO''').upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
lowerCAmelCase      :  Any      							=1_000

# Size of the preloaded record batch in `Dataset.__iter__`
lowerCAmelCase      :  Optional[int]      							=10

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
lowerCAmelCase      :  Optional[Any]      							=4 << 30

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
lowerCAmelCase      :  int      							='''500MB'''

# Parquet configuration
lowerCAmelCase      :  Optional[Any]      							=100
lowerCAmelCase      :  Optional[Any]      							=100
lowerCAmelCase      :  Dict      							=100

# Offline mode
lowerCAmelCase      :  Optional[Any]      							=os.environ.get('''HF_DATASETS_OFFLINE''', '''AUTO''').upper() in ENV_VARS_TRUE_VALUES

# In-memory
lowerCAmelCase      :  Dict      							=0  # Disabled
lowerCAmelCase      :  List[Any]      							=float(os.environ.get('''HF_DATASETS_IN_MEMORY_MAX_SIZE''', DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
lowerCAmelCase      :  Optional[Any]      							='''dataset.arrow'''
lowerCAmelCase      :  List[str]      							='''indices.arrow'''
lowerCAmelCase      :  Optional[Any]      							='''state.json'''
lowerCAmelCase      :  Optional[int]      							='''dataset_info.json'''
lowerCAmelCase      :  Any      							='''dataset_infos.json'''
lowerCAmelCase      :  Dict      							='''LICENSE'''
lowerCAmelCase      :  Optional[int]      							='''metric_info.json'''
lowerCAmelCase      :  Union[str, Any]      							='''dataset_dict.json'''

lowerCAmelCase      :  Optional[int]      							='''datasets_modules'''

lowerCAmelCase      :  Optional[Any]      							=255

# Streaming
lowerCAmelCase      :  Optional[int]      							=20
lowerCAmelCase      :  int      							=5

# Datasets without script
lowerCAmelCase      :  List[Any]      							=200
lowerCAmelCase      :  Union[str, Any]      							=10
lowerCAmelCase      :  Optional[int]      							=200

# Progress bars
lowerCAmelCase      :  int      							=0.05  # 20 progress updates per sec









'''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      :  str      							=logging.get_logger(__name__)

lowerCAmelCase      :  Union[str, Any]      							={
    '''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    a_     (       _lowerCAmelCase							):
     __A  				=    "blenderbot"
     __A  				=    ["past_key_values"]
     __A  				=    {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}





     def __init__(				self	:      Dict			,   lowercase	:      List[Any]=8_008			,   lowercase	:      List[str]=128			,   lowercase	:      Optional[int]=2			,   lowercase	:      Optional[int]=10_240			,   lowercase	:      Tuple=32			,   lowercase	:      int=24			,   lowercase	:      Dict=10_240			,   lowercase	:      Any=32			,   lowercase	:      Optional[int]=0.0			,   lowercase	:      Dict=0.0			,   lowercase	:      int=True			,   lowercase	:      Tuple=True			,   lowercase	:      List[str]="gelu"			,   lowercase	:      int=2_560			,   lowercase	:      Optional[Any]=0.1			,   lowercase	:      Any=0.0			,   lowercase	:      List[str]=0.0			,   lowercase	:      Optional[Any]=0.02			,   lowercase	:      Tuple=1			,   lowercase	:      Union[str, Any]=False			,   lowercase	:      str=0			,   lowercase	:      List[str]=1			,   lowercase	:      Optional[Any]=2			,   lowercase	:      Union[str, Any]=3			,   lowercase	:      List[str]=2			,   **lowercase	:      Optional[Any]			,   ):





        """simple docstring"""




        lowercase_    :str					    =				vocab_size
        lowercase_    :Any					    =				max_position_embeddings
        lowercase_    :List[Any]					    =				d_model
        lowercase_    :Union[str, Any]					    =				encoder_ffn_dim
        lowercase_    :str					    =				encoder_layers
        lowercase_    :Optional[int]					    =				encoder_attention_heads
        lowercase_    :Dict					    =				decoder_ffn_dim
        lowercase_    :str					    =				decoder_layers
        lowercase_    :int					    =				decoder_attention_heads
        lowercase_    :Union[str, Any]					    =				dropout
        lowercase_    :int					    =				attention_dropout
        lowercase_    :int					    =				activation_dropout
        lowercase_    :str					    =				activation_function
        lowercase_    :Tuple					    =				init_std
        lowercase_    :Any					    =				encoder_layerdrop
        lowercase_    :Dict					    =				decoder_layerdrop
        lowercase_    :int					    =				use_cache
        lowercase_    :Dict					    =				encoder_layers
        lowercase_    :Dict					    =				scale_embedding  # scale factor will be sqrt(d_model) if True

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







class    a_     (       _lowerCAmelCase							):





     @property
     def 							lowercase__   (				self	:      Union[str, Any]		):





        """simple docstring"""




        if self.task in ["default", "seq2seq-lm"]:
           lowercase_    :Optional[int]					    =				OrderedDict(
               [
                   ("input_ids", {0: "batch", 1: "encoder_sequence"}),
                   ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
               ]		)
           if self.use_past:
              lowercase_    :int					    =				{0: "batch"}
              lowercase_    :List[str]					    =				{0: "batch", 1: "past_decoder_sequence + sequence"}
           else:
              lowercase_    :Union[str, Any]					    =				{0: "batch", 1: "decoder_sequence"}
              lowercase_    :List[Any]					    =				{0: "batch", 1: "decoder_sequence"}
           if self.use_past:
              self.fill_with_past_key_values_(lowercase			,   direction="inputs"		)
        elif self.task == "causal-lm":
           lowercase_    :List[Any]					    =				OrderedDict(
               [
                   ("input_ids", {0: "batch", 1: "encoder_sequence"}),
                   ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
               ]		)
           if self.use_past:
              lowercase_    ,							lowercase_    :Optional[int]					    =				self.num_layers
              for i in range(lowercase		):
                 lowercase_    :List[str]					    =				{0: "batch", 2: "past_sequence + sequence"}
                 lowercase_    :Any					    =				{0: "batch", 2: "past_sequence + sequence"}
        else:
           lowercase_    :str					    =				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 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




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





     def 							lowercase__   (				self	:      Tuple			,   lowercase	:      PreTrainedTokenizer			,   lowercase	:      int = -1			,   lowercase	:      int = -1			,   lowercase	:      bool = False			,   lowercase	:      Optional[TensorType] = None			,   ):





        """simple docstring"""




        lowercase_    :int					    =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            lowercase			,   lowercase			,   lowercase			,   lowercase			,   lowercase		)
        # Generate decoder inputs
        lowercase_    :List[Any]					    =				seq_length if not self.use_past else 1
        lowercase_    :Optional[Any]					    =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            lowercase			,   lowercase			,   lowercase			,   lowercase			,   lowercase		)
        lowercase_    :Tuple					    =				{F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
        lowercase_    :Any					    =				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
           lowercase_    ,							lowercase_    :int					    =				common_inputs["input_ids"].shape
           lowercase_    :Tuple					    =				common_inputs["decoder_input_ids"].shape[1]
           lowercase_    ,							lowercase_    :Tuple					    =				self.num_attention_heads
           lowercase_    :List[Any]					    =				(
               batch,
               num_encoder_attention_heads,
               encoder_seq_length,
               self._config.hidden_size // num_encoder_attention_heads,
           )
           lowercase_    :List[Any]					    =				decoder_seq_length
           lowercase_    :str					    =				(
               batch,
               num_decoder_attention_heads,
               decoder_past_length,
               self._config.hidden_size // num_decoder_attention_heads,
           )
           lowercase_    :Optional[int]					    =				torch.cat(
               [common_inputs["decoder_attention_mask"], torch.ones(lowercase			,   lowercase		)]			,   dim=1		)
           lowercase_    :int					    =				[]
           lowercase_    ,							lowercase_    :Tuple					    =				self.num_layers

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





     def 							lowercase__   (				self	:      Optional[Any]			,   lowercase	:      PreTrainedTokenizer			,   lowercase	:      int = -1			,   lowercase	:      int = -1			,   lowercase	:      bool = False			,   lowercase	:      Optional[TensorType] = None			,   ):





        """simple docstring"""




        lowercase_    :str					    =				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
           lowercase_    ,							lowercase_    :List[str]					    =				common_inputs["input_ids"].shape
           lowercase_    :int					    =				seqlen
           lowercase_    ,							lowercase_    :int					    =				self.num_layers
           lowercase_    ,							lowercase_    :Union[str, Any]					    =				self.num_attention_heads
           lowercase_    :Any					    =				(
               batch,
               num_encoder_attention_heads,
               past_key_values_length,
               self._config.hidden_size // num_encoder_attention_heads,
           )
           lowercase_    :Optional[Any]					    =				common_inputs["attention_mask"].dtype
           lowercase_    :List[Any]					    =				torch.cat(
               [common_inputs["attention_mask"], torch.ones(lowercase			,   lowercase			,   dtype=lowercase		)]			,   dim=1		)
           lowercase_    :Any					    =				[
               (torch.zeros(lowercase		), torch.zeros(lowercase		)) for _ in range(lowercase		)
           ]
        return common_inputs





     def 							lowercase__   (				self	:      Dict			,   lowercase	:      PreTrainedTokenizer			,   lowercase	:      int = -1			,   lowercase	:      int = -1			,   lowercase	:      bool = False			,   lowercase	:      Optional[TensorType] = None			,   ):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				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
        lowercase_    :Optional[Any]					    =				tokenizer.num_special_tokens_to_add(lowercase		)
        lowercase_    :int					    =				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
        lowercase_    :int					    =				[" ".join([tokenizer.unk_token]		) * seq_length] * batch_size
        lowercase_    :Dict					    =				dict(tokenizer(lowercase			,   return_tensors=lowercase		)		)
        return common_inputs





     def 							lowercase__   (				self	:      Optional[Any]			,   lowercase	:      PreTrainedTokenizer			,   lowercase	:      int = -1			,   lowercase	:      int = -1			,   lowercase	:      bool = False			,   lowercase	:      Optional[TensorType] = None			,   ):





        """simple docstring"""




        if self.task in ["default", "seq2seq-lm"]:
           lowercase_    :str					    =				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":
           lowercase_    :Optional[Any]					    =				self._generate_dummy_inputs_for_causal_lm(
               lowercase			,   batch_size=lowercase			,   seq_length=lowercase			,   is_pair=lowercase			,   framework=lowercase		)
        else:
           lowercase_    :List[str]					    =				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 							lowercase__   (				self	:      Optional[int]			,   lowercase	:      str			,   lowercase	:      Union[str, Any]			,   lowercase	:      int			,   lowercase	:      List[Any]		):





        """simple docstring"""




        if self.task in ["default", "seq2seq-lm"]:
           lowercase_    :Optional[int]					    =				super()._flatten_past_key_values_(lowercase			,   lowercase			,   lowercase			,   lowercase		)
        else:
           lowercase_    :Tuple					    =				super(lowercase			,   self		)._flatten_past_key_values_(
               lowercase			,   lowercase			,   lowercase			,   lowercase		)







     def 							lowercase__   (				self	:      List[Any]			,   lowercase	:      Mapping[str, Mapping[int, str]]			,   lowercase	:      str		):





        """simple docstring"""




        if direction not in ["inputs", "outputs"]:
           raise ValueError(F'direction must either be "inputs" or "outputs", but {direction} was given'		)

        lowercase_    :Any					    =				"past_key_values" if direction == "inputs" else "present"
        lowercase_    ,							lowercase_    :Optional[int]					    =				self.num_layers

        lowercase_    :str					    =				"past_encoder_sequence"
        lowercase_    :Tuple					    =				"past_decoder_sequence" if direction == "inputs" else "past_decoder_sequence + sequence"

        for i in range(lowercase		):
           lowercase_    :Dict					    =				{0: "batch", 2: decoder_sequence}
           lowercase_    :Optional[int]					    =				{0: "batch", 2: decoder_sequence}
           lowercase_    :Optional[int]					    =				{0: "batch", 2: encoder_sequence}
           lowercase_    :int					    =				{0: "batch", 2: encoder_sequence}


