
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] ,    snake_case_			: List[str] ,    snake_case_			: Any=1_3 ,    snake_case_			: Optional[int]=7 ,    snake_case_			: Any=True ,    snake_case_			: Dict=True ,    snake_case_			: Dict=True ,    snake_case_			: Any=9_9 ,    snake_case_			: Optional[Any]=3_2 ,    snake_case_			: List[str]=5 ,    snake_case_			: Tuple=4 ,    snake_case_			: List[Any]=3_7 ,    snake_case_			: Dict="gelu" ,    snake_case_			: Any=0.1 ,    snake_case_			: Tuple=0.1 ,    snake_case_			: int=5_1_2 ,    snake_case_			: str=1_6 ,    snake_case_			: Tuple=2 ,    snake_case_			: int=0.02 ,    snake_case_			: List[str]=3 ,    snake_case_			: Optional[int]=4 ,    snake_case_			: List[Any]=None ,    ):
    __a			:  Tuple		    =  parent
    __a			:  Any		    =  batch_size
    __a			:  int		    =  seq_length
    __a			:  Tuple		    =  is_training
    __a			:  Tuple		    =  use_token_type_ids
    __a			:  Optional[int]		    =  use_labels
    __a			:  Dict		    =  vocab_size
    __a			:  Tuple		    =  hidden_size
    __a			:  Optional[int]		    =  num_hidden_layers
    __a			:  List[Any]		    =  num_attention_heads
    __a			:  int		    =  intermediate_size
    __a			:  List[str]		    =  hidden_act
    __a			:  Optional[int]		    =  hidden_dropout_prob
    __a			:  Any		    =  attention_probs_dropout_prob
    __a			:  Optional[Any]		    =  max_position_embeddings
    __a			:  Dict		    =  type_vocab_size
    __a			:  Tuple		    =  type_sequence_label_size
    __a			:  Dict		    =  initializer_range
    __a			:  Any		    =  num_labels
    __a			:  Tuple		    =  num_choices
    __a			:  List[Any]		    =  scope
    __a			:  int		    =  self.vocab_size - 1
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  str		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.vocab_size       )

    __a			:  Any		    =  None
    if self.use_token_type_ids:
     __a			:  List[str]		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.type_vocab_size       )

    __a			:  List[str]		    =  None
    __a			:  Any		    =  None
    __a			:  str		    =  None
    if self.use_labels:
     __a			:  List[Any]		    =  ids_tensor([self.batch_size] ,    self.type_sequence_label_size       )
     __a			:  Union[str, Any]		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.num_labels       )
     __a			:  Optional[Any]		    =  ids_tensor([self.batch_size] ,    self.num_choices       )

    __a			:  Any		    =  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 ,    )

    __a			:  Union[str, Any]		    =  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 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: List[Any] ,    snake_case_			: str ,    snake_case_			: Any ,    snake_case_			: List[Any] ,    *snake_case_			: Dict       ):
    __a			:  List[Any]		    =  OpenAIGPTModel(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  List[Any]		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    head_mask=snake_case_       )
    __a			:  str		    =  model(snake_case_ ,    token_type_ids=snake_case_       )
    __a			:  List[str]		    =  model(snake_case_       )

    self.parent.assertEqual(result.last_hidden_state.shape ,    (self.batch_size, self.seq_length, self.hidden_size)       )
   def 				lowerCAmelCase      (self			: Optional[int] ,    snake_case_			: int ,    snake_case_			: List[Any] ,    snake_case_			: Union[str, Any] ,    snake_case_			: List[Any] ,    *snake_case_			: List[Any]       ):
    __a			:  Any		    =  OpenAIGPTLMHeadModel(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  int		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.loss.shape ,    ()       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.seq_length, self.vocab_size)       )
   def 				lowerCAmelCase      (self			: Optional[int] ,    snake_case_			: List[Any] ,    snake_case_			: Optional[int] ,    snake_case_			: Dict ,    snake_case_			: List[str] ,    *snake_case_			: Dict       ):
    __a			:  Any		    =  OpenAIGPTDoubleHeadsModel(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  List[Any]		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.loss.shape ,    ()       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.seq_length, self.vocab_size)       )
   def 				lowerCAmelCase      (self			: Union[str, Any] ,    snake_case_			: Tuple ,    snake_case_			: Optional[int] ,    snake_case_			: Dict ,    snake_case_			: Dict ,    *snake_case_			: Tuple       ):
    __a			:  Tuple		    =  self.num_labels
    __a			:  List[str]		    =  OpenAIGPTForSequenceClassification(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  Optional[int]		    =  ids_tensor([self.batch_size] ,    self.type_sequence_label_size       )
    __a			:  str		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.num_labels)       )







   def 				lowerCAmelCase      (self			: str       ):
    __a			:  List[str]		    =  self.prepare_config_and_inputs()
    (
        (
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	
    )			:  int		    =  config_and_inputs
    __a			:  str		    =  {
        '''input_ids''': input_ids,
        '''token_type_ids''': token_type_ids,
        '''head_mask''': head_mask,
    }

    return config, inputs_dict





@require_torch
class 		UpperCamelCase__  (	__lowercase   ,__lowercase   ,__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Optional[int]     	=				(
       (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
       if is_torch_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE				:							Any     	=				(
       (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
   )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
   _SCREAMING_SNAKE_CASE				:							Tuple     	=				(
       {
           "feature-extraction": OpenAIGPTModel,
           "text-classification": OpenAIGPTForSequenceClassification,
           "text-generation": OpenAIGPTLMHeadModel,
           "zero-shot": OpenAIGPTForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   def 				lowerCAmelCase      (self			: List[Any] ,    snake_case_			: str ,    snake_case_			: List[str] ,    snake_case_			: Dict ,    snake_case_			: List[str] ,    snake_case_			: List[Any]       ):
    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 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: Any ,    snake_case_			: str ,    snake_case_			: int=False       ):
    __a			:  List[str]		    =  super()._prepare_for_class(snake_case_ ,    snake_case_ ,    return_labels=snake_case_       )

    if return_labels:
     if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
      __a			:  str		    =  torch.zeros(
          (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) ,    dtype=torch.long ,    device=snake_case_ ,    )
      __a			:  List[str]		    =  inputs_dict['''labels''']
      __a			:  Dict		    =  inputs_dict['''labels''']
      __a			:  int		    =  torch.zeros(
          (self.model_tester.batch_size, self.model_tester.num_choices) ,    dtype=torch.long ,    device=snake_case_ ,    )
      __a			:  List[Any]		    =  torch.zeros(
          self.model_tester.batch_size ,    dtype=torch.long ,    device=snake_case_       )
    return inputs_dict
   def 				lowerCAmelCase      (self			: List[str]       ):
    __a			:  List[str]		    =  OpenAIGPTModelTester(self       )
    __a			:  Optional[int]		    =  ConfigTester(self ,    config_class=snake_case_ ,    n_embd=3_7       )
   def 				lowerCAmelCase      (self			: str       ):
    self.config_tester.run_common_tests()
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  int		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_openai_gpt_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a			:  Optional[Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_lm_head_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  Optional[Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_double_lm_head_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*snake_case_       )







   @slow
   def 				lowerCAmelCase      (self			: str       ):
    for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a			:  List[Any]		    =  OpenAIGPTModel.from_pretrained(snake_case_       )
     self.assertIsNotNone(snake_case_       )





@require_torch
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @slow
   def 				lowerCAmelCase      (self			: Tuple       ):
    __a			:  Any		    =  OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''       )
    model.to(snake_case_       )
    __a			:  str		    =  torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] ,    dtype=torch.long ,    device=snake_case_       )  # the president is
    __a			:  Dict		    =  [
        4_8_1,
        4_7_3_5,
        5_4_4,
        2_4_6,
        9_6_3,
        8_7_0,
        7_6_2,
        2_3_9,
        2_4_4,
        4_0_4_7_7,
        2_4_4,
        2_4_9,
        7_1_9,
        8_8_1,
        4_8_7,
        5_4_4,
        2_4_0,
        2_4_4,
        6_0_3,
        4_8_1,
    ]  # the president is a very good man. " \n " i\'m sure he is, " said the

    __a			:  List[str]		    =  model.generate(snake_case_ ,    do_sample=snake_case_       )
    self.assertListEqual(output_ids[0].tolist() ,    snake_case_       )


# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


lowercase__          ={
    'configuration_efficientnet': [
        'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'EfficientNetConfig',
        'EfficientNetOnnxConfig',
    ]
}

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__          =['EfficientNetImageProcessor']

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__          =[
          'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST',
          'EfficientNetForImageClassification',
          'EfficientNetModel',
          'EfficientNetPreTrainedModel',
      ]

if TYPE_CHECKING:
      from .configuration_efficientnet import (
          EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
          EfficientNetConfig,
          EfficientNetOnnxConfig,
      )

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .image_processing_efficientnet import EfficientNetImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_efficientnet import (
                EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                EfficientNetForImageClassification,
                EfficientNetModel,
                EfficientNetPreTrainedModel,
            )

else:
      import sys

      lowercase__          =_LazyModule(__name__, globals()['__file__'], _import_structure)
