





"""simple docstring"""




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowerCamelCase_					:						Union[str, Any]      = {'''configuration_yoso''': ['''YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YosoConfig''']}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						int      = [
       '''YOSO_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''YosoForMaskedLM''',
       '''YosoForMultipleChoice''',
       '''YosoForQuestionAnswering''',
       '''YosoForSequenceClassification''',
       '''YosoForTokenClassification''',
       '''YosoLayer''',
       '''YosoModel''',
       '''YosoPreTrainedModel''',
   ]


if TYPE_CHECKING:
   from .configuration_yoso import YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP, YosoConfig

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_yoso import (
          YOSO_PRETRAINED_MODEL_ARCHIVE_LIST,
          YosoForMaskedLM,
          YosoForMultipleChoice,
          YosoForQuestionAnswering,
          YosoForSequenceClassification,
          YosoForTokenClassification,
          YosoLayer,
          YosoModel,
          YosoPreTrainedModel,
      )


else:
   import sys

   lowerCamelCase_					:						Optional[int]      = _LazyModule(__name__, globals()['__file__'], _import_structure)







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