





"""simple docstring"""




from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


lowerCamelCase_					:						Union[str, Any]      = logging.get_logger(__name__)

lowerCamelCase_					:						Optional[Any]      = {
    'gpt2': 'https://huggingface.co/gpt2/resolve/main/config.json',
    'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/config.json',
    'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/config.json',
    'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/config.json',
    'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/config.json',
}

class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_				:			Optional[Any]        =       """gpt2"""
      lowercase_				:			Optional[int]        =       ["""past_key_values"""]
      lowercase_				:			Dict        =       {
          """hidden_size""": """n_embd""",
          """max_position_embeddings""": """n_positions""",
          """num_attention_heads""": """n_head""",
          """num_hidden_layers""": """n_layer""",
      }

      def __init__(					self ,				snake_case_=5_0_2_5_7 ,				snake_case_=1_0_2_4 ,				snake_case_=7_6_8 ,				snake_case_=1_2 ,				snake_case_=1_2 ,				snake_case_=None ,				snake_case_="gelu_new" ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=1E-5 ,				snake_case_=0.02 ,				snake_case_="cls_index" ,				snake_case_=True ,				snake_case_=None ,				snake_case_=True ,				snake_case_=0.1 ,				snake_case_=True ,				snake_case_=True ,				snake_case_=5_0_2_5_6 ,				snake_case_=5_0_2_5_6 ,				snake_case_=False ,				snake_case_=False ,				**snake_case_ ,				):

        """simple docstring"""

        A_  :	Union[str, Any]    						=  vocab_size
        A_  :	List[Any]    						=  n_positions
        A_  :	List[Any]    						=  n_embd
        A_  :	Tuple    						=  n_layer
        A_  :	List[Any]    						=  n_head
        A_  :	List[str]    						=  n_inner
        A_  :	str    						=  activation_function
        A_  :	Optional[Any]    						=  resid_pdrop
        A_  :	int    						=  embd_pdrop
        A_  :	Tuple    						=  attn_pdrop
        A_  :	str    						=  layer_norm_epsilon
        A_  :	Any    						=  initializer_range
        A_  :	Union[str, Any]    						=  summary_type
        A_  :	Optional[Any]    						=  summary_use_proj
        A_  :	Dict    						=  summary_activation
        A_  :	Optional[int]    						=  summary_first_dropout
        A_  :	Optional[int]    						=  summary_proj_to_labels
        A_  :	Any    						=  scale_attn_weights
        A_  :	Optional[Any]    						=  use_cache
        A_  :	Dict    						=  scale_attn_by_inverse_layer_idx
        A_  :	Any    						=  reorder_and_upcast_attn

        A_  :	Optional[Any]    						=  bos_token_id
        A_  :	List[Any]    						=  eos_token_id

        super().__init__(bos_token_id=snake_case_ ,				eos_token_id=snake_case_ ,				**snake_case_  )


class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(					self ,				snake_case_ ,				snake_case_ = "default" ,				snake_case_ = None ,				snake_case_ = False ,				):

        """simple docstring"""

        super().__init__(snake_case_ ,				task=snake_case_ ,				patching_specs=snake_case_ ,				use_past=snake_case_  )
        if not getattr(self._config ,				'pad_token_id' ,				snake_case_  ):
          # TODO: how to do that better?
          A_  :	Tuple    						=  0

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Dict    						=  OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}  )
        if self.use_past:
          self.fill_with_past_key_values_(snake_case_ ,				direction='inputs'  )
          A_  :	List[str]    						=  {0: 'batch', 1: 'past_sequence + sequence'}
        else:
          A_  :	Tuple    						=  {0: 'batch', 1: 'sequence'}

        return common_inputs

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return self._config.n_layer

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return self._config.n_head

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

        """simple docstring"""

        A_  :	int    						=  super(snake_case_ ,				self  ).generate_dummy_inputs(
            snake_case_ ,				batch_size=snake_case_ ,				seq_length=snake_case_ ,				is_pair=snake_case_ ,				framework=snake_case_  )

        # We need to order the input in the way they appears in the forward()
        A_  :	Optional[Any]    						=  OrderedDict({'input_ids': common_inputs['input_ids']}  )

        # Need to add the past_keys
        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_  :	List[str]    						=  common_inputs['input_ids'].shape
            # Not using the same length for past_key_values
            A_  :	Optional[Any]    						=  seqlen + 2
            A_  :	Any    						=  (
                batch,
                self.num_attention_heads,
                past_key_values_length,
                self._config.hidden_size // self.num_attention_heads,
            )
            A_  :	Any    						=  [
                (torch.zeros(snake_case_  ), torch.zeros(snake_case_  )) for _ in range(self.num_layers  )
            ]

        A_  :	List[Any]    						=  common_inputs['attention_mask']
        if self.use_past:
          A_  :	List[Any]    						=  ordered_inputs['attention_mask'].dtype
          A_  :	Any    						=  torch.cat(
              [ordered_inputs['attention_mask'], torch.ones(snake_case_ ,				snake_case_ ,				dtype=snake_case_  )] ,				dim=1  )

        return ordered_inputs

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return 1_3






"""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__)