


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__     							= logging.get_logger(__name__)

lowercase__     							= {
    '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     snake_case__  (      lowerCamelCase__  ):
				__lowerCAmelCase		=      'blenderbot'
				__lowerCAmelCase		=      ['past_key_values']
				__lowerCAmelCase		=      {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
				def __init__(  self     ,      _UpperCAmelCase=8008     ,      _UpperCAmelCase=128     ,      _UpperCAmelCase=2     ,      _UpperCAmelCase=1_0240     ,      _UpperCAmelCase=32     ,      _UpperCAmelCase=24     ,      _UpperCAmelCase=1_0240     ,      _UpperCAmelCase=32     ,      _UpperCAmelCase=0.0     ,      _UpperCAmelCase=0.0     ,      _UpperCAmelCase=True     ,      _UpperCAmelCase=True     ,      _UpperCAmelCase="gelu"     ,      _UpperCAmelCase=2560     ,      _UpperCAmelCase=0.1     ,      _UpperCAmelCase=0.0     ,      _UpperCAmelCase=0.0     ,      _UpperCAmelCase=0.02     ,      _UpperCAmelCase=1     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=0     ,      _UpperCAmelCase=1     ,      _UpperCAmelCase=2     ,      _UpperCAmelCase=3     ,      _UpperCAmelCase=2     ,      **_UpperCAmelCase     ,      ):




										"""simple docstring"""




										__magic_name__				:							List[str]				=      vocab_size
										__magic_name__				:							Any				=      max_position_embeddings
										__magic_name__				:							Optional[Any]				=      d_model
										__magic_name__				:							List[Any]				=      encoder_ffn_dim
										__magic_name__				:							Dict				=      encoder_layers
										__magic_name__				:							Optional[Any]				=      encoder_attention_heads
										__magic_name__				:							int				=      decoder_ffn_dim
										__magic_name__				:							Tuple				=      decoder_layers
										__magic_name__				:							List[Any]				=      decoder_attention_heads
										__magic_name__				:							str				=      dropout
										__magic_name__				:							List[Any]				=      attention_dropout
										__magic_name__				:							Union[str, Any]				=      activation_dropout
										__magic_name__				:							int				=      activation_function
										__magic_name__				:							Any				=      init_std
										__magic_name__				:							str				=      encoder_layerdrop
										__magic_name__				:							int				=      decoder_layerdrop
										__magic_name__				:							Dict				=      use_cache
										__magic_name__				:							Union[str, Any]				=      encoder_layers
										__magic_name__				:							str				=      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     snake_case__  (      lowerCamelCase__  ):
				@property
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										if self.task in ["default", "seq2seq-lm"]:
																__magic_name__				:							str				=      OrderedDict(
																    [
																        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																    ]      )
																if self.use_past:
																						__magic_name__				:							int				=      {0: 'batch'}
																						__magic_name__				:							Optional[Any]				=      {0: 'batch', 1: 'past_decoder_sequence + sequence'}
																else:
																						__magic_name__				:							Any				=      {0: 'batch', 1: 'decoder_sequence'}
																						__magic_name__				:							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":
																__magic_name__				:							List[str]				=      OrderedDict(
																    [
																        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																    ]      )
																if self.use_past:
																						__magic_name__		, __magic_name__				:							int				=      self.num_layers
																						for i in range(lowercase_      ):
																												__magic_name__				:							Optional[int]				=      {0: 'batch', 2: 'past_sequence + sequence'}
																												__magic_name__				:							Any				=      {0: 'batch', 2: 'past_sequence + sequence'}
										else:
																__magic_name__				:							Optional[int]				=      OrderedDict(
																    [
																        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																        ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
																        ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
																    ]      )

										return common_inputs
				@property
				# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										if self.task in ["default", "seq2seq-lm"]:
																__magic_name__				:							str				=      super().outputs
										else:
																__magic_name__				:							Dict				=      super(lowercase_     ,      self      ).outputs
																if self.use_past:
																						__magic_name__		, __magic_name__				:							Dict				=      self.num_layers
																						for i in range(lowercase_      ):
																												__magic_name__				:							int				=      {0: 'batch', 2: 'past_sequence + sequence'}
																												__magic_name__				:							Optional[int]				=      {0: 'batch', 2: 'past_sequence + sequence'}
										return common_outputs
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase = -1     ,      _UpperCAmelCase = -1     ,      _UpperCAmelCase = False     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




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




										"""simple docstring"""




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




										"""simple docstring"""




										__magic_name__				:							List[str]				=      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
										__magic_name__				:							List[str]				=      tokenizer.num_special_tokens_to_add(lowercase_      )
										__magic_name__				:							str				=      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
										__magic_name__				:							str				=      [' '.join([tokenizer.unk_token]      ) * seq_length] * batch_size
										__magic_name__				:							Union[str, Any]				=      dict(tokenizer(lowercase_     ,      return_tensors=lowercase_      )      )
										return common_inputs
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase = -1     ,      _UpperCAmelCase = -1     ,      _UpperCAmelCase = False     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




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




										"""simple docstring"""




										if self.task in ["default", "seq2seq-lm"]:
																__magic_name__				:							List[Any]				=      super()._flatten_past_key_values_(lowercase_     ,      lowercase_     ,      lowercase_     ,      lowercase_      )
										else:
																__magic_name__				:							Union[str, Any]				=      super(lowercase_     ,      self      )._flatten_past_key_values_(
																    lowercase_     ,      lowercase_     ,      lowercase_     ,      lowercase_      )





				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




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

										__magic_name__				:							int				=      'past_key_values' if direction == 'inputs' else 'present'
										__magic_name__		, __magic_name__				:							Union[str, Any]				=      self.num_layers

										__magic_name__				:							Optional[int]				=      'past_encoder_sequence'
										__magic_name__				:							Dict				=      'past_decoder_sequence' if direction == 'inputs' else 'past_decoder_sequence + sequence'

										for i in range(lowercase_      ):
																__magic_name__				:							str				=      {0: 'batch', 2: decoder_sequence}
																__magic_name__				:							List[Any]				=      {0: 'batch', 2: decoder_sequence}
																__magic_name__				:							Optional[int]				=      {0: 'batch', 2: encoder_sequence}
																__magic_name__				:							Optional[int]				=      {0: 'batch', 2: encoder_sequence}






import dataclasses
import enum
import functools
import math
import re

# The following script is adapted from the script of TaPas.
# Original: https://github.com/google-research/tapas/master/wikisql_utils.py
from typing import Any, List, Text


snake_case__     							= 'none'
snake_case__     							= 'none'
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :List[str]      ,						lowercase__  :Optional[Any]				)       ->  List[str]:
						__magic_name__				:							Dict				=      value.split(lowercase__				)
						return len(lowercase__				) > 1 and any((len(lowercase__				) == 3 for x in split)				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :List[Any]				)       ->  List[str]:
						if isinstance(lowercase__      ,						lowercase__				):
												return value
						if isinstance(lowercase__      ,						lowercase__				):
												return float(lowercase__				)
						if not isinstance(lowercase__      ,						lowercase__				):
												raise ValueError('Argument value is not a string. Can\'t parse it as float'				)
						__magic_name__				:							List[str]				=      value

						try:
												# Example: 1,000.7
												if "." in sanitized and "," in sanitized:
																		return float(sanitized.replace(','      ,						''				)				)
												# 1,000
												if "," in sanitized and _split_thousands(','      ,						lowercase__				):
																		return float(sanitized.replace(','      ,						''				)				)
												# 5,5556
												if "," in sanitized and sanitized.count(','				) == 1 and not _split_thousands(','      ,						lowercase__				):
																		return float(sanitized.replace(','      ,						'.'				)				)
												# 0.0.0.1
												if sanitized.count('.'				) > 1:
																		return float(sanitized.replace('.'      ,						''				)				)
												# 0,0,0,1
												if sanitized.count(','				) > 1:
																		return float(sanitized.replace(','      ,						''				)				)
												return float(lowercase__				)
						except ValueError:
												# Avoid adding the sanitized value in the error message.
												raise ValueError('Unable to convert value to float'				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Tuple				)       ->  Tuple:
						if answer is None:
												return None
						try:
												__magic_name__				:							Any				=      convert_to_float(lowercase__				)
												if isinstance(lowercase__      ,						lowercase__				) and math.isnan(lowercase__				):
																		return None
												return value
						except ValueError:
												return answer.lower()


snake_case__     							= {
    'text': lambda x: x,
    'real': convert_to_float,
}



class     snake_case__  (      enum.Enum  ):
				__lowerCAmelCase		=      0
				__lowerCAmelCase		=      1
				__lowerCAmelCase		=      2
				__lowerCAmelCase		=      3
				__lowerCAmelCase		=      4
				__lowerCAmelCase		=      5






class     snake_case__  (      enum.Enum  ):
				__lowerCAmelCase		=      0
				__lowerCAmelCase		=      1
				__lowerCAmelCase		=      2






@dataclasses.dataclass
class     snake_case__  :
				__lowerCAmelCase		=      42
				__lowerCAmelCase		=      42
				__lowerCAmelCase		=      42






snake_case__     							= re.compile(R'\w+|[^\w\s]+', re.UNICODE | re.MULTILINE | re.DOTALL)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Any				)       ->  str:
						return list(_TOKENIZER.findall(x.lower()				)				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :str      ,						lowercase__  :str      ,						lowercase__  :Dict				)       ->  Dict:
						if operator == _Operator.EQUALS:
												return src == tgt
						elif operator == _Operator.GREATER:
												return src > tgt
						elif operator == _Operator.LESSER:
												return src < tgt
						raise ValueError(f"Unknown operator: {operator}"				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :List[Any]      ,						lowercase__  :Tuple      ,						lowercase__  :Union[str, Any]				)       ->  Optional[int]:
						__magic_name__				:							str				=      table['types']
						return _TYPE_CONVERTER[types[column]](lowercase__				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Tuple				)       ->  Union[str, Any]:
						return isinstance(lowercase__      ,						lowercase__				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :List[Any]      ,						lowercase__  :List[str]      ,						lowercase__  :int				)       ->  str:
						for cond in conditions:
												__magic_name__				:							Optional[Any]				=      row[cond.column]

												__magic_name__				:							List[str]				=      _parse_value(lowercase__      ,						cond.column      ,						cond.cmp_value				)

												if _is_string(lowercase__				) and _is_string(lowercase__				):
																		__magic_name__				:							str				=      _normalize_for_match(lowercase__				)
																		__magic_name__				:							List[str]				=      _normalize_for_match(lowercase__				)

												if not isinstance(lowercase__      ,						type(lowercase__				)				):
																		raise ValueError('Type difference {} != {}'.format(type(lowercase__				)      ,						type(lowercase__				)				)				)

												if not _compare(cond.operator      ,						lowercase__      ,						lowercase__				):
																		return False
						return True
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :str      ,						lowercase__  :List[Any]      ,						lowercase__  :List[Any]				)       ->  int:
						if not answer_coordinates:
												if aggregation_op == _Aggregation.COUNT:
																		return 0.0
												else:
																		return EMPTY_ANSWER_AGG

    # Count can support non numeric answers.
						if aggregation_op == _Aggregation.COUNT:
												return float(len(lowercase__				)				)

						# If we have just one answer, if float returns it or try a conversion.
						__magic_name__				:							Any				=      [table['rows'][i][j] for (i, j) in answer_coordinates]
						if len(lowercase__				) == 1:
												try:
																		return convert_to_float(values[0]				)
												except ValueError as e:
																		if aggregation_op != _Aggregation.NONE:
																								raise e

						if aggregation_op == _Aggregation.NONE:
												return None

						# Other aggregation only support numeric values. Bail out if we have strings.
						if not all((isinstance(lowercase__      ,						(int, float)				) for v in values)				):
												return None

						if aggregation_op == _Aggregation.SUM:
												return float(sum(lowercase__				)				)
						elif aggregation_op == _Aggregation.AVERAGE:
												return sum(lowercase__				) / len(lowercase__				)
						else:
												raise ValueError(f"Unknown aggregation: {aggregation_op}"				)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Tuple      ,						lowercase__  :Any				)       ->  Optional[int]:
						__magic_name__				:							Optional[Any]				=      sql_query['agg']
						if aggregation_op_index >= 3:
												__magic_name__				:							Any				=      _Aggregation(lowercase__				)
						else:
												__magic_name__				:							int				=      _Aggregation.NONE

						__magic_name__				:							str				=      sql_query['sel']
						__magic_name__				:							Any				=      [
						    _Condition(lowercase__      ,						_Operator(lowercase__				)      ,						lowercase__				)
						    for column, operator, cmp_value in zip(
						        sql_query['conds']['column_index']      ,						sql_query['conds']['operator_index']      ,						sql_query['conds']['condition']				)
						]

						__magic_name__				:							Any				=      []
						for row in range(len(table['rows']				)				):
												if _respect_conditions(lowercase__      ,						table['rows'][row]      ,						lowercase__				):
																		indices.append((row, target_column)				)

						if not indices:
												return [], aggregation_op

						if len(lowercase__				) == 1:
												return indices, aggregation_op

						# Parsing of MIN/MAX.
						if aggregation_op_index in (1, 2):
												__magic_name__				:							str				=      {2: min, 1: max}
												__magic_name__				:							Optional[int]				=      [(table['rows'][i][j], index) for index, (i, j) in enumerate(lowercase__				)]
												__magic_name__				:							str				=      functools.reduce(operators[sql_query['agg']]      ,						lowercase__				)

												__magic_name__				:							List[Any]				=      [indices[reduced[1]]]
												return ret, _Aggregation.NONE

						return indices, aggregation_op
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Tuple      ,						lowercase__  :Any      ,						lowercase__  :Optional[int]				)       ->  List[Any]:
						if float_answer is not None:
												return [str(lowercase__				)]
						return [str(table['real_rows'][r][c]				) for r, c in answer_coordinates]

def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Optional[Any]      ,						lowercase__  :Union[str, Any]				)       ->  List:
						__magic_name__		, __magic_name__				:							List[Any]				=      _get_answer_coordinates(lowercase__      ,						lowercase__				)
						__magic_name__				:							List[Any]				=      _get_float_answer(lowercase__      ,						lowercase__      ,						lowercase__				)
						__magic_name__				:							Any				=      _get_answer_text(lowercase__      ,						lowercase__      ,						lowercase__				)
						# keep the original data the same with TaPas
						if len(lowercase__				) == 0:
												__magic_name__				:							int				=      [EMPTY_ANSWER]
						return answer_text


