


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

		"""simple docstring"""

		def __init__(						self       ,  UpperCamelCase_       ,  UpperCamelCase_=13       ,  UpperCamelCase_=7       ,  UpperCamelCase_=True       ,  UpperCamelCase_=True       ,  UpperCamelCase_=True       ,  UpperCamelCase_=99       ,  UpperCamelCase_=32       ,  UpperCamelCase_=5       ,  UpperCamelCase_=4       ,  UpperCamelCase_=37       ,  UpperCamelCase_="gelu"       ,  UpperCamelCase_=0.1       ,  UpperCamelCase_=0.1       ,  UpperCamelCase_=512       ,  UpperCamelCase_=16       ,  UpperCamelCase_=2       ,  UpperCamelCase_=0.02       ,  UpperCamelCase_=3       ,  UpperCamelCase_=4       ,  UpperCamelCase_=None       ,  ):

							'''simple docstring'''


							UpperCamelCase__  :Optional[Any]				   =					parent
							UpperCamelCase__  :Union[str, Any]				   =					batch_size
							UpperCamelCase__  :List[str]				   =					seq_length
							UpperCamelCase__  :Optional[Any]				   =					is_training
							UpperCamelCase__  :int				   =					use_token_type_ids
							UpperCamelCase__  :Optional[int]				   =					use_labels
							UpperCamelCase__  :str				   =					vocab_size
							UpperCamelCase__  :List[Any]				   =					hidden_size
							UpperCamelCase__  :str				   =					num_hidden_layers
							UpperCamelCase__  :str				   =					num_attention_heads
							UpperCamelCase__  :Any				   =					intermediate_size
							UpperCamelCase__  :Any				   =					hidden_act
							UpperCamelCase__  :int				   =					hidden_dropout_prob
							UpperCamelCase__  :Any				   =					attention_probs_dropout_prob
							UpperCamelCase__  :Dict				   =					max_position_embeddings
							UpperCamelCase__  :List[str]				   =					type_vocab_size
							UpperCamelCase__  :List[Any]				   =					type_sequence_label_size
							UpperCamelCase__  :List[Any]				   =					initializer_range
							UpperCamelCase__  :str				   =					num_labels
							UpperCamelCase__  :List[Any]				   =					num_choices
							UpperCamelCase__  :Tuple				   =					scope
							UpperCamelCase__  :Any				   =					self.vocab_size - 1




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Optional[Any]				   =					ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size				)

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

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

							UpperCamelCase__  :List[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       ,  )

							UpperCamelCase__  :List[str]				   =					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       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  *UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :Tuple				   =					OpenAIGPTModel(config=UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()

							UpperCamelCase__  :Optional[int]				   =					model(UpperCamelCase_       ,  token_type_ids=UpperCamelCase_       ,  head_mask=UpperCamelCase_				)
							UpperCamelCase__  :List[Any]				   =					model(UpperCamelCase_       ,  token_type_ids=UpperCamelCase_				)
							UpperCamelCase__  :int				   =					model(UpperCamelCase_				)

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




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  *UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :Any				   =					OpenAIGPTLMHeadModel(UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()

							UpperCamelCase__  :Union[str, Any]				   =					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        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  *UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :Union[str, Any]				   =					OpenAIGPTDoubleHeadsModel(UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()

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

							'''simple docstring'''


							UpperCamelCase__  :Tuple				   =					self.num_labels
							UpperCamelCase__  :Union[str, Any]				   =					OpenAIGPTForSequenceClassification(UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()

							UpperCamelCase__  :Any				   =					ids_tensor([self.batch_size]       ,  self.type_sequence_label_size				)
							UpperCamelCase__  :int				   =					model(UpperCamelCase_       ,  token_type_ids=UpperCamelCase_       ,  labels=UpperCamelCase_				)
							self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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

							return config, inputs_dict



@require_torch
class   lowercase      (				A__      ,						A__      ,						A__      ,						unittest.TestCase   ):

		"""simple docstring"""

		_a       					=							(
		    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
		    if is_torch_available()
		    else ()
		)
		_a       					=							(
		    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
		)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
		_a       					=							(
		    {
		        'feature-extraction': OpenAIGPTModel,
		        'text-classification': OpenAIGPTForSequenceClassification,
		        'text-generation': OpenAIGPTLMHeadModel,
		        'zero-shot': OpenAIGPTForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''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        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_=False				):

							'''simple docstring'''


							UpperCamelCase__  :List[str]				   =					super()._prepare_for_class(UpperCamelCase_       ,  UpperCamelCase_       ,  return_labels=UpperCamelCase_				)

							if return_labels:
												if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
																	UpperCamelCase__  :str				   =					torch.zeros(
																	    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)       ,  dtype=torch.long       ,  device=UpperCamelCase_       ,  )
																	UpperCamelCase__  :List[Any]				   =					inputs_dict['''labels''']
																	UpperCamelCase__  :Any				   =					inputs_dict['''labels''']
																	UpperCamelCase__  :Tuple				   =					torch.zeros(
																	    (self.model_tester.batch_size, self.model_tester.num_choices)       ,  dtype=torch.long       ,  device=UpperCamelCase_       ,  )
																	UpperCamelCase__  :int				   =					torch.zeros(
																	    self.model_tester.batch_size       ,  dtype=torch.long       ,  device=UpperCamelCase_				)
							return inputs_dict




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					OpenAIGPTModelTester(self				)
							UpperCamelCase__  :Optional[int]				   =					ConfigTester(self       ,  config_class=UpperCamelCase_       ,  n_embd=37				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							self.config_tester.run_common_tests()




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Union[str, Any]				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_openai_gpt_model(*UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :List[Any]				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_lm_head_model(*UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_double_lm_head_model(*UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Union[str, Any]				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCamelCase_				)




		@slow
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCamelCase__  :Union[str, Any]				   =					OpenAIGPTModel.from_pretrained(UpperCamelCase_				)
												self.assertIsNotNone(UpperCamelCase_				)



@require_torch
class   lowercase      (				unittest.TestCase   ):

		"""simple docstring"""

		@slow
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Tuple				   =					OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''				)
							model.to(UpperCamelCase_				)
							UpperCamelCase__  :List[Any]				   =					torch.tensor([[481, 4735, 544]]       ,  dtype=torch.long       ,  device=UpperCamelCase_				)  # the president is
							UpperCamelCase__  :List[str]				   =					[
							    481,
							    4735,
							    544,
							    246,
							    963,
							    870,
							    762,
							    239,
							    244,
							    40477,
							    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__  :Optional[int]				   =					model.generate(UpperCamelCase_       ,  do_sample=UpperCamelCase_				)
							self.assertListEqual(output_ids[0].tolist()       ,  UpperCamelCase_				)



'''simple docstring'''
from dataclasses import dataclass
from typing import Optional, Tuple

import torch
from torch import nn
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
from transformers.utils import ModelOutput
@dataclass
class   lowercase      (				A__   ):

		"""simple docstring"""

		_a       					=							None
		_a       					=							None
		_a       					=							None
		_a       					=							None



class   lowercase      (				A__   ):

		"""simple docstring"""

		def __init__(						self       ,  UpperCamelCase_=1       ,  UpperCamelCase_=0       ,  UpperCamelCase_=2       ,  UpperCamelCase_=512       ,  UpperCamelCase_="cls"       ,  UpperCamelCase_=False       ,  UpperCamelCase_=True       ,  **UpperCamelCase_       ,  ):

							'''simple docstring'''


							super().__init__(pad_token_id=UpperCamelCase_       ,  bos_token_id=UpperCamelCase_       ,  eos_token_id=UpperCamelCase_       ,  **UpperCamelCase_				)
							UpperCamelCase__  :Optional[int]				   =					project_dim
							UpperCamelCase__  :List[str]				   =					pooler_fn
							UpperCamelCase__  :Dict				   =					learn_encoder
							UpperCamelCase__  :Any				   =					use_attention_mask



class   lowercase      (				A__   ):

		"""simple docstring"""

		_a       					=							[R'pooler', R'logit_scale']
		_a       					=							[R'position_ids', R'predictions.decoder.bias']
		_a       					=							'roberta'
		_a       					=							RobertaSeriesConfig




		def __init__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							super().__init__(UpperCamelCase_				)
							UpperCamelCase__  :Optional[Any]				   =					XLMRobertaModel(UpperCamelCase_				)
							UpperCamelCase__  :Tuple				   =					nn.Linear(config.hidden_size       ,  config.project_dim				)
							UpperCamelCase__  :Union[str, Any]				   =					getattr(UpperCamelCase_       ,  '''has_pre_transformation'''       ,  UpperCamelCase_				)
							if self.has_pre_transformation:
												UpperCamelCase__  :Any				   =					nn.Linear(config.hidden_size       ,  config.project_dim				)
												UpperCamelCase__  :str				   =					nn.LayerNorm(config.hidden_size       ,  eps=config.layer_norm_eps				)
							self.post_init()




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  UpperCamelCase_ = None       ,  ):

							'''simple docstring'''


							UpperCamelCase__  :Optional[int]				   =					return_dict if return_dict is not None else self.config.use_return_dict

							UpperCamelCase__  :str				   =					self.base_model(
							    input_ids=UpperCamelCase_       ,  attention_mask=UpperCamelCase_       ,  token_type_ids=UpperCamelCase_       ,  position_ids=UpperCamelCase_       ,  head_mask=UpperCamelCase_       ,  inputs_embeds=UpperCamelCase_       ,  encoder_hidden_states=UpperCamelCase_       ,  encoder_attention_mask=UpperCamelCase_       ,  output_attentions=UpperCamelCase_       ,  output_hidden_states=True if self.has_pre_transformation else output_hidden_states       ,  return_dict=UpperCamelCase_       ,  )

							if self.has_pre_transformation:
												UpperCamelCase__  :Dict				   =					outputs['''hidden_states'''][-2]
												UpperCamelCase__  :Optional[int]				   =					self.pre_LN(UpperCamelCase_				)
												UpperCamelCase__  :Optional[Any]				   =					self.transformation_pre(UpperCamelCase_				)

												return TransformationModelOutput(
												    projection_state=UpperCamelCase_       ,  last_hidden_state=outputs.last_hidden_state       ,  hidden_states=outputs.hidden_states       ,  attentions=outputs.attentions       ,  )
							else:
												UpperCamelCase__  :List[Any]				   =					self.transformation(outputs.last_hidden_state				)
												return TransformationModelOutput(
												    projection_state=UpperCamelCase_       ,  last_hidden_state=outputs.last_hidden_state       ,  hidden_states=outputs.hidden_states       ,  attentions=outputs.attentions       ,  )