

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

a_						     =    {
    '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 _UpperCamelCase							(							snake_case__   ):
			'''simple docstring'''







			lowerCamelCase__           ="""blenderbot-small"""
			lowerCamelCase__           =["""past_key_values"""]
			lowerCamelCase__           ={"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}
			def __init__(			self							: Optional[Any]      ,      a							: int=5_0265      ,      a							: Dict=512      ,      a							: List[Any]=8      ,      a							: List[Any]=2048      ,      a							: Optional[Any]=16      ,      a							: List[str]=8      ,      a							: int=2048      ,      a							: Any=16      ,      a							: Tuple=0.0      ,      a							: str=0.0      ,      a							: Tuple=True      ,      a							: Union[str, Any]=True      ,      a							: List[str]="gelu"      ,      a							: Any=512      ,      a							: Union[str, Any]=0.1      ,      a							: Dict=0.0      ,      a							: Union[str, Any]=0.0      ,      a							: Optional[Any]=0.02      ,      a							: Any=1      ,      a							: Any=False      ,      a							: Optional[int]=0      ,      a							: str=1      ,      a							: List[Any]=2      ,      a							: Optional[Any]=2      ,      **a							: List[str]      ,      )							->       Optional[int]:

				"""simple docstring"""

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

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






class _UpperCamelCase							(							snake_case__   ):
			'''simple docstring'''







			@property
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Mapping[str, Mapping[int, str]]:

				"""simple docstring"""

				if self.task in ["default", "seq2seq-lm"]:
					SCREAMING_SNAKE_CASE   :      List[str]				     =       OrderedDict(
					    [
					        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
					        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
					    ]	)

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

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

				"""simple docstring"""

				if self.task in ["default", "seq2seq-lm"]:
					SCREAMING_SNAKE_CASE   :      str				     =       super().outputs
				else:
					SCREAMING_SNAKE_CASE   :      int				     =       super(UpperCAmelCase_      ,      self	).outputs
					if self.use_past:
						SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      str				     =       self.num_layers
						for i in range(UpperCAmelCase_	):
							SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       {0: "batch", 2: "past_sequence + sequence"}
							SCREAMING_SNAKE_CASE   :      Optional[int]				     =       {0: "batch", 2: "past_sequence + sequence"}
				return common_outputs
			def 							__UpperCamelCase (			self							: List[Any]      ,      a							: PreTrainedTokenizer      ,      a							: int = -1      ,      a							: int = -1      ,      a							: bool = False      ,      a							: Optional[TensorType] = None      ,      )							->       Mapping[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_	)

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

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

					SCREAMING_SNAKE_CASE   :      Optional[int]				     =       torch.cat(
					    [common_inputs["decoder_attention_mask"], torch.ones(UpperCAmelCase_      ,      UpperCAmelCase_	)]      ,      dim=1	)

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

					for _ in range(UpperCAmelCase_	):
						common_inputs["past_key_values"].append(
						    (
						        torch.zeros(UpperCAmelCase_	),
						        torch.zeros(UpperCAmelCase_	),
						        torch.zeros(UpperCAmelCase_	),
						        torch.zeros(UpperCAmelCase_	),
						    )	)
					# TODO: test this.
					SCREAMING_SNAKE_CASE   :      Dict				     =       encoder_shape if remaining_side_name == "encoder" else decoder_shape
					for _ in range(UpperCAmelCase_      ,      UpperCAmelCase_	):
						common_inputs["past_key_values"].append((torch.zeros(UpperCAmelCase_	), torch.zeros(UpperCAmelCase_	))	)
				return common_inputs
			def 							__UpperCamelCase (			self							: int      ,      a							: PreTrainedTokenizer      ,      a							: int = -1      ,      a							: int = -1      ,      a							: bool = False      ,      a							: Optional[TensorType] = None      ,      )							->       Mapping[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_	)

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

					SCREAMING_SNAKE_CASE   :      int				     =       common_inputs["attention_mask"].dtype
					SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       torch.cat(
					    [common_inputs["attention_mask"], torch.ones(UpperCAmelCase_      ,      UpperCAmelCase_      ,      dtype=UpperCAmelCase_	)]      ,      dim=1	)
					SCREAMING_SNAKE_CASE   :      List[str]				     =       [
					    (torch.zeros(UpperCAmelCase_	), torch.zeros(UpperCAmelCase_	)) for _ in range(UpperCAmelCase_	)
					]
				return common_inputs
			def 							__UpperCamelCase (			self							: Optional[Any]      ,      a							: PreTrainedTokenizer      ,      a							: int = -1      ,      a							: int = -1      ,      a							: bool = False      ,      a							: Optional[TensorType] = None      ,      )							->       Mapping[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       compute_effective_axis_dimension(
				    UpperCAmelCase_      ,      fixed_dimension=OnnxConfig.default_fixed_batch      ,      num_token_to_add=0	)

				# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
				SCREAMING_SNAKE_CASE   :      str				     =       tokenizer.num_special_tokens_to_add(UpperCAmelCase_	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       compute_effective_axis_dimension(
				    UpperCAmelCase_      ,      fixed_dimension=OnnxConfig.default_fixed_sequence      ,      num_token_to_add=UpperCAmelCase_	)

				# Generate dummy inputs according to compute batch and sequence
				SCREAMING_SNAKE_CASE   :      Any				     =       [" ".join([tokenizer.unk_token]	) * seq_length] * batch_size
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       dict(tokenizer(UpperCAmelCase_      ,      return_tensors=UpperCAmelCase_	)	)
				return common_inputs
			def 							__UpperCamelCase (			self							: Tuple      ,      a							: PreTrainedTokenizer      ,      a							: int = -1      ,      a							: int = -1      ,      a							: bool = False      ,      a							: Optional[TensorType] = None      ,      )							->       Mapping[str, Any]:

				"""simple docstring"""

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

				elif self.task == "causal-lm":
					SCREAMING_SNAKE_CASE   :      Tuple				     =       self._generate_dummy_inputs_for_causal_lm(
					    UpperCAmelCase_      ,      batch_size=UpperCAmelCase_      ,      seq_length=UpperCAmelCase_      ,      is_pair=UpperCAmelCase_      ,      framework=UpperCAmelCase_	)
				else:
					SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
					    UpperCAmelCase_      ,      batch_size=UpperCAmelCase_      ,      seq_length=UpperCAmelCase_      ,      is_pair=UpperCAmelCase_      ,      framework=UpperCAmelCase_	)

				return common_inputs






			def 							__UpperCamelCase (			self							: Tuple      ,      a							: Optional[int]      ,      a							: Any      ,      a							: List[str]      ,      a							: Optional[Any]	)							->       Optional[int]:

				"""simple docstring"""

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


from dataclasses import dataclass
from typing import Optional

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin






@dataclass
class _UpperCamelCase							(							__A   ):
			'''simple docstring'''







			lowerCamelCase__           =42






class _UpperCamelCase							(							__A							,	__A   ):
			'''simple docstring'''







			@register_to_config
			def __init__(			self							: str      ,      a							: int = 16      ,      a							: int = 88      ,      a							: Optional[int] = None      ,      a							: Optional[int] = None      ,      a							: int = 1      ,      a							: float = 0.0      ,      a							: int = 32      ,      a							: Optional[int] = None      ,      a							: bool = False      ,      a							: Optional[int] = None      ,      a							: str = "geglu"      ,      a							: bool = True      ,      a							: bool = True      ,      )							->       str:

				"""simple docstring"""

				super().__init__()
				SCREAMING_SNAKE_CASE   :      str				     =       num_attention_heads
				SCREAMING_SNAKE_CASE   :      Tuple				     =       attention_head_dim
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       num_attention_heads * attention_head_dim

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       in_channels

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       torch.nn.GroupNorm(num_groups=a      ,      num_channels=a      ,      eps=1e-6      ,      affine=a	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       nn.Linear(a      ,      a	)

				# 3. Define transformers blocks
				SCREAMING_SNAKE_CASE   :      List[str]				     =       nn.ModuleList(
				    [
				        BasicTransformerBlock(
				            a      ,      a      ,      a      ,      dropout=a      ,      cross_attention_dim=a      ,      activation_fn=a      ,      attention_bias=a      ,      double_self_attention=a      ,      norm_elementwise_affine=a      ,      )
				        for d in range(a	)
				    ]	)

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       nn.Linear(a      ,      a	)






			def 							__UpperCamelCase (			self							: Any      ,      a							: int      ,      a							: Optional[int]=None      ,      a							: List[str]=None      ,      a							: List[str]=None      ,      a							: Union[str, Any]=1      ,      a							: Any=None      ,      a							: bool = True      ,      )							->       Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      Any				     =       hidden_states.shape
				SCREAMING_SNAKE_CASE   :      Any				     =       batch_frames // num_frames

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       hidden_states

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       hidden_states[None, :].reshape(a      ,      a      ,      a      ,      a      ,      a	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       hidden_states.permute(0      ,      2      ,      1      ,      3      ,      4	)

				SCREAMING_SNAKE_CASE   :      Tuple				     =       self.norm(a	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       hidden_states.permute(0      ,      3      ,      4      ,      2      ,      1	).reshape(batch_size * height * width      ,      a      ,      a	)

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       self.proj_in(a	)

				# 2. Blocks
				for block in self.transformer_blocks:
					SCREAMING_SNAKE_CASE   :      Optional[int]				     =       block(
					    a      ,      encoder_hidden_states=a      ,      timestep=a      ,      cross_attention_kwargs=a      ,      class_labels=a      ,      )

				# 3. Output
				SCREAMING_SNAKE_CASE   :      List[str]				     =       self.proj_out(a	)
				SCREAMING_SNAKE_CASE   :      int				     =       (
				    hidden_states[None, None, :]
				    .reshape(a      ,      a      ,      a      ,      a      ,      a	)
				    .permute(0      ,      3      ,      4      ,      1      ,      2	)
				    .contiguous()
				)
				SCREAMING_SNAKE_CASE   :      Dict				     =       hidden_states.reshape(a      ,      a      ,      a      ,      a	)

				SCREAMING_SNAKE_CASE   :      int				     =       hidden_states + residual

				if not return_dict:
					return (output,)

				return TransformerTemporalModelOutput(sample=a	)