





"""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_					:						Union[str, Any]      = logging.get_logger(__name__)

lowerCamelCase_					:						List[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 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_				:			Optional[int]        =       """blenderbot"""
      lowercase_				:			Any        =       ["""past_key_values"""]
      lowercase_				:			int        =       {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}

      def __init__(					self ,				snake_case_=8_0_0_8 ,				snake_case_=1_2_8 ,				snake_case_=2 ,				snake_case_=1_0_2_4_0 ,				snake_case_=3_2 ,				snake_case_=2_4 ,				snake_case_=1_0_2_4_0 ,				snake_case_=3_2 ,				snake_case_=0.0 ,				snake_case_=0.0 ,				snake_case_=True ,				snake_case_=True ,				snake_case_="gelu" ,				snake_case_=2_5_6_0 ,				snake_case_=0.1 ,				snake_case_=0.0 ,				snake_case_=0.0 ,				snake_case_=0.02 ,				snake_case_=1 ,				snake_case_=False ,				snake_case_=0 ,				snake_case_=1 ,				snake_case_=2 ,				snake_case_=3 ,				snake_case_=2 ,				**snake_case_ ,				):

        """simple docstring"""

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

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


class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
          A_  :	List[str]    						=  super().outputs
        else:
          A_  :	int    						=  super(snake_case_ ,				self  ).outputs
          if self.use_past:
            A_						,	A_  :	Any    						=  self.num_layers
            for i in range(snake_case_  ):
              A_  :	Any    						=  {0: 'batch', 2: 'past_sequence + sequence'}
              A_  :	Dict    						=  {0: 'batch', 2: 'past_sequence + sequence'}
        return common_outputs

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				):

        """simple docstring"""

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

        if self.use_past:
          if not is_torch_available():
            raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'  )
          else:
            import torch
          A_						,	A_  :	Any    						=  common_inputs['input_ids'].shape
          A_  :	str    						=  common_inputs['decoder_input_ids'].shape[1]
          A_						,	A_  :	Union[str, Any]    						=  self.num_attention_heads
          A_  :	int    						=  (
              batch,
              num_encoder_attention_heads,
              encoder_seq_length,
              self._config.hidden_size // num_encoder_attention_heads,
          )
          A_  :	int    						=  decoder_seq_length
          A_  :	int    						=  (
              batch,
              num_decoder_attention_heads,
              decoder_past_length,
              self._config.hidden_size // num_decoder_attention_heads,
          )
          A_  :	Tuple    						=  torch.cat(
              [common_inputs['decoder_attention_mask'], torch.ones(snake_case_ ,				snake_case_  )] ,				dim=1  )
          A_  :	str    						=  []
          A_						,	A_  :	Union[str, Any]    						=  self.num_layers

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

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				):

        """simple docstring"""

        A_  :	List[Any]    						=  self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_  )

        if self.use_past:
          if not is_torch_available():
            raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'  )
          else:
            import torch
          A_						,	A_  :	Union[str, Any]    						=  common_inputs['input_ids'].shape
          A_  :	str    						=  seqlen
          A_						,	A_  :	List[str]    						=  self.num_layers
          A_						,	A_  :	int    						=  self.num_attention_heads
          A_  :	Any    						=  (
              batch,
              num_encoder_attention_heads,
              past_key_values_length,
              self._config.hidden_size // num_encoder_attention_heads,
          )
          A_  :	str    						=  common_inputs['attention_mask'].dtype
          A_  :	List[str]    						=  torch.cat(
              [common_inputs['attention_mask'], torch.ones(snake_case_ ,				snake_case_ ,				dtype=snake_case_  )] ,				dim=1  )
          A_  :	str    						=  [
              (torch.zeros(snake_case_  ), torch.zeros(snake_case_  )) for _ in range(snake_case_  )
          ]
        return common_inputs

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				):

        """simple docstring"""

        A_  :	Tuple    						=  compute_effective_axis_dimension(
            snake_case_ ,				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
        A_  :	str    						=  tokenizer.num_special_tokens_to_add(snake_case_  )
        A_  :	Any    						=  compute_effective_axis_dimension(
            snake_case_ ,				fixed_dimension=OnnxConfig.default_fixed_sequence ,				num_token_to_add=snake_case_  )

        # Generate dummy inputs according to compute batch and sequence
        A_  :	int    						=  [' '.join([tokenizer.unk_token]  ) * seq_length] * batch_size
        A_  :	Any    						=  dict(tokenizer(snake_case_ ,				return_tensors=snake_case_  )  )
        return common_inputs

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				):

        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
          A_  :	List[str]    						=  self._generate_dummy_inputs_for_default_and_seqaseq_lm(
              snake_case_ ,				batch_size=snake_case_ ,				seq_length=snake_case_ ,				is_pair=snake_case_ ,				framework=snake_case_  )

        elif self.task == "causal-lm":
          A_  :	Dict    						=  self._generate_dummy_inputs_for_causal_lm(
              snake_case_ ,				batch_size=snake_case_ ,				seq_length=snake_case_ ,				is_pair=snake_case_ ,				framework=snake_case_  )
        else:
          A_  :	int    						=  self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
              snake_case_ ,				batch_size=snake_case_ ,				seq_length=snake_case_ ,				is_pair=snake_case_ ,				framework=snake_case_  )

        return common_inputs

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_  ):

        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
          A_  :	str    						=  super()._flatten_past_key_values_(snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_  )
        else:
          A_  :	int    						=  super(snake_case_ ,				self  )._flatten_past_key_values_(
              snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_  )

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_  ):

        """simple docstring"""

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

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

        A_  :	Optional[int]    						=  'past_encoder_sequence'
        A_  :	List[Any]    						=  'past_decoder_sequence' if direction == 'inputs' else 'past_decoder_sequence + sequence'

        for i in range(snake_case_  ):
          A_  :	Tuple    						=  {0: 'batch', 2: decoder_sequence}
          A_  :	List[str]    						=  {0: 'batch', 2: decoder_sequence}
          A_  :	Optional[Any]    						=  {0: 'batch', 2: encoder_sequence}
          A_  :	Union[str, Any]    						=  {0: 'batch', 2: encoder_sequence}






"""simple docstring"""




from typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


lowerCamelCase_					:						Any      = {
    'configuration_utils': ['GenerationConfig'],
    'streamers': ['TextIteratorStreamer', 'TextStreamer'],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						Optional[Any]      = [
       'Constraint',
       'ConstraintListState',
       'DisjunctiveConstraint',
       'PhrasalConstraint',
   ]
   lowerCamelCase_					:						List[str]      = [
       'BeamHypotheses',
       'BeamScorer',
       'BeamSearchScorer',
       'ConstrainedBeamSearchScorer',
   ]
   lowerCamelCase_					:						Dict      = [
       'EpsilonLogitsWarper',
       'EtaLogitsWarper',
       'ForcedBOSTokenLogitsProcessor',
       'ForcedEOSTokenLogitsProcessor',
       'HammingDiversityLogitsProcessor',
       'InfNanRemoveLogitsProcessor',
       'LogitsProcessor',
       'LogitsProcessorList',
       'LogitsWarper',
       'MinLengthLogitsProcessor',
       'MinNewTokensLengthLogitsProcessor',
       'NoBadWordsLogitsProcessor',
       'NoRepeatNGramLogitsProcessor',
       'PrefixConstrainedLogitsProcessor',
       'RepetitionPenaltyLogitsProcessor',
       'SequenceBiasLogitsProcessor',
       'EncoderRepetitionPenaltyLogitsProcessor',
       'TemperatureLogitsWarper',
       'TopKLogitsWarper',
       'TopPLogitsWarper',
       'TypicalLogitsWarper',
       'EncoderNoRepeatNGramLogitsProcessor',
       'ExponentialDecayLengthPenalty',
       'LogitNormalization',
   ]
   lowerCamelCase_					:						str      = [
       'MaxNewTokensCriteria',
       'MaxLengthCriteria',
       'MaxTimeCriteria',
       'StoppingCriteria',
       'StoppingCriteriaList',
       'validate_stopping_criteria',
   ]
   lowerCamelCase_					:						List[str]      = [
       'GenerationMixin',
       'top_k_top_p_filtering',
       'GreedySearchEncoderDecoderOutput',
       'GreedySearchDecoderOnlyOutput',
       'SampleEncoderDecoderOutput',
       'SampleDecoderOnlyOutput',
       'BeamSearchEncoderDecoderOutput',
       'BeamSearchDecoderOnlyOutput',
       'BeamSampleEncoderDecoderOutput',
       'BeamSampleDecoderOnlyOutput',
       'ContrastiveSearchEncoderDecoderOutput',
       'ContrastiveSearchDecoderOnlyOutput',
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						Union[str, Any]      = [
       'TFForcedBOSTokenLogitsProcessor',
       'TFForcedEOSTokenLogitsProcessor',
       'TFLogitsProcessor',
       'TFLogitsProcessorList',
       'TFLogitsWarper',
       'TFMinLengthLogitsProcessor',
       'TFNoBadWordsLogitsProcessor',
       'TFNoRepeatNGramLogitsProcessor',
       'TFRepetitionPenaltyLogitsProcessor',
       'TFTemperatureLogitsWarper',
       'TFTopKLogitsWarper',
       'TFTopPLogitsWarper',
       'TFForceTokensLogitsProcessor',
       'TFSuppressTokensAtBeginLogitsProcessor',
       'TFSuppressTokensLogitsProcessor',
   ]
   lowerCamelCase_					:						Union[str, Any]      = [
       'TFGenerationMixin',
       'tf_top_k_top_p_filtering',
       'TFGreedySearchDecoderOnlyOutput',
       'TFGreedySearchEncoderDecoderOutput',
       'TFSampleEncoderDecoderOutput',
       'TFSampleDecoderOnlyOutput',
       'TFBeamSearchEncoderDecoderOutput',
       'TFBeamSearchDecoderOnlyOutput',
       'TFBeamSampleEncoderDecoderOutput',
       'TFBeamSampleDecoderOnlyOutput',
       'TFContrastiveSearchEncoderDecoderOutput',
       'TFContrastiveSearchDecoderOnlyOutput',
   ]

try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						int      = [
       'FlaxForcedBOSTokenLogitsProcessor',
       'FlaxForcedEOSTokenLogitsProcessor',
       'FlaxLogitsProcessor',
       'FlaxLogitsProcessorList',
       'FlaxLogitsWarper',
       'FlaxMinLengthLogitsProcessor',
       'FlaxTemperatureLogitsWarper',
       'FlaxTopKLogitsWarper',
       'FlaxTopPLogitsWarper',
   ]
   lowerCamelCase_					:						Tuple      = [
       'FlaxGenerationMixin',
       'FlaxGreedySearchOutput',
       'FlaxSampleOutput',
       'FlaxBeamSearchOutput',
   ]

if TYPE_CHECKING:
   from .configuration_utils import GenerationConfig
   from .streamers import TextIteratorStreamer, TextStreamer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
      from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
      from .logits_process import (
          EncoderNoRepeatNGramLogitsProcessor,
          EncoderRepetitionPenaltyLogitsProcessor,
          EpsilonLogitsWarper,
          EtaLogitsWarper,
          ExponentialDecayLengthPenalty,
          ForcedBOSTokenLogitsProcessor,
          ForcedEOSTokenLogitsProcessor,
          HammingDiversityLogitsProcessor,
          InfNanRemoveLogitsProcessor,
          LogitNormalization,
          LogitsProcessor,
          LogitsProcessorList,
          LogitsWarper,
          MinLengthLogitsProcessor,
          MinNewTokensLengthLogitsProcessor,
          NoBadWordsLogitsProcessor,
          NoRepeatNGramLogitsProcessor,
          PrefixConstrainedLogitsProcessor,
          RepetitionPenaltyLogitsProcessor,
          SequenceBiasLogitsProcessor,
          TemperatureLogitsWarper,
          TopKLogitsWarper,
          TopPLogitsWarper,
          TypicalLogitsWarper,
      )
      from .stopping_criteria import (
          MaxLengthCriteria,
          MaxNewTokensCriteria,
          MaxTimeCriteria,
          StoppingCriteria,
          StoppingCriteriaList,
          validate_stopping_criteria,
      )
      from .utils import (
          BeamSampleDecoderOnlyOutput,
          BeamSampleEncoderDecoderOutput,
          BeamSearchDecoderOnlyOutput,
          BeamSearchEncoderDecoderOutput,
          ContrastiveSearchDecoderOnlyOutput,
          ContrastiveSearchEncoderDecoderOutput,
          GenerationMixin,
          GreedySearchDecoderOnlyOutput,
          GreedySearchEncoderDecoderOutput,
          SampleDecoderOnlyOutput,
          SampleEncoderDecoderOutput,
          top_k_top_p_filtering,
      )

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tf_logits_process import (
          TFForcedBOSTokenLogitsProcessor,
          TFForcedEOSTokenLogitsProcessor,
          TFForceTokensLogitsProcessor,
          TFLogitsProcessor,
          TFLogitsProcessorList,
          TFLogitsWarper,
          TFMinLengthLogitsProcessor,
          TFNoBadWordsLogitsProcessor,
          TFNoRepeatNGramLogitsProcessor,
          TFRepetitionPenaltyLogitsProcessor,
          TFSuppressTokensAtBeginLogitsProcessor,
          TFSuppressTokensLogitsProcessor,
          TFTemperatureLogitsWarper,
          TFTopKLogitsWarper,
          TFTopPLogitsWarper,
      )
      from .tf_utils import (
          TFBeamSampleDecoderOnlyOutput,
          TFBeamSampleEncoderDecoderOutput,
          TFBeamSearchDecoderOnlyOutput,
          TFBeamSearchEncoderDecoderOutput,
          TFContrastiveSearchDecoderOnlyOutput,
          TFContrastiveSearchEncoderDecoderOutput,
          TFGenerationMixin,
          TFGreedySearchDecoderOnlyOutput,
          TFGreedySearchEncoderDecoderOutput,
          TFSampleDecoderOnlyOutput,
          TFSampleEncoderDecoderOutput,
          tf_top_k_top_p_filtering,
      )

   try:
      if not is_flax_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .flax_logits_process import (
          FlaxForcedBOSTokenLogitsProcessor,
          FlaxForcedEOSTokenLogitsProcessor,
          FlaxLogitsProcessor,
          FlaxLogitsProcessorList,
          FlaxLogitsWarper,
          FlaxMinLengthLogitsProcessor,
          FlaxTemperatureLogitsWarper,
          FlaxTopKLogitsWarper,
          FlaxTopPLogitsWarper,
      )
      from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
   import sys

   lowerCamelCase_					:						Tuple      = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)