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      A							:


   def __init__(self     :						List[str]       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						Optional[int]=1_3       ,  __UpperCAmelCase     :						Optional[Any]=7       ,  __UpperCAmelCase     :						Tuple=True       ,  __UpperCAmelCase     :						Optional[Any]=True       ,  __UpperCAmelCase     :						List[Any]=True       ,  __UpperCAmelCase     :						Optional[Any]=9_9       ,  __UpperCAmelCase     :						Tuple=3_2       ,  __UpperCAmelCase     :						List[Any]=5       ,  __UpperCAmelCase     :						Optional[int]=4       ,  __UpperCAmelCase     :						Tuple=3_7       ,  __UpperCAmelCase     :						List[str]="gelu"       ,  __UpperCAmelCase     :						Dict=0.1       ,  __UpperCAmelCase     :						Optional[Any]=0.1       ,  __UpperCAmelCase     :						Tuple=5_1_2       ,  __UpperCAmelCase     :						Dict=1_6       ,  __UpperCAmelCase     :						Optional[int]=2       ,  __UpperCAmelCase     :						str=0.02       ,  __UpperCAmelCase     :						int=3       ,  __UpperCAmelCase     :						int=4       ,  __UpperCAmelCase     :						List[Any]=None       ,  )						->				List[Any]:
         """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     :						List[Any]		)						->				Optional[int]:
         """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     :						List[str]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						Dict       ,  *__UpperCAmelCase     :						int		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTModel(config=__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  head_mask=__UpperCAmelCase		)
         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase		)
         UpperCAmelCase__								=  model(__UpperCAmelCase		)

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


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Union[str, Any]       ,  *__UpperCAmelCase     :						Optional[Any]		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTLMHeadModel(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

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


   def 			lowercase_      (self     :						int       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Any       ,  __UpperCAmelCase     :						Dict       ,  *__UpperCAmelCase     :						str		)						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTDoubleHeadsModel(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  labels=__UpperCAmelCase		)
         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]       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						List[str]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Optional[Any]       ,  *__UpperCAmelCase     :						Optional[Any]		)						->				int:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  OpenAIGPTForSequenceClassification(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

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





   def 			lowercase_      (self     :						List[str]		)						->				Optional[Any]:
         """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      A							(				UpperCAmelCase_		,				UpperCAmelCase_		,				UpperCAmelCase_		,				unittest.TestCase     ):
   __UpperCAmelCase : Optional[Any]      =			(
       (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
       if is_torch_available()
       else ()
   )
   __UpperCAmelCase : List[Any]      =			(
       (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
   )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
   __UpperCAmelCase : Optional[Any]      =			(
       {
           'feature-extraction': OpenAIGPTModel,
           'text-classification': OpenAIGPTForSequenceClassification,
           'text-generation': OpenAIGPTLMHeadModel,
           'zero-shot': OpenAIGPTForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )


   def 			lowercase_      (self     :						List[str]       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						int		)						->				Tuple:
         """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       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						str=False		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super()._prepare_for_class(__UpperCAmelCase       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)

         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=__UpperCAmelCase       ,  )
                     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=__UpperCAmelCase       ,  )
                     UpperCAmelCase__								=  torch.zeros(
                         self.model_tester.batch_size       ,  dtype=torch.long       ,  device=__UpperCAmelCase		)
         return inputs_dict


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTModelTester(self		)
         UpperCAmelCase__								=  ConfigTester(self       ,  config_class=__UpperCAmelCase       ,  n_embd=3_7		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Any:
         """simple docstring"""



         self.config_tester.run_common_tests()


   def 			lowercase_      (self     :						List[str]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_openai_gpt_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_lm_head_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_double_lm_head_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						Tuple		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__UpperCAmelCase		)





   @slow
   def 			lowercase_      (self     :						Optional[int]		)						->				Union[str, Any]:
         """simple docstring"""



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





@require_torch
class      A							(				unittest.TestCase     ):


   @slow
   def 			lowercase_      (self     :						List[Any]		)						->				int:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"		)
         model.to(__UpperCAmelCase		)
         UpperCAmelCase__								=  torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]]       ,  dtype=torch.long       ,  device=__UpperCAmelCase		)  # the president is
         UpperCAmelCase__								=  [
             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

         UpperCAmelCase__								=  model.generate(__UpperCAmelCase       ,  do_sample=__UpperCAmelCase		)
         self.assertListEqual(output_ids[0].tolist()       ,  __UpperCAmelCase		)




from __future__ import annotations

from collections import deque





class      A							:


   def __init__(self     :						Dict       ,  __UpperCAmelCase     :						list[str]		)						->				Optional[int]:
         """simple docstring"""



         UpperCAmelCase__								=  []
         self.adlist.append(
             {"value": "", "next_states": [], "fail_state": 0, "output": []}		)

         for keyword in keywords:
               self.add_keyword(__UpperCAmelCase		)
         self.set_fail_transitions()


   def 			lowercase_      (self     :						Tuple       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						str		)						->				int | None:
         """simple docstring"""



         for state in self.adlist[current_state]["next_states"]:
               if char == self.adlist[state]["value"]:
                     return state
         return None


   def 			lowercase_      (self     :						Dict       ,  __UpperCAmelCase     :						str		)						->				None:
         """simple docstring"""



         UpperCAmelCase__								=  0
         for character in keyword:
               UpperCAmelCase__								=  self.find_next_state(__UpperCAmelCase       ,  __UpperCAmelCase		)
               if next_state is None:
                     self.adlist.append(
                         {
                             "value": character,
                             "next_states": [],
                             "fail_state": 0,
                             "output": [],
                         }		)
                     self.adlist[current_state]["next_states"].append(len(self.adlist		) - 1		)
                     UpperCAmelCase__								=  len(self.adlist		) - 1
               else:
                     UpperCAmelCase__								=  next_state
         self.adlist[current_state]["output"].append(__UpperCAmelCase		)


   def 			lowercase_      (self     :						Optional[int]		)						->				None:
         """simple docstring"""



         UpperCAmelCase__								=  deque()
         for node in self.adlist[0]["next_states"]:
               q.append(__UpperCAmelCase		)
               UpperCAmelCase__								=  0
         while q:
               UpperCAmelCase__								=  q.popleft()
               for child in self.adlist[r]["next_states"]:
                     q.append(__UpperCAmelCase		)
                     UpperCAmelCase__								=  self.adlist[r]["fail_state"]
                     while (
                         self.find_next_state(__UpperCAmelCase       ,  self.adlist[child]["value"]		) is None
                         and state != 0
                     ):
                           UpperCAmelCase__								=  self.adlist[state]["fail_state"]
                     UpperCAmelCase__								=  self.find_next_state(
                         __UpperCAmelCase       ,  self.adlist[child]["value"]		)
                     if self.adlist[child]["fail_state"] is None:
                           UpperCAmelCase__								=  0
                     UpperCAmelCase__								=  (
                         self.adlist[child]["output"]
                         + self.adlist[self.adlist[child]["fail_state"]]["output"]
                     )





   def 			lowercase_      (self     :						Union[str, Any]       ,  __UpperCAmelCase     :						str		)						->				dict[str, list[int]]:
         """simple docstring"""



         UpperCAmelCase__								=  {}  # returns a dict with keywords and list of its occurrences
         UpperCAmelCase__								=  0
         for i in range(len(__UpperCAmelCase		)		):
               while (
                   self.find_next_state(__UpperCAmelCase       ,  string[i]		) is None
                   and current_state != 0
               ):
                     UpperCAmelCase__								=  self.adlist[current_state]["fail_state"]
               UpperCAmelCase__								=  self.find_next_state(__UpperCAmelCase       ,  string[i]		)
               if next_state is None:
                     UpperCAmelCase__								=  0
               else:
                     UpperCAmelCase__								=  next_state
                     for key in self.adlist[current_state]["output"]:
                           if key not in result:
                                 UpperCAmelCase__								=  []
                           result[key].append(i - len(__UpperCAmelCase		) + 1		)
         return result


if __name__ == "__main__":
      import doctest

      doctest.testmod()



