






"""simple docstring"""







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 ,		snake_case__ ,		snake_case__=13 ,		snake_case__=7 ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=99 ,		snake_case__=32 ,		snake_case__=5 ,		snake_case__=4 ,		snake_case__=37 ,		snake_case__="gelu" ,		snake_case__=0.1 ,		snake_case__=0.1 ,		snake_case__=5_12 ,		snake_case__=16 ,		snake_case__=2 ,		snake_case__=0.02 ,		snake_case__=3 ,		snake_case__=4 ,		snake_case__=None ,		)			->			str:



         """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 		UpperCamelCase_				(      self				)			->			List[str]:



         """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 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			Tuple:



         """simple docstring"""





         UpperCAmelCase	    =			OpenAIGPTModel(config=snake_case__				)
         model.to(snake_case__				)
         model.eval()

         UpperCAmelCase	    =			model(snake_case__ ,		token_type_ids=snake_case__ ,		head_mask=snake_case__				)
         UpperCAmelCase	    =			model(snake_case__ ,		token_type_ids=snake_case__				)
         UpperCAmelCase	    =			model(snake_case__				)

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



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			Union[str, Any]:



         """simple docstring"""





         UpperCAmelCase	    =			OpenAIGPTLMHeadModel(snake_case__				)
         model.to(snake_case__				)
         model.eval()

         UpperCAmelCase	    =			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 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			int:



         """simple docstring"""





         UpperCAmelCase	    =			OpenAIGPTDoubleHeadsModel(snake_case__				)
         model.to(snake_case__				)
         model.eval()

         UpperCAmelCase	    =			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 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			Tuple:



         """simple docstring"""





         UpperCAmelCase	    =			self.num_labels
         UpperCAmelCase	    =			OpenAIGPTForSequenceClassification(snake_case__				)
         model.to(snake_case__				)
         model.eval()

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



  def 		UpperCamelCase_				(      self				)			->			str:



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



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__				)			->			List[str]:



         """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 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__=False				)			->			Tuple:



         """simple docstring"""





         UpperCAmelCase	    =			super()._prepare_for_class(snake_case__ ,		snake_case__ ,		return_labels=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=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=snake_case__ ,		)
                       UpperCAmelCase	    =			torch.zeros(
                           self.model_tester.batch_size ,		dtype=torch.long ,		device=snake_case__				)
         return inputs_dict



  def 		UpperCamelCase_				(      self				)			->			Union[str, Any]:



         """simple docstring"""





         UpperCAmelCase	    =			OpenAIGPTModelTester(self				)
         UpperCAmelCase	    =			ConfigTester(self ,		config_class=snake_case__ ,		n_embd=37				)



  def 		UpperCamelCase_				(      self				)			->			str:



         """simple docstring"""





         self.config_tester.run_common_tests()



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



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_openai_gpt_model(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Optional[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_lm_head_model(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_double_lm_head_model(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			str:



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*snake_case__				)



  @slow
  def 		UpperCamelCase_				(      self				)			->			Union[str, Any]:



         """simple docstring"""





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





@require_torch
class   UpperCamelCase_ (       unittest.TestCase  ):



  @slow
  def 		UpperCamelCase_				(      self				)			->			Union[str, Any]:



         """simple docstring"""





         UpperCAmelCase	    =			OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""				)
         model.to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor([[4_81, 47_35, 5_44]] ,		dtype=torch.long ,		device=snake_case__				)  # the president is
         UpperCAmelCase	    =			[
             4_81,
             47_35,
             5_44,
             2_46,
             9_63,
             8_70,
             7_62,
             2_39,
             2_44,
             4_04_77,
             2_44,
             2_49,
             7_19,
             8_81,
             4_87,
             5_44,
             2_40,
             2_44,
             6_03,
             4_81,
         ]  # the president is a very good man. " \n " i\'m sure he is, " said the

         UpperCAmelCase	    =			model.generate(snake_case__ ,		do_sample=snake_case__				)
         self.assertListEqual(output_ids[0].tolist() ,		snake_case__				)








"""simple docstring"""







import random
from typing import Any






def       _lowerCAmelCase       (      lowerCAmelCase		):







       '''simple docstring'''
       for _ in range(len(lowerCAmelCase		)		):
              UpperCAmelCase	    =			random.randint(0	,      len(lowerCAmelCase		) - 1		)
              UpperCAmelCase	    =			random.randint(0	,      len(lowerCAmelCase		) - 1		)
              UpperCAmelCase    ,       UpperCAmelCase	    =			data[b], data[a]
       return data


if __name__ == "__main__":
 lowerCAmelCase_	:    Tuple            =      [0, 1, 2, 3, 4, 5, 6, 7]
 lowerCAmelCase_	:    List[str]            =      ['''python''', '''says''', '''hello''', '''!''']
 print('''Fisher-Yates Shuffle:''')
 print('''List''', integers, strings)
 print('''FY Shuffle''', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
