



"""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					:List[str]  =      {
    '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							(				a   ):





     '''simple docstring'''



     a__             ='''gpt2'''
     a__             =['''past_key_values''']
     a__             ={
         '''hidden_size''': '''n_embd''',
         '''max_position_embeddings''': '''n_positions''',
         '''num_attention_heads''': '''n_head''',
         '''num_hidden_layers''': '''n_layer''',
     }





     def __init__(      self ,			A=5_0_2_5_7 ,			A=1_0_2_4 ,			A=7_6_8 ,			A=1_2 ,			A=1_2 ,			A=None ,			A="gelu_new" ,			A=0.1 ,			A=0.1 ,			A=0.1 ,			A=1E-5 ,			A=0.02 ,			A="cls_index" ,			A=True ,			A=None ,			A=True ,			A=0.1 ,			A=True ,			A=True ,			A=5_0_2_5_6 ,			A=5_0_2_5_6 ,			A=False ,			A=False ,			**A ,			)							->      Union[str, Any]:
         _UpperCAmelCase							:						Optional[int]       							=					vocab_size
         _UpperCAmelCase							:						Union[str, Any]       							=					n_positions
         _UpperCAmelCase							:						Optional[Any]       							=					n_embd
         _UpperCAmelCase							:						Tuple       							=					n_layer
         _UpperCAmelCase							:						Any       							=					n_head
         _UpperCAmelCase							:						Union[str, Any]       							=					n_inner
         _UpperCAmelCase							:						Optional[int]       							=					activation_function
         _UpperCAmelCase							:						Optional[int]       							=					resid_pdrop
         _UpperCAmelCase							:						Dict       							=					embd_pdrop
         _UpperCAmelCase							:						List[Any]       							=					attn_pdrop
         _UpperCAmelCase							:						Tuple       							=					layer_norm_epsilon
         _UpperCAmelCase							:						Optional[int]       							=					initializer_range
         _UpperCAmelCase							:						List[str]       							=					summary_type
         _UpperCAmelCase							:						Tuple       							=					summary_use_proj
         _UpperCAmelCase							:						List[Any]       							=					summary_activation
         _UpperCAmelCase							:						Optional[int]       							=					summary_first_dropout
         _UpperCAmelCase							:						int       							=					summary_proj_to_labels
         _UpperCAmelCase							:						Union[str, Any]       							=					scale_attn_weights
         _UpperCAmelCase							:						Any       							=					use_cache
         _UpperCAmelCase							:						Tuple       							=					scale_attn_by_inverse_layer_idx
         _UpperCAmelCase							:						Optional[Any]       							=					reorder_and_upcast_attn

         _UpperCAmelCase							:						Union[str, Any]       							=					bos_token_id
         _UpperCAmelCase							:						Optional[int]       							=					eos_token_id

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



class 							_UpperCAmelCase							(				a   ):





     '''simple docstring'''



     def __init__(      self ,			A ,			A = "default" ,			A = None ,			A = False ,			)							->      str:
         super().__init__(A ,			task=A ,			patching_specs=A ,			use_past=A	)
         if not getattr(self._config ,			'''pad_token_id''' ,			A	):
             # TODO: how to do that better?
             _UpperCAmelCase							:						Optional[int]       							=					0





     @property
     def 				__lowerCAmelCase			(      self	)							->      Mapping[str, Mapping[int, str]]:
         _UpperCAmelCase							:						List[str]       							=					OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}	)
         if self.use_past:
             self.fill_with_past_key_values_(A ,			direction='''inputs'''	)
             _UpperCAmelCase							:						Union[str, Any]       							=					{0: '''batch''', 1: '''past_sequence + sequence'''}
         else:
             _UpperCAmelCase							:						Tuple       							=					{0: '''batch''', 1: '''sequence'''}

         return common_inputs





     @property
     def 				__lowerCAmelCase			(      self	)							->      int:
         return self._config.n_layer





     @property
     def 				__lowerCAmelCase			(      self	)							->      int:
         return self._config.n_head





     def 				__lowerCAmelCase			(      self ,			A ,			A = -1 ,			A = -1 ,			A = False ,			A = None ,			)							->      Mapping[str, Any]:
         _UpperCAmelCase							:						int       							=					super(A ,			self	).generate_dummy_inputs(
             A ,			batch_size=A ,			seq_length=A ,			is_pair=A ,			framework=A	)

         # We need to order the input in the way they appears in the forward()
         _UpperCAmelCase							:						List[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

                 _UpperCAmelCase							:						Optional[Any]       							=					common_inputs['''input_ids'''].shape
                 # Not using the same length for past_key_values
                 _UpperCAmelCase							:						Optional[Any]       							=					seqlen + 2
                 _UpperCAmelCase							:						Union[str, Any]       							=					(
                     batch,
                     self.num_attention_heads,
                     past_key_values_length,
                     self._config.hidden_size // self.num_attention_heads,
                 )
                 _UpperCAmelCase							:						List[Any]       							=					[
                     (torch.zeros(A	), torch.zeros(A	)) for _ in range(self.num_layers	)
                 ]

         _UpperCAmelCase							:						int       							=					common_inputs['''attention_mask''']
         if self.use_past:
             _UpperCAmelCase							:						int       							=					ordered_inputs['''attention_mask'''].dtype
             _UpperCAmelCase							:						Dict       							=					torch.cat(
                 [ordered_inputs['''attention_mask'''], torch.ones(A ,			A ,			dtype=A	)] ,			dim=1	)

         return ordered_inputs





     @property
     def 				__lowerCAmelCase			(      self	)							->      int:
         return 1_3







"""simple docstring"""
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
  import tensorflow as tf
class 							_UpperCAmelCase							(				TensorFormatter[Mapping, '''tf.Tensor''', Mapping]   ):





     '''simple docstring'''



     def __init__(      self ,			A=None ,			**A	)							->      List[str]:
         super().__init__(features=A	)
         _UpperCAmelCase							:						Any       							=					tf_tensor_kwargs
         import tensorflow as tf  # noqa: import tf at initialization





     def 				__lowerCAmelCase			(      self ,			A	)							->      Optional[Any]:
         import tensorflow as tf

         if isinstance(A ,			A	) and column:
             if all(
                 isinstance(A ,			tf.Tensor	) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column	):
                 return tf.stack(A	)
             elif all(
                 isinstance(A ,			(tf.Tensor, tf.RaggedTensor)	) and x.ndim == 1 and x.dtype == column[0].dtype
                 for x in column	):
                 # only rag 1-D tensors, otherwise some dimensions become ragged even though they were consolidated
                 return tf.ragged.stack(A	)

         return column





     def 				__lowerCAmelCase			(      self ,			A	)							->      int:
         import tensorflow as tf

         if value is None:
             return value

         _UpperCAmelCase							:						Any       							=					{}

         if isinstance(A ,			(np.number, np.ndarray)	) and np.issubdtype(value.dtype ,			np.integer	):
             _UpperCAmelCase							:						Union[str, Any]       							=					{'''dtype''': tf.intaa}
         elif isinstance(A ,			(np.number, np.ndarray)	) and np.issubdtype(value.dtype ,			np.floating	):
             _UpperCAmelCase							:						Dict       							=					{'''dtype''': tf.floataa}
         elif config.PIL_AVAILABLE and "PIL" in sys.modules:
             import PIL.Image

             if isinstance(A ,			PIL.Image.Image	):
                 _UpperCAmelCase							:						Optional[int]       							=					np.asarray(A	)

         return tf.convert_to_tensor(A ,			**{**default_dtype, **self.tf_tensor_kwargs}	)





     def 				__lowerCAmelCase			(      self ,			A	)							->      Tuple:
         import tensorflow as tf

         # support for torch, tf, jax etc.
         if config.TORCH_AVAILABLE and "torch" in sys.modules:
             import torch

             if isinstance(A ,			torch.Tensor	):
                 return self._tensorize(data_struct.detach().cpu().numpy()[()]	)
         if hasattr(A ,			'''__array__'''	) and not isinstance(A ,			tf.Tensor	):
             _UpperCAmelCase							:						List[str]       							=					data_struct.__array__()
         # support for nested types like struct of list of struct
         if isinstance(A ,			np.ndarray	):
             if data_struct.dtype == object:  # tf tensors cannot be instantied from an array of objects
                 return self._consolidate([self.recursive_tensorize(A	) for substruct in data_struct]	)
         elif isinstance(A ,			(list, tuple)	):
             return self._consolidate([self.recursive_tensorize(A	) for substruct in data_struct]	)
         return self._tensorize(A	)





     def 				__lowerCAmelCase			(      self ,			A	)							->      Optional[int]:
         return map_nested(self._recursive_tensorize ,			A ,			map_list=A	)





     def 				__lowerCAmelCase			(      self ,			A	)							->      Mapping:
         _UpperCAmelCase							:						str       							=					self.numpy_arrow_extractor().extract_row(A	)
         _UpperCAmelCase							:						List[Any]       							=					self.python_features_decoder.decode_row(A	)
         return self.recursive_tensorize(A	)





     def 				__lowerCAmelCase			(      self ,			A	)							->      "tf.Tensor":
         _UpperCAmelCase							:						Union[str, Any]       							=					self.numpy_arrow_extractor().extract_column(A	)
         _UpperCAmelCase							:						Tuple       							=					self.python_features_decoder.decode_column(A ,			pa_table.column_names[0]	)
         _UpperCAmelCase							:						str       							=					self.recursive_tensorize(A	)
         _UpperCAmelCase							:						Optional[Any]       							=					self._consolidate(A	)
         return column





     def 				__lowerCAmelCase			(      self ,			A	)							->      Mapping:
         _UpperCAmelCase							:						Dict       							=					self.numpy_arrow_extractor().extract_batch(A	)
         _UpperCAmelCase							:						Tuple       							=					self.python_features_decoder.decode_batch(A	)
         _UpperCAmelCase							:						Union[str, Any]       							=					self.recursive_tensorize(A	)
         for column_name in batch:
             _UpperCAmelCase							:						str       							=					self._consolidate(batch[column_name]	)
         return batch


