
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


lowercase						:      List[str]									= logging.get_logger(__name__)

lowercase						:      Tuple									= {
    'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json',
    # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
}




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  'blenderbot-small'
	_A			=  ['past_key_values']
	_A			=  {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}







	def __init__(      self	:Union[str, Any]  ,     a	:List[str]=5_0_2_6_5  ,     a	:Dict=5_1_2  ,     a	:str=8  ,     a	:List[Any]=2_0_4_8  ,     a	:Tuple=1_6  ,     a	:str=8  ,     a	:str=2_0_4_8  ,     a	:List[Any]=1_6  ,     a	:List[str]=0.0  ,     a	:Optional[Any]=0.0  ,     a	:int=True  ,     a	:Dict=True  ,     a	:List[str]="gelu"  ,     a	:str=5_1_2  ,     a	:List[Any]=0.1  ,     a	:Union[str, Any]=0.0  ,     a	:Any=0.0  ,     a	:Optional[Any]=0.02  ,     a	:Any=1  ,     a	:Optional[int]=False  ,     a	:Union[str, Any]=0  ,     a	:Union[str, Any]=1  ,     a	:Optional[int]=2  ,     a	:Tuple=2  ,     **a	:Tuple  ,     )	->				Dict:
								__UpperCamelCase			:     Union[str, Any]         =      vocab_size
								__UpperCamelCase			:     Optional[int]         =      max_position_embeddings
								__UpperCamelCase			:     str         =      d_model
								__UpperCamelCase			:     Optional[Any]         =      encoder_ffn_dim
								__UpperCamelCase			:     Union[str, Any]         =      encoder_layers
								__UpperCamelCase			:     List[str]         =      encoder_attention_heads
								__UpperCamelCase			:     List[Any]         =      decoder_ffn_dim
								__UpperCamelCase			:     str         =      decoder_layers
								__UpperCamelCase			:     Any         =      decoder_attention_heads
								__UpperCamelCase			:     Optional[int]         =      dropout
								__UpperCamelCase			:     Dict         =      attention_dropout
								__UpperCamelCase			:     Optional[Any]         =      activation_dropout
								__UpperCamelCase			:     int         =      activation_function
								__UpperCamelCase			:     Optional[int]         =      init_std
								__UpperCamelCase			:     Tuple         =      encoder_layerdrop
								__UpperCamelCase			:     List[str]         =      decoder_layerdrop
								__UpperCamelCase			:     Optional[int]         =      use_cache
								__UpperCamelCase			:     Optional[int]         =      encoder_layers
								__UpperCamelCase			:     Dict         =      scale_embedding  # scale factor will be sqrt(d_model) if True

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




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	@property
	def      _lowerCamelCase       (      self	:Tuple		)	->				Mapping[str, Mapping[int, str]]:
								if self.task in ["default", "seq2seq-lm"]:
															__UpperCamelCase			:     Tuple         =      OrderedDict(
															    [
															        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
															        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
															    ]		)

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

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







	def      _lowerCamelCase       (      self	:int  ,     a	:PreTrainedTokenizer  ,     a	:int = -1  ,     a	:int = -1  ,     a	:bool = False  ,     a	:Optional[TensorType] = None  ,     )	->				Mapping[str, Any]:
								__UpperCamelCase			:     List[Any]         =      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    a  ,     a  ,     a  ,     a  ,     a		)

								# Generate decoder inputs
								__UpperCamelCase			:     List[Any]         =      seq_length if not self.use_past else 1
								__UpperCamelCase			:     str         =      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    a  ,     a  ,     a  ,     a  ,     a		)
								__UpperCamelCase			:     List[str]         =      {f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
								__UpperCamelCase			:     Dict         =      dict(**a  ,     **a		)

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

															__UpperCamelCase			:     Any         =      torch.cat(
															    [common_inputs["decoder_attention_mask"], torch.ones(a  ,     a		)]  ,     dim=1		)

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

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







	def      _lowerCamelCase       (      self	:str  ,     a	:PreTrainedTokenizer  ,     a	:int = -1  ,     a	:int = -1  ,     a	:bool = False  ,     a	:Optional[TensorType] = None  ,     )	->				Mapping[str, Any]:
								__UpperCamelCase			:     Optional[int]         =      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    a  ,     a  ,     a  ,     a  ,     a		)

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

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







	def      _lowerCamelCase       (      self	:Dict  ,     a	:PreTrainedTokenizer  ,     a	:int = -1  ,     a	:int = -1  ,     a	:bool = False  ,     a	:Optional[TensorType] = 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
								__UpperCamelCase			:     str         =      compute_effective_axis_dimension(
								    a  ,     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
								__UpperCamelCase			:     Any         =      tokenizer.num_special_tokens_to_add(a		)
								__UpperCamelCase			:     int         =      compute_effective_axis_dimension(
								    a  ,     fixed_dimension=OnnxConfig.default_fixed_sequence  ,     num_token_to_add=a		)

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







	def      _lowerCamelCase       (      self	:List[Any]  ,     a	:PreTrainedTokenizer  ,     a	:int = -1  ,     a	:int = -1  ,     a	:bool = False  ,     a	:Optional[TensorType] = None  ,     )	->				Mapping[str, Any]:
								if self.task in ["default", "seq2seq-lm"]:
															__UpperCamelCase			:     Tuple         =      self._generate_dummy_inputs_for_default_and_seqaseq_lm(
															    a  ,     batch_size=a  ,     seq_length=a  ,     is_pair=a  ,     framework=a		)

								elif self.task == "causal-lm":
															__UpperCamelCase			:     Any         =      self._generate_dummy_inputs_for_causal_lm(
															    a  ,     batch_size=a  ,     seq_length=a  ,     is_pair=a  ,     framework=a		)
								else:
															__UpperCamelCase			:     int         =      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
															    a  ,     batch_size=a  ,     seq_length=a  ,     is_pair=a  ,     framework=a		)

								return common_inputs







	def      _lowerCamelCase       (      self	:str  ,     a	:Any  ,     a	:Any  ,     a	:int  ,     a	:str		)	->				str:
								if self.task in ["default", "seq2seq-lm"]:
															__UpperCamelCase			:     Any         =      super()._flatten_past_key_values_(a  ,     a  ,     a  ,     a		)
								else:
															__UpperCamelCase			:     str         =      super(a  ,     self		)._flatten_past_key_values_(
															    a  ,     a  ,     a  ,     a		)

# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


lowercase						:      Any									= 'pytorch_model.bin'
lowercase						:      List[str]									= 'pytorch_model.bin.index.json'
lowercase						:      List[Any]									= 'adapter_config.json'
lowercase						:      str									= 'adapter_model.bin'
lowercase						:      List[str]									= 'adapter_model.safetensors'
lowercase						:      Any									= 'tf_model.h5'
lowercase						:      str									= 'tf_model.h5.index.json'
lowercase						:      Any									= 'model.ckpt'
lowercase						:      Optional[int]									= 'flax_model.msgpack'
lowercase						:      Dict									= 'flax_model.msgpack.index.json'
lowercase						:      Dict									= 'model.safetensors'
lowercase						:      Dict									= 'model.safetensors.index.json'
lowercase						:      Union[str, Any]									= 'config.json'
lowercase						:      Tuple									= 'preprocessor_config.json'
lowercase						:      Tuple									= FEATURE_EXTRACTOR_NAME
lowercase						:      Dict									= 'generation_config.json'
lowercase						:      Dict									= 'modelcard.json'

lowercase						:      Optional[int]									= '▁'
lowercase						:      Any									= SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

lowercase						:      List[Any]									= [
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
lowercase						:      Tuple									= [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
lowercase						:      Any									= [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Union[str, Any])      ->					List[str]:






							'''simple docstring'''





							if version.parse(_lowerCamelCase) < version.parse(_lowerCamelCase):
														if "dev" in min_version:
																					__UpperCamelCase			:     List[str]         =      (
																					    "This example requires a source install from HuggingFace Transformers (see "
																					    "`https://huggingface.co/docs/transformers/installation#install-from-source`),"
																					)
														else:
																					__UpperCamelCase			:     Optional[Any]         =      F'This example requires a minimum version of {min_version},'
														error_message += F' but the version found is {__version__}.\n'
														raise ImportError(
														    error_message
														    + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other "
														    "versions of HuggingFace Transformers.")