





import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
         OpenAIGPTConfig,
         OpenAIGPTDoubleHeadsModel,
         OpenAIGPTForSequenceClassification,
         OpenAIGPTLMHeadModel,
         OpenAIGPTModel,
     )



class 							_UpperCamelCase					:

       def __init__(		self: List[Any]					,   _SCREAMING_SNAKE_CASE: List[str]					,   _SCREAMING_SNAKE_CASE: Dict=13					,   _SCREAMING_SNAKE_CASE: str=7					,   _SCREAMING_SNAKE_CASE: Dict=True					,   _SCREAMING_SNAKE_CASE: Union[str, Any]=True					,   _SCREAMING_SNAKE_CASE: Union[str, Any]=True					,   _SCREAMING_SNAKE_CASE: Dict=99					,   _SCREAMING_SNAKE_CASE: Optional[Any]=32					,   _SCREAMING_SNAKE_CASE: Any=5					,   _SCREAMING_SNAKE_CASE: Union[str, Any]=4					,   _SCREAMING_SNAKE_CASE: Dict=37					,   _SCREAMING_SNAKE_CASE: Any="gelu"					,   _SCREAMING_SNAKE_CASE: Union[str, Any]=0.1					,   _SCREAMING_SNAKE_CASE: str=0.1					,   _SCREAMING_SNAKE_CASE: Any=512					,   _SCREAMING_SNAKE_CASE: int=16					,   _SCREAMING_SNAKE_CASE: str=2					,   _SCREAMING_SNAKE_CASE: str=0.02					,   _SCREAMING_SNAKE_CASE: str=3					,   _SCREAMING_SNAKE_CASE: Tuple=4					,   _SCREAMING_SNAKE_CASE: Tuple=None					,   )       -> Dict:




              """simple docstring"""


              UpperCamelCase_          =  parent
              UpperCamelCase_          =  batch_size
              UpperCamelCase_          =  seq_length
              UpperCamelCase_          =  is_training
              UpperCamelCase_          =  use_token_type_ids
              UpperCamelCase_          =  use_labels
              UpperCamelCase_          =  vocab_size
              UpperCamelCase_          =  hidden_size
              UpperCamelCase_          =  num_hidden_layers
              UpperCamelCase_          =  num_attention_heads
              UpperCamelCase_          =  intermediate_size
              UpperCamelCase_          =  hidden_act
              UpperCamelCase_          =  hidden_dropout_prob
              UpperCamelCase_          =  attention_probs_dropout_prob
              UpperCamelCase_          =  max_position_embeddings
              UpperCamelCase_          =  type_vocab_size
              UpperCamelCase_          =  type_sequence_label_size
              UpperCamelCase_          =  initializer_range
              UpperCamelCase_          =  num_labels
              UpperCamelCase_          =  num_choices
              UpperCamelCase_          =  scope
              UpperCamelCase_          =  self.vocab_size - 1

       def lowercase (		self: str		)       -> Tuple:




              """simple docstring"""


              UpperCamelCase_          =  ids_tensor([self.batch_size, self.seq_length]					,   self.vocab_size		)

              UpperCamelCase_          =  None
              if self.use_token_type_ids:
                     UpperCamelCase_          =  ids_tensor([self.batch_size, self.seq_length]					,   self.type_vocab_size		)

              UpperCamelCase_          =  None
              UpperCamelCase_          =  None
              UpperCamelCase_          =  None
              if self.use_labels:
                     UpperCamelCase_          =  ids_tensor([self.batch_size]					,   self.type_sequence_label_size		)
                     UpperCamelCase_          =  ids_tensor([self.batch_size, self.seq_length]					,   self.num_labels		)
                     UpperCamelCase_          =  ids_tensor([self.batch_size]					,   self.num_choices		)

              UpperCamelCase_          =  OpenAIGPTConfig(
                  vocab_size=self.vocab_size					,   n_embd=self.hidden_size					,   n_layer=self.num_hidden_layers					,   n_head=self.num_attention_heads					,   n_positions=self.max_position_embeddings					,   pad_token_id=self.pad_token_id					,   )

              UpperCamelCase_          =  ids_tensor([self.num_hidden_layers, self.num_attention_heads]					,   2		)

              return (
                  config,
                  input_ids,
                  head_mask,
                  token_type_ids,
                  sequence_labels,
                  token_labels,
                  choice_labels,
              )

       def lowercase (		self: Union[str, Any]					,   _SCREAMING_SNAKE_CASE: int					,   _SCREAMING_SNAKE_CASE: Union[str, Any]					,   _SCREAMING_SNAKE_CASE: List[Any]					,   _SCREAMING_SNAKE_CASE: Tuple					,   *_SCREAMING_SNAKE_CASE: Any		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  OpenAIGPTModel(config=_SCREAMING_SNAKE_CASE		)
              model.to(_SCREAMING_SNAKE_CASE		)
              model.eval()

              UpperCamelCase_          =  model(_SCREAMING_SNAKE_CASE					,   token_type_ids=_SCREAMING_SNAKE_CASE					,   head_mask=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  model(_SCREAMING_SNAKE_CASE					,   token_type_ids=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  model(_SCREAMING_SNAKE_CASE		)

              self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, self.seq_length, self.hidden_size)		)

       def lowercase (		self: str					,   _SCREAMING_SNAKE_CASE: List[Any]					,   _SCREAMING_SNAKE_CASE: List[Any]					,   _SCREAMING_SNAKE_CASE: List[str]					,   _SCREAMING_SNAKE_CASE: Dict					,   *_SCREAMING_SNAKE_CASE: Optional[Any]		)       -> Any:




              """simple docstring"""


              UpperCamelCase_          =  OpenAIGPTLMHeadModel(_SCREAMING_SNAKE_CASE		)
              model.to(_SCREAMING_SNAKE_CASE		)
              model.eval()

              UpperCamelCase_          =  model(_SCREAMING_SNAKE_CASE					,   token_type_ids=_SCREAMING_SNAKE_CASE					,   labels=_SCREAMING_SNAKE_CASE		)
              self.parent.assertEqual(result.loss.shape					,   ()		)
              self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.seq_length, self.vocab_size)		)

       def lowercase (		self: List[str]					,   _SCREAMING_SNAKE_CASE: Dict					,   _SCREAMING_SNAKE_CASE: Optional[int]					,   _SCREAMING_SNAKE_CASE: Dict					,   _SCREAMING_SNAKE_CASE: int					,   *_SCREAMING_SNAKE_CASE: str		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  OpenAIGPTDoubleHeadsModel(_SCREAMING_SNAKE_CASE		)
              model.to(_SCREAMING_SNAKE_CASE		)
              model.eval()

              UpperCamelCase_          =  model(_SCREAMING_SNAKE_CASE					,   token_type_ids=_SCREAMING_SNAKE_CASE					,   labels=_SCREAMING_SNAKE_CASE		)
              self.parent.assertEqual(result.loss.shape					,   ()		)
              self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.seq_length, self.vocab_size)		)

       def lowercase (		self: List[Any]					,   _SCREAMING_SNAKE_CASE: str					,   _SCREAMING_SNAKE_CASE: List[str]					,   _SCREAMING_SNAKE_CASE: List[Any]					,   _SCREAMING_SNAKE_CASE: int					,   *_SCREAMING_SNAKE_CASE: str		)       -> List[Any]:




              """simple docstring"""


              UpperCamelCase_          =  self.num_labels
              UpperCamelCase_          =  OpenAIGPTForSequenceClassification(_SCREAMING_SNAKE_CASE		)
              model.to(_SCREAMING_SNAKE_CASE		)
              model.eval()

              UpperCamelCase_          =  ids_tensor([self.batch_size]					,   self.type_sequence_label_size		)
              UpperCamelCase_          =  model(_SCREAMING_SNAKE_CASE					,   token_type_ids=_SCREAMING_SNAKE_CASE					,   labels=_SCREAMING_SNAKE_CASE		)
              self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.num_labels)		)



       def lowercase (		self: int		)       -> int:




              """simple docstring"""


              UpperCamelCase_          =  self.prepare_config_and_inputs()
              (
                  (
                  UpperCamelCase_
              )       , (
                  UpperCamelCase_
              )       , (
                  UpperCamelCase_
              )       , (
                  UpperCamelCase_
              )       , (
                  UpperCamelCase_
              )       , (
                  UpperCamelCase_
              )       , (
                  UpperCamelCase_
              )       , 
              )          =  config_and_inputs
              UpperCamelCase_          =  {
                  "input_ids": input_ids,
                  "token_type_ids": token_type_ids,
                  "head_mask": head_mask,
              }

              return config, inputs_dict



@require_torch
class 							_UpperCamelCase					(	lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_  ,						unittest.TestCase     ):
       _UpperCamelCase				:					List[str]         =   (
           (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
           if is_torch_available()
           else ()
       )
       _UpperCamelCase				:					List[str]         =   (
           (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
       )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
       _UpperCamelCase				:					int         =   (
           {
               '''feature-extraction''': OpenAIGPTModel,
               '''text-classification''': OpenAIGPTForSequenceClassification,
               '''text-generation''': OpenAIGPTLMHeadModel,
               '''zero-shot''': OpenAIGPTForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )

       def lowercase (		self: Optional[int]					,   _SCREAMING_SNAKE_CASE: Union[str, Any]					,   _SCREAMING_SNAKE_CASE: Tuple					,   _SCREAMING_SNAKE_CASE: Dict					,   _SCREAMING_SNAKE_CASE: Any					,   _SCREAMING_SNAKE_CASE: str		)       -> Union[str, Any]:




              """simple docstring"""


              if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
                     # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
                     # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
                     # tiny config could not be created.
                     return True

              return False

       def lowercase (		self: Dict					,   _SCREAMING_SNAKE_CASE: Tuple					,   _SCREAMING_SNAKE_CASE: List[Any]					,   _SCREAMING_SNAKE_CASE: List[Any]=False		)       -> Union[str, Any]:




              """simple docstring"""


              UpperCamelCase_          =  super()._prepare_for_class(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   return_labels=_SCREAMING_SNAKE_CASE		)

              if return_labels:
                     if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                            UpperCamelCase_          =  torch.zeros(
                                (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)					,   dtype=torch.long					,   device=_SCREAMING_SNAKE_CASE					,   )
                            UpperCamelCase_          =  inputs_dict["labels"]
                            UpperCamelCase_          =  inputs_dict["labels"]
                            UpperCamelCase_          =  torch.zeros(
                                (self.model_tester.batch_size, self.model_tester.num_choices)					,   dtype=torch.long					,   device=_SCREAMING_SNAKE_CASE					,   )
                            UpperCamelCase_          =  torch.zeros(
                                self.model_tester.batch_size					,   dtype=torch.long					,   device=_SCREAMING_SNAKE_CASE		)
              return inputs_dict

       def lowercase (		self: List[Any]		)       -> Optional[int]:




              """simple docstring"""


              UpperCamelCase_          =  OpenAIGPTModelTester(self		)
              UpperCamelCase_          =  ConfigTester(self					,   config_class=_SCREAMING_SNAKE_CASE					,   n_embd=37		)

       def lowercase (		self: str		)       -> List[Any]:




              """simple docstring"""


              self.config_tester.run_common_tests()

       def lowercase (		self: Union[str, Any]		)       -> Optional[int]:




              """simple docstring"""


              UpperCamelCase_          =  self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_openai_gpt_model(*_SCREAMING_SNAKE_CASE		)

       def lowercase (		self: int		)       -> Tuple:




              """simple docstring"""


              UpperCamelCase_          =  self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_lm_head_model(*_SCREAMING_SNAKE_CASE		)

       def lowercase (		self: Any		)       -> List[Any]:




              """simple docstring"""


              UpperCamelCase_          =  self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_double_lm_head_model(*_SCREAMING_SNAKE_CASE		)

       def lowercase (		self: int		)       -> List[str]:




              """simple docstring"""


              UpperCamelCase_          =  self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_SCREAMING_SNAKE_CASE		)



       @slow
       def lowercase (		self: Optional[int]		)       -> Tuple:




              """simple docstring"""


              for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase_          =  OpenAIGPTModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
                     self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)



@require_torch
class 							_UpperCamelCase					(	unittest.TestCase     ):

       @slow
       def lowercase (		self: Optional[Any]		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"		)
              model.to(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  torch.tensor([[481, 4735, 544]]					,   dtype=torch.long					,   device=_SCREAMING_SNAKE_CASE		)  # the president is
              UpperCamelCase_          =  [
                  481,
                  4735,
                  544,
                  246,
                  963,
                  870,
                  762,
                  239,
                  244,
                  40477,
                  244,
                  249,
                  719,
                  881,
                  487,
                  544,
                  240,
                  244,
                  603,
                  481,
              ]  # the president is a very good man. " \n " i\'m sure he is, " said the

              UpperCamelCase_          =  model.generate(_SCREAMING_SNAKE_CASE					,   do_sample=_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(output_ids[0].tolist()					,   _SCREAMING_SNAKE_CASE		)








_UpperCAmelCase        =				{
    'Pillow': 'Pillow',
    'accelerate': 'accelerate>=0.11.0',
    'compel': 'compel==0.1.8',
    'black': 'black~=23.1',
    'datasets': 'datasets',
    'filelock': 'filelock',
    'flax': 'flax>=0.4.1',
    'hf-doc-builder': 'hf-doc-builder>=0.3.0',
    'huggingface-hub': 'huggingface-hub>=0.13.2',
    'requests-mock': 'requests-mock==1.10.0',
    'importlib_metadata': 'importlib_metadata',
    'invisible-watermark': 'invisible-watermark',
    'isort': 'isort>=5.5.4',
    'jax': 'jax>=0.2.8,!=0.3.2',
    'jaxlib': 'jaxlib>=0.1.65',
    'Jinja2': 'Jinja2',
    'k-diffusion': 'k-diffusion>=0.0.12',
    'torchsde': 'torchsde',
    'note_seq': 'note_seq',
    'librosa': 'librosa',
    'numpy': 'numpy',
    'omegaconf': 'omegaconf',
    'parameterized': 'parameterized',
    'protobuf': 'protobuf>=3.20.3,<4',
    'pytest': 'pytest',
    'pytest-timeout': 'pytest-timeout',
    'pytest-xdist': 'pytest-xdist',
    'ruff': 'ruff>=0.0.241',
    'safetensors': 'safetensors',
    'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
    'scipy': 'scipy',
    'onnx': 'onnx',
    'regex': 'regex!=2019.12.17',
    'requests': 'requests',
    'tensorboard': 'tensorboard',
    'torch': 'torch>=1.4',
    'torchvision': 'torchvision',
    'transformers': 'transformers>=4.25.1',
    'urllib3': 'urllib3<=2.0.0',
}

