

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


_a:      Any								=     logging.get_logger(__name__)

_a:      int								=     {
    """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      (   lowercase  ):
	SCREAMING_SNAKE_CASE__      			=       'blenderbot'
	SCREAMING_SNAKE_CASE__      			=       ['past_key_values']
	SCREAMING_SNAKE_CASE__      			=       {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}




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


		'''simple docstring'''







		UpperCAmelCase_    			=     vocab_size
		UpperCAmelCase_    			=     max_position_embeddings
		UpperCAmelCase_    			=     d_model
		UpperCAmelCase_    			=     encoder_ffn_dim
		UpperCAmelCase_    			=     encoder_layers
		UpperCAmelCase_    			=     encoder_attention_heads
		UpperCAmelCase_    			=     decoder_ffn_dim
		UpperCAmelCase_    			=     decoder_layers
		UpperCAmelCase_    			=     decoder_attention_heads
		UpperCAmelCase_    			=     dropout
		UpperCAmelCase_    			=     attention_dropout
		UpperCAmelCase_    			=     activation_dropout
		UpperCAmelCase_    			=     activation_function
		UpperCAmelCase_    			=     init_std
		UpperCAmelCase_    			=     encoder_layerdrop
		UpperCAmelCase_    			=     decoder_layerdrop
		UpperCAmelCase_    			=     use_cache
		UpperCAmelCase_    			=     encoder_layers
		UpperCAmelCase_    			=     scale_embedding  # scale factor will be sqrt(d_model) if True

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


class   __UpperCamelCase      (   lowercase  ):




	@property
	def  __A   (						self		:  Any							):


		'''simple docstring'''







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


		'''simple docstring'''







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




	def  __A   (						self		:  List[str]						,		lowerCAmelCase		:  PreTrainedTokenizer						,		lowerCAmelCase		:  int = -1						,		lowerCAmelCase		:  int = -1						,		lowerCAmelCase		:  bool = False						,		lowerCAmelCase		:  Optional[TensorType] = None						,		):


		'''simple docstring'''







		UpperCAmelCase_    			=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
		    lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase							)
		# Generate decoder inputs
		UpperCAmelCase_    			=     seq_length if not self.use_past else 1
		UpperCAmelCase_    			=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
		    lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase							)
		UpperCAmelCase_    			=     {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
		UpperCAmelCase_    			=     dict(**lowerCAmelCase						,		**lowerCAmelCase							)

		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_    			=     common_inputs["input_ids"].shape
			UpperCAmelCase_    			=     common_inputs["decoder_input_ids"].shape[1]
			UpperCAmelCase_			,				UpperCAmelCase_    			=     self.num_attention_heads
			UpperCAmelCase_    			=     (
			    batch,
			    num_encoder_attention_heads,
			    encoder_seq_length,
			    self._config.hidden_size // num_encoder_attention_heads,
			)
			UpperCAmelCase_    			=     decoder_seq_length
			UpperCAmelCase_    			=     (
			    batch,
			    num_decoder_attention_heads,
			    decoder_past_length,
			    self._config.hidden_size // num_decoder_attention_heads,
			)
			UpperCAmelCase_    			=     torch.cat(
			    [common_inputs["decoder_attention_mask"], torch.ones(lowerCAmelCase						,		lowerCAmelCase							)]						,		dim=1							)
			UpperCAmelCase_    			=     []
			UpperCAmelCase_			,				UpperCAmelCase_    			=     self.num_layers

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




	def  __A   (						self		:  List[str]						,		lowerCAmelCase		:  PreTrainedTokenizer						,		lowerCAmelCase		:  int = -1						,		lowerCAmelCase		:  int = -1						,		lowerCAmelCase		:  bool = False						,		lowerCAmelCase		:  Optional[TensorType] = None						,		):


		'''simple docstring'''







		UpperCAmelCase_    			=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
		    lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase							)

		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_    			=     common_inputs["input_ids"].shape
			UpperCAmelCase_    			=     seqlen
			UpperCAmelCase_			,				UpperCAmelCase_    			=     self.num_layers
			UpperCAmelCase_			,				UpperCAmelCase_    			=     self.num_attention_heads
			UpperCAmelCase_    			=     (
			    batch,
			    num_encoder_attention_heads,
			    past_key_values_length,
			    self._config.hidden_size // num_encoder_attention_heads,
			)
			UpperCAmelCase_    			=     common_inputs["attention_mask"].dtype
			UpperCAmelCase_    			=     torch.cat(
			    [common_inputs["attention_mask"], torch.ones(lowerCAmelCase						,		lowerCAmelCase						,		dtype=lowerCAmelCase							)]						,		dim=1							)
			UpperCAmelCase_    			=     [
			    (torch.zeros(lowerCAmelCase							), torch.zeros(lowerCAmelCase							)) for _ in range(lowerCAmelCase							)
			]
		return common_inputs




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


		'''simple docstring'''







		UpperCAmelCase_    			=     compute_effective_axis_dimension(
		    lowerCAmelCase						,		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_    			=     tokenizer.num_special_tokens_to_add(lowerCAmelCase							)
		UpperCAmelCase_    			=     compute_effective_axis_dimension(
		    lowerCAmelCase						,		fixed_dimension=OnnxConfig.default_fixed_sequence						,		num_token_to_add=lowerCAmelCase							)

		# Generate dummy inputs according to compute batch and sequence
		UpperCAmelCase_    			=     [" ".join([tokenizer.unk_token]							) * seq_length] * batch_size
		UpperCAmelCase_    			=     dict(tokenizer(lowerCAmelCase						,		return_tensors=lowerCAmelCase							)							)
		return common_inputs




	def  __A   (						self		:  str						,		lowerCAmelCase		:  PreTrainedTokenizer						,		lowerCAmelCase		:  int = -1						,		lowerCAmelCase		:  int = -1						,		lowerCAmelCase		:  bool = False						,		lowerCAmelCase		:  Optional[TensorType] = None						,		):


		'''simple docstring'''







		if self.task in ["default", "seq2seq-lm"]:
			UpperCAmelCase_    			=     self._generate_dummy_inputs_for_default_and_seqaseq_lm(
			    lowerCAmelCase						,		batch_size=lowerCAmelCase						,		seq_length=lowerCAmelCase						,		is_pair=lowerCAmelCase						,		framework=lowerCAmelCase							)

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

		return common_inputs




	def  __A   (						self		:  List[str]						,		lowerCAmelCase		:  Tuple						,		lowerCAmelCase		:  int						,		lowerCAmelCase		:  Tuple						,		lowerCAmelCase		:  Any							):


		'''simple docstring'''







		if self.task in ["default", "seq2seq-lm"]:
			UpperCAmelCase_    			=     super()._flatten_past_key_values_(lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase							)
		else:
			UpperCAmelCase_    			=     super(lowerCAmelCase						,		self							)._flatten_past_key_values_(
			    lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase							)




	def  __A   (						self		:  str						,		lowerCAmelCase		:  Mapping[str, Mapping[int, str]]						,		lowerCAmelCase		:  str							):


		'''simple docstring'''







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

		UpperCAmelCase_    			=     "past_key_values" if direction == "inputs" else "present"
		UpperCAmelCase_			,				UpperCAmelCase_    			=     self.num_layers

		UpperCAmelCase_    			=     "past_encoder_sequence"
		UpperCAmelCase_    			=     "past_decoder_sequence" if direction == "inputs" else "past_decoder_sequence + sequence"

		for i in range(lowerCAmelCase							):
			UpperCAmelCase_    			=     {0: "batch", 2: decoder_sequence}
			UpperCAmelCase_    			=     {0: "batch", 2: decoder_sequence}
			UpperCAmelCase_    			=     {0: "batch", 2: encoder_sequence}
			UpperCAmelCase_    			=     {0: "batch", 2: encoder_sequence}


import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
				import torch_xla.core.xla_model as xm  # noqa: F401

				_a:      List[Any]								=     True
except ImportError:
				_a:      int								=     False


# Cache this result has it's a C FFI call which can be pretty time-consuming
_a:      str								=     torch.distributed.is_available()



def  __lowerCAmelCase (  A      ):
	# Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
	UpperCAmelCase_    			=     importlib.util.find_spec(A      ) is not None
	if package_exists:
		try:
			UpperCAmelCase_    			=     importlib.metadata.metadata(A      )
			return True
		except importlib.metadata.PackageNotFoundError:
			return False



def  __lowerCAmelCase (  ):
	return _torch_distributed_available



def  __lowerCAmelCase (  ):
	try:
		pass
	except ImportError:
		print(
		    "Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not"
		    " detected. If you see \"ValueError: Invalid backend: 'ccl'\" error, please install Intel(R) oneCCL"
		    " Bindings for PyTorch*."      )
	return (
	    importlib.util.find_spec("torch_ccl"      ) is not None
	    or importlib.util.find_spec("oneccl_bindings_for_pytorch"      ) is not None
	)



def  __lowerCAmelCase (  ):
	return importlib.metadata.version("oneccl_bind_pt"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("transformer_engine"      )



@lru_cache
def  __lowerCAmelCase (  A=True      ):
	# Due to bugs on the amp series GPUs, we disable torch-xla on them
	if torch.cuda.is_available():
		return False
	if _tpu_available and check_device:
		try:
			# Will raise a RuntimeError if no XLA configuration is found
			UpperCAmelCase_    			=     xm.xla_device()
			return True
		except RuntimeError:
			return False
	return _tpu_available



def  __lowerCAmelCase (  ):
	return _is_package_available("deepspeed"      )



def  __lowerCAmelCase (  A=False      ):
	if is_tpu_available():
		return not ignore_tpu
	if torch.cuda.is_available():
		return torch.cuda.is_bfaa_supported()
	if is_npu_available():
		return False
	return True



def  __lowerCAmelCase (  ):
	UpperCAmelCase_    			=     _is_package_available("bitsandbytes"      )
	if package_exists:
		UpperCAmelCase_    			=     version.parse(importlib.metadata.version("bitsandbytes"      )      )
		return compare_versions(A    ,       ">="    ,       "0.39.0"      )
	return False



def  __lowerCAmelCase (  ):
	UpperCAmelCase_    			=     _is_package_available("bitsandbytes"      )
	if package_exists:
		UpperCAmelCase_    			=     version.parse(importlib.metadata.version("bitsandbytes"      )      )
		return compare_versions(A    ,       ">="    ,       "0.37.2"      )
	return False



def  __lowerCAmelCase (  ):
	return _is_package_available("bitsandbytes"      )



def  __lowerCAmelCase (  ):
	if strtobool(os.environ.get("ACCELERATE_USE_MEGATRON_LM"    ,       "False"      )      ) == 1:
		UpperCAmelCase_    			=     importlib.util.find_spec("megatron"      ) is not None
		if package_exists:
			try:
				UpperCAmelCase_    			=     parse(importlib.metadata.version("megatron-lm"      )      )
				return compare_versions(A    ,       ">="    ,       "2.2.0"      )
			except Exception as e:
				warnings.warn(F"Parse Megatron version failed. Exception:{e}"      )
				return False



def  __lowerCAmelCase (  ):
	return _is_package_available("safetensors"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("transformers"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("datasets"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("aim"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("tensorboard"      ) or _is_package_available("tensorboardX"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("wandb"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("comet_ml"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("boto3"      )



def  __lowerCAmelCase (  ):
	if _is_package_available("rich"      ):
		if "ACCELERATE_DISABLE_RICH" in os.environ:
			warnings.warn(
			    "`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`."      )
			return not parse_flag_from_env("ACCELERATE_DISABLE_RICH"    ,       A      )
		return parse_flag_from_env("ACCELERATE_ENABLE_RICH"    ,       A      )
	return False



def  __lowerCAmelCase (  ):
	return _is_package_available("sagemaker"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("tqdm"      )



def  __lowerCAmelCase (  ):
	return _is_package_available("mlflow"      )



def  __lowerCAmelCase (  ):
	return is_torch_version(">="    ,       "1.12"      ) and torch.backends.mps.is_available() and torch.backends.mps.is_built()



def  __lowerCAmelCase (  ):
	def get_major_and_minor_from_version(A      ):
		return str(version.parse(A      ).major      ) + "." + str(version.parse(A      ).minor      )

	UpperCAmelCase_    			=     importlib.metadata.version("torch"      )
	if importlib.util.find_spec("intel_extension_for_pytorch"      ) is None:
		return False
	UpperCAmelCase_    			=     "N/A"
	try:
		UpperCAmelCase_    			=     importlib.metadata.version("intel_extension_for_pytorch"      )
	except importlib.metadata.PackageNotFoundError:
		return False
	UpperCAmelCase_    			=     get_major_and_minor_from_version(_torch_version      )
	UpperCAmelCase_    			=     get_major_and_minor_from_version(_ipex_version      )
	if torch_major_and_minor != ipex_major_and_minor:
		warnings.warn(
		    F"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
		    F" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."      )
		return False
	return True



@lru_cache
def  __lowerCAmelCase (  A=False      ):
	if importlib.util.find_spec("torch"      ) is None or importlib.util.find_spec("torch_npu"      ) is None:
		return False

	import torch
	import torch_npu  # noqa: F401

	if check_device:
		try:
			# Will raise a RuntimeError if no NPU is found
			UpperCAmelCase_    			=     torch.npu.device_count()
			return torch.npu.is_available()
		except RuntimeError:
			return False
	return hasattr(A    ,       "npu"      ) and torch.npu.is_available()




@lru_cache
def  __lowerCAmelCase (  A=False      ):
	if not parse_flag_from_env("ACCELERATE_USE_XPU"    ,       default=A      ):
		return False
	if is_ipex_available():
		import torch

		if is_torch_version("<="    ,       "1.12"      ):
			return False
	else:
		return False

	import intel_extension_for_pytorch  # noqa: F401

	if check_device:
		try:
			# Will raise a RuntimeError if no XPU  is found
			UpperCAmelCase_    			=     torch.xpu.device_count()
			return torch.xpu.is_available()
		except RuntimeError:
			return False
	return hasattr(A    ,       "xpu"      ) and torch.xpu.is_available()