



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






	"""simple docstring"""


	def __init__(     self     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						Dict=13						,  __UpperCAmelCase     :						str=7						,  __UpperCAmelCase     :						Optional[int]=True						,  __UpperCAmelCase     :						Union[str, Any]=True						,  __UpperCAmelCase     :						Union[str, Any]=True						,  __UpperCAmelCase     :						List[Any]=99						,  __UpperCAmelCase     :						Any=32						,  __UpperCAmelCase     :						int=5						,  __UpperCAmelCase     :						List[str]=4						,  __UpperCAmelCase     :						Any=37						,  __UpperCAmelCase     :						Any="gelu"						,  __UpperCAmelCase     :						Dict=0.1						,  __UpperCAmelCase     :						Tuple=0.1						,  __UpperCAmelCase     :						Dict=512						,  __UpperCAmelCase     :						str=16						,  __UpperCAmelCase     :						int=2						,  __UpperCAmelCase     :						Optional[int]=0.02						,  __UpperCAmelCase     :						Union[str, Any]=3						,  __UpperCAmelCase     :						List[str]=4						,  __UpperCAmelCase     :						Dict=None						,  )      ->			List[Any]:
							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   _SCREAMING_SNAKE_CASE		(     self     :						Union[str, Any]					)      ->			Any:
							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   _SCREAMING_SNAKE_CASE		(     self     :						Any						,  __UpperCAmelCase     :						Optional[int]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						str						,  *__UpperCAmelCase     :						int					)      ->			Dict:
							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   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						int						,  *__UpperCAmelCase     :						int					)      ->			Any:
							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   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  __UpperCAmelCase     :						Optional[int]						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						Tuple						,  *__UpperCAmelCase     :						Tuple					)      ->			List[str]:
							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   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]						,  __UpperCAmelCase     :						List[Any]						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						Optional[int]						,  *__UpperCAmelCase     :						Tuple					)      ->			Dict:
							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   _SCREAMING_SNAKE_CASE		(     self     :						int					)      ->			int:
							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 		lowercase						(			snake_case__			,   snake_case__			,   snake_case__			,   unittest.TestCase):






	"""simple docstring"""


	a__				: Tuple		       =							(
	    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
	    if is_torch_available()
	    else ()
	)
	a__				: Optional[int]		       =							(
	    (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   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[Any]						,  __UpperCAmelCase     :						Dict					)      ->			List[str]:
							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   _SCREAMING_SNAKE_CASE		(     self     :						str						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						List[str]=False					)      ->			List[str]:
							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   _SCREAMING_SNAKE_CASE		(     self     :						int					)      ->			Dict:
							UpperCAmelCase_=       OpenAIGPTModelTester(self					)
							UpperCAmelCase_=       ConfigTester(self						,  config_class=__UpperCAmelCase						,  n_embd=37					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]					)      ->			Tuple:
							self.config_tester.run_common_tests()




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple					)      ->			List[Any]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_openai_gpt_model(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						str					)      ->			List[Any]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_lm_head_model(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Union[str, Any]					)      ->			Optional[Any]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_double_lm_head_model(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						List[Any]					)      ->			List[str]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__UpperCAmelCase					)




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






@require_torch
class 		lowercase						(			unittest.TestCase):






	"""simple docstring"""


	@slow
	def   _SCREAMING_SNAKE_CASE		(     self     :						Any					)      ->			Tuple:
							UpperCAmelCase_=       OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""					)
							model.to(__UpperCAmelCase					)
							UpperCAmelCase_=       torch.tensor([[481, 4_735, 544]]						,  dtype=torch.long						,  device=__UpperCAmelCase					)  # the president is
							UpperCAmelCase_=       [
							    481,
							    4_735,
							    544,
							    246,
							    963,
							    870,
							    762,
							    239,
							    244,
							    40_477,
							    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(__UpperCAmelCase						,  do_sample=__UpperCAmelCase					)
							self.assertListEqual(output_ids[0].tolist()						,  __UpperCAmelCase					)









import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
	import torch_xla.core.xla_model as xm
	import torch_xla.debug.metrics as met






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	def __init__(     self     :						Any						,  *__UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]=None						,  __UpperCAmelCase     :						Optional[int]=None						,  **__UpperCAmelCase     :						Dict					)      ->			Optional[int]:
							super().__init__(*__UpperCAmelCase						,  **__UpperCAmelCase					)
							UpperCAmelCase_=       eval_examples
							UpperCAmelCase_=       post_process_function




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple						,  __UpperCAmelCase     :						Optional[Dataset] = None						,  __UpperCAmelCase     :						Optional[Any]=None						,  __UpperCAmelCase     :						Optional[List[str]] = None						,  __UpperCAmelCase     :						str = "eval"						,  **__UpperCAmelCase     :						Any						,  )      ->			Dict[str, float]:
							UpperCAmelCase_=       gen_kwargs.copy()
							UpperCAmelCase_=       (
							    gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length"""					) is not None else self.args.generation_max_length
							)
							UpperCAmelCase_=       (
							    gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams"""					) is not None else self.args.generation_num_beams
							)
							UpperCAmelCase_=       gen_kwargs

							UpperCAmelCase_=       self.eval_dataset if eval_dataset is None else eval_dataset
							UpperCAmelCase_=       self.get_eval_dataloader(__UpperCAmelCase					)
							UpperCAmelCase_=       self.eval_examples if eval_examples is None else eval_examples

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Evaluation"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics
							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)

							if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
													# Only the main node write the results by default
													UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase					)
													UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

													# Prefix all keys with metric_key_prefix + '_'
													for key in list(metrics.keys()					):
																			if not key.startswith(F"""{metric_key_prefix}_"""					):
																									UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)

													metrics.update(output.metrics					)
							else:
													UpperCAmelCase_=       output.metrics

							if self.args.should_log:
													# Only the main node log the results by default
													self.log(__UpperCAmelCase					)

							if self.args.tpu_metrics_debug or self.args.debug:
													# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
													xm.master_print(met.metrics_report()					)

							UpperCAmelCase_=       self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  __UpperCAmelCase					)
							return metrics




	def   _SCREAMING_SNAKE_CASE		(     self     :						int						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[int]=None						,  __UpperCAmelCase     :						str = "test"						,  **__UpperCAmelCase     :						List[str]					)      ->			Tuple:
							UpperCAmelCase_=       gen_kwargs.copy()

							UpperCAmelCase_=       self.get_test_dataloader(__UpperCAmelCase					)

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Prediction"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics

							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)
							if self.post_process_function is None or self.compute_metrics is None:
													return output

							UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase						,  """predict"""					)
							UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()					):
													if not key.startswith(F"""{metric_key_prefix}_"""					):
																			UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)
							metrics.update(output.metrics					)
							return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=__UpperCAmelCase					)




