


"""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_			:

 """simple docstring"""





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




 def 						UpperCAmelCase_   (				self    :       int     ) ->			Tuple:
      __SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size     )

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

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

      __SCREAMING_SNAKE_CASE		     =       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    ,    )

      __SCREAMING_SNAKE_CASE		     =       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    :       Optional[Any]    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       Optional[Any]    ,    UpperCAmelCase__    :       str    ,    *UpperCAmelCase__    :       List[str]     ) ->			Union[str, Any]:
      __SCREAMING_SNAKE_CASE		     =       OpenAIGPTModel(config=UpperCAmelCase__     )
      model.to(UpperCAmelCase__     )
      model.eval()

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

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




 def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       Dict    ,    *UpperCAmelCase__    :       Dict     ) ->			Any:
      __SCREAMING_SNAKE_CASE		     =       OpenAIGPTLMHeadModel(UpperCAmelCase__     )
      model.to(UpperCAmelCase__     )
      model.eval()

      __SCREAMING_SNAKE_CASE		     =       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 						UpperCAmelCase_   (				self    :       Union[str, Any]    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       List[Any]    ,    *UpperCAmelCase__    :       Optional[int]     ) ->			List[Any]:
      __SCREAMING_SNAKE_CASE		     =       OpenAIGPTDoubleHeadsModel(UpperCAmelCase__     )
      model.to(UpperCAmelCase__     )
      model.eval()

      __SCREAMING_SNAKE_CASE		     =       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 						UpperCAmelCase_   (				self    :       Union[str, Any]    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       Any    ,    *UpperCAmelCase__    :       Dict     ) ->			List[str]:
      __SCREAMING_SNAKE_CASE		     =       self.num_labels
      __SCREAMING_SNAKE_CASE		     =       OpenAIGPTForSequenceClassification(UpperCAmelCase__     )
      model.to(UpperCAmelCase__     )
      model.eval()

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




 def 						UpperCAmelCase_   (				self    :       str     ) ->			List[Any]:
      __SCREAMING_SNAKE_CASE		     =       self.prepare_config_and_inputs()
      (
          (
          __SCREAMING_SNAKE_CASE						
      )     ,						(
          __SCREAMING_SNAKE_CASE						
      )     ,						(
          __SCREAMING_SNAKE_CASE						
      )     ,						(
          __SCREAMING_SNAKE_CASE						
      )     ,						(
          __SCREAMING_SNAKE_CASE						
      )     ,						(
          __SCREAMING_SNAKE_CASE						
      )     ,						(
          __SCREAMING_SNAKE_CASE						
      )     ,												
      )		     =       config_and_inputs
      __SCREAMING_SNAKE_CASE		     =       {
          "input_ids": input_ids,
          "token_type_ids": token_type_ids,
          "head_mask": head_mask,
      }

      return config, inputs_dict




@require_torch
class 				UpperCamelCase_			(				UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase    ,						unittest.TestCase):

 """simple docstring"""





 snake_case__       :						int					      =    (
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 snake_case__       :						Tuple					      =    (
     (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
 )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
 snake_case__       :						Union[str, Any]					      =    (
     {
         "feature-extraction": OpenAIGPTModel,
         "text-classification": OpenAIGPTForSequenceClassification,
         "text-generation": OpenAIGPTLMHeadModel,
         "zero-shot": OpenAIGPTForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )




 def 						UpperCAmelCase_   (				self    :       Tuple    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Optional[Any]    ,    UpperCAmelCase__    :       Tuple     ) ->			Tuple:
      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    :       Union[str, Any]    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       List[Any]=False     ) ->			Optional[Any]:
      __SCREAMING_SNAKE_CASE		     =       super()._prepare_for_class(UpperCAmelCase__    ,    UpperCAmelCase__    ,    return_labels=UpperCAmelCase__     )

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




 def 						UpperCAmelCase_   (				self    :       int     ) ->			Dict:
      __SCREAMING_SNAKE_CASE		     =       OpenAIGPTModelTester(self     )
      __SCREAMING_SNAKE_CASE		     =       ConfigTester(self    ,    config_class=UpperCAmelCase__    ,    n_embd=3_7     )




 def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Dict:
      self.config_tester.run_common_tests()




 def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			str:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_openai_gpt_model(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Union[str, Any]:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       List[Any]     ) ->			Dict:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_double_lm_head_model(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Tuple:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCAmelCase__     )




 @slow
 def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Any:
      for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __SCREAMING_SNAKE_CASE		     =       OpenAIGPTModel.from_pretrained(UpperCAmelCase__     )
           self.assertIsNotNone(UpperCAmelCase__     )




@require_torch
class 				UpperCamelCase_			(				unittest.TestCase):

 """simple docstring"""





 @slow
 def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			List[Any]:
      __SCREAMING_SNAKE_CASE		     =       OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"     )
      model.to(UpperCAmelCase__     )
      __SCREAMING_SNAKE_CASE		     =       torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]]    ,    dtype=torch.long    ,    device=UpperCAmelCase__     )  # the president is
      __SCREAMING_SNAKE_CASE		     =       [
          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

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




"""simple docstring"""







import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser




def      UpperCAmelCase__ (lowerCAmelCase_=None						,		lowerCAmelCase_=None     ):




					'''simple docstring'''


					return field(default_factory=lambda: default						,		metadata=lowerCAmelCase_     )




@dataclass
class 				UpperCamelCase_			:

	"""simple docstring"""





	snake_case__       :						str					      =    field(
	    metadata={"help": "The csv file to plot."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Disable logarithmic scale when plotting"}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={
	        "help": "Whether the csv file has training results or inference results. Defaults to inference results."
	    }    ,						)
	snake_case__       :						Optional[str]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."}    ,						)
	snake_case__       :						Optional[List[str]]					      =    list_field(
	    default=UpperCamelCase    ,						metadata={"help": "List of model names that are used instead of the ones in the csv file."})




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					try:
										int(lowerCAmelCase_     )
										return True
					except ValueError:
										return False




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					try:
										float(lowerCAmelCase_     )
										return True
					except ValueError:
										return False




class 				UpperCamelCase_			:

	"""simple docstring"""





	def __init__(				self    :       str    ,    UpperCAmelCase__    :       Dict     ) ->			Optional[Any]:
						__SCREAMING_SNAKE_CASE		     =       args
						__SCREAMING_SNAKE_CASE		     =       defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}     )

						with open(self.args.csv_file    ,    newline=""     ) as csv_file:
											__SCREAMING_SNAKE_CASE		     =       csv.DictReader(UpperCAmelCase__     )
											for row in reader:
																__SCREAMING_SNAKE_CASE		     =       row["model"]
																self.result_dict[model_name]["bsz"].append(int(row["batch_size"]     )     )
																self.result_dict[model_name]["seq_len"].append(int(row["sequence_length"]     )     )
																if can_convert_to_int(row["result"]     ):
																					# value is not None
																					__SCREAMING_SNAKE_CASE		     =       int(row["result"]     )
																elif can_convert_to_float(row["result"]     ):
																					# value is not None
																					__SCREAMING_SNAKE_CASE		     =       float(row["result"]     )




	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       plt.subplots()
						__SCREAMING_SNAKE_CASE		     =       "Time usage" if self.args.is_time else "Memory usage"
						__SCREAMING_SNAKE_CASE		     =       title_str + " for training" if self.args.is_train else title_str + " for inference"

						if not self.args.no_log_scale:
											# set logarithm scales
											ax.set_xscale("log"     )
											ax.set_yscale("log"     )

						for axis in [ax.xaxis, ax.yaxis]:
											axis.set_major_formatter(ScalarFormatter()     )

						for model_name_idx, model_name in enumerate(self.result_dict.keys()     ):
											__SCREAMING_SNAKE_CASE		     =       sorted(set(self.result_dict[model_name]["bsz"]     )     )
											__SCREAMING_SNAKE_CASE		     =       sorted(set(self.result_dict[model_name]["seq_len"]     )     )
											__SCREAMING_SNAKE_CASE		     =       self.result_dict[model_name]["result"]

											((__SCREAMING_SNAKE_CASE)     ,						(__SCREAMING_SNAKE_CASE))		     =       (
											    (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
											)

											__SCREAMING_SNAKE_CASE		     =       (
											    model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
											)

											for inner_loop_value in inner_loop_array:
																if self.args.plot_along_batch:
																					__SCREAMING_SNAKE_CASE		     =       np.asarray(
																					    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results]    ,    dtype=UpperCAmelCase__    ,    )
																else:
																					__SCREAMING_SNAKE_CASE		     =       np.asarray(
																					    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results]    ,    dtype=np.floataa    ,    )

																((__SCREAMING_SNAKE_CASE)     ,						(__SCREAMING_SNAKE_CASE))		     =       (
																    ("batch_size", "len") if self.args.plot_along_batch else ("in #tokens", "bsz")
																)

																__SCREAMING_SNAKE_CASE		     =       np.asarray(UpperCAmelCase__    ,    UpperCAmelCase__     )[: len(UpperCAmelCase__     )]
																plt.scatter(
																    UpperCAmelCase__    ,    UpperCAmelCase__    ,    label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}"""     )
																plt.plot(UpperCAmelCase__    ,    UpperCAmelCase__    ,    "--"     )

											title_str += F""" {label_model_name} vs."""

						__SCREAMING_SNAKE_CASE		     =       title_str[:-4]
						__SCREAMING_SNAKE_CASE		     =       "Time in s" if self.args.is_time else "Memory in MB"

						# plot
						plt.title(UpperCAmelCase__     )
						plt.xlabel(UpperCAmelCase__     )
						plt.ylabel(UpperCAmelCase__     )
						plt.legend()

						if self.args.figure_png_file is not None:
											plt.savefig(self.args.figure_png_file     )
						else:
											plt.show()




def      UpperCAmelCase__ ():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       HfArgumentParser(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       parser.parse_args_into_dataclasses()[0]
					__SCREAMING_SNAKE_CASE		     =       Plot(args=lowerCAmelCase_     )
					plot.plot()


if __name__ == "__main__":
		main()
