






import unittest

from transformers import XLMConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    XLMForMultipleChoice,
				    XLMForQuestionAnswering,
				    XLMForQuestionAnsweringSimple,
				    XLMForSequenceClassification,
				    XLMForTokenClassification,
				    XLMModel,
				    XLMWithLMHeadModel,
				)
				from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST

class 		_snake_case	:






			def __init__(							self		,       a		,       a=13		,       a=7		,       a=True		,       a=True		,       a=True		,       a=True		,       a=True		,       a=False		,       a=False		,       a=False		,       a=2		,       a=99		,       a=0		,       a=32		,       a=5		,       a=4		,       a=0.1		,       a=0.1		,       a=512		,       a=2		,       a=0.02		,       a=2		,       a=4		,       a="last"		,       a=True		,       a=None		,       a=0		,       )   ->							Tuple:
						SCREAMING_SNAKE_CASE							=			parent
						SCREAMING_SNAKE_CASE							=			batch_size
						SCREAMING_SNAKE_CASE							=			seq_length
						SCREAMING_SNAKE_CASE							=			is_training
						SCREAMING_SNAKE_CASE							=			use_input_lengths
						SCREAMING_SNAKE_CASE							=			use_token_type_ids
						SCREAMING_SNAKE_CASE							=			use_labels
						SCREAMING_SNAKE_CASE							=			gelu_activation
						SCREAMING_SNAKE_CASE							=			sinusoidal_embeddings
						SCREAMING_SNAKE_CASE							=			causal
						SCREAMING_SNAKE_CASE							=			asm
						SCREAMING_SNAKE_CASE							=			n_langs
						SCREAMING_SNAKE_CASE							=			vocab_size
						SCREAMING_SNAKE_CASE							=			n_special
						SCREAMING_SNAKE_CASE							=			hidden_size
						SCREAMING_SNAKE_CASE							=			num_hidden_layers
						SCREAMING_SNAKE_CASE							=			num_attention_heads
						SCREAMING_SNAKE_CASE							=			hidden_dropout_prob
						SCREAMING_SNAKE_CASE							=			attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE							=			max_position_embeddings
						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							=			summary_type
						SCREAMING_SNAKE_CASE							=			use_proj
						SCREAMING_SNAKE_CASE							=			scope
						SCREAMING_SNAKE_CASE							=			bos_token_id






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Tuple:
						SCREAMING_SNAKE_CASE							=			ids_tensor([self.batch_size, self.seq_length]		,       self.vocab_size)
						SCREAMING_SNAKE_CASE							=			random_attention_mask([self.batch_size, self.seq_length])

						SCREAMING_SNAKE_CASE							=			None
						if self.use_input_lengths:
									SCREAMING_SNAKE_CASE							=			(
									    ids_tensor([self.batch_size]		,       vocab_size=2) + self.seq_length - 2
									)  # small variation of seq_length

						SCREAMING_SNAKE_CASE							=			None
						if self.use_token_type_ids:
									SCREAMING_SNAKE_CASE							=			ids_tensor([self.batch_size, self.seq_length]		,       self.n_langs)

						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]		,       2).float()
									SCREAMING_SNAKE_CASE							=			ids_tensor([self.batch_size]		,       self.num_choices)

						SCREAMING_SNAKE_CASE							=			self.get_config()

						return (
						    config,
						    input_ids,
						    token_type_ids,
						    input_lengths,
						    sequence_labels,
						    token_labels,
						    is_impossible_labels,
						    choice_labels,
						    input_mask,
						)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[str]:
						return XLMConfig(
						    vocab_size=self.vocab_size		,       n_special=self.n_special		,       emb_dim=self.hidden_size		,       n_layers=self.num_hidden_layers		,       n_heads=self.num_attention_heads		,       dropout=self.hidden_dropout_prob		,       attention_dropout=self.attention_probs_dropout_prob		,       gelu_activation=self.gelu_activation		,       sinusoidal_embeddings=self.sinusoidal_embeddings		,       asm=self.asm		,       causal=self.causal		,       n_langs=self.n_langs		,       max_position_embeddings=self.max_position_embeddings		,       initializer_range=self.initializer_range		,       summary_type=self.summary_type		,       use_proj=self.use_proj		,       num_labels=self.num_labels		,       bos_token_id=self.bos_token_id		,       )






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							List[Any]:
						SCREAMING_SNAKE_CASE							=			XLMModel(config=a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE							=			model(a		,       lengths=a		,       langs=a)
						SCREAMING_SNAKE_CASE							=			model(a		,       langs=a)
						SCREAMING_SNAKE_CASE							=			model(a)
						self.parent.assertEqual(result.last_hidden_state.shape		,       (self.batch_size, self.seq_length, self.hidden_size))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							Optional[int]:
						SCREAMING_SNAKE_CASE							=			XLMWithLMHeadModel(a)
						model.to(a)
						model.eval()

						SCREAMING_SNAKE_CASE							=			model(a		,       token_type_ids=a		,       labels=a)
						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		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							str:
						SCREAMING_SNAKE_CASE							=			XLMForQuestionAnsweringSimple(a)
						model.to(a)
						model.eval()

						SCREAMING_SNAKE_CASE							=			model(a)

						SCREAMING_SNAKE_CASE							=			model(a		,       start_positions=a		,       end_positions=a)
						SCREAMING_SNAKE_CASE							=			outputs
						self.parent.assertEqual(result.start_logits.shape		,       (self.batch_size, self.seq_length))
						self.parent.assertEqual(result.end_logits.shape		,       (self.batch_size, self.seq_length))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							Tuple:
						SCREAMING_SNAKE_CASE							=			XLMForQuestionAnswering(a)
						model.to(a)
						model.eval()

						SCREAMING_SNAKE_CASE							=			model(a)

						SCREAMING_SNAKE_CASE							=			model(
						    a		,       start_positions=a		,       end_positions=a		,       cls_index=a		,       is_impossible=a		,       p_mask=a		,       )

						SCREAMING_SNAKE_CASE							=			model(
						    a		,       start_positions=a		,       end_positions=a		,       cls_index=a		,       is_impossible=a		,       )

						((SCREAMING_SNAKE_CASE)					,    )							=			result_with_labels.to_tuple()

						SCREAMING_SNAKE_CASE							=			model(a		,       start_positions=a		,       end_positions=a)

						((SCREAMING_SNAKE_CASE)					,    )							=			result_with_labels.to_tuple()

						self.parent.assertEqual(result_with_labels.loss.shape		,       ())
						self.parent.assertEqual(result.start_top_log_probs.shape		,       (self.batch_size, model.config.start_n_top))
						self.parent.assertEqual(result.start_top_index.shape		,       (self.batch_size, model.config.start_n_top))
						self.parent.assertEqual(
						    result.end_top_log_probs.shape		,       (self.batch_size, model.config.start_n_top * model.config.end_n_top))
						self.parent.assertEqual(
						    result.end_top_index.shape		,       (self.batch_size, model.config.start_n_top * model.config.end_n_top))
						self.parent.assertEqual(result.cls_logits.shape		,       (self.batch_size,))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							Dict:
						SCREAMING_SNAKE_CASE							=			XLMForSequenceClassification(a)
						model.to(a)
						model.eval()

						SCREAMING_SNAKE_CASE							=			model(a)
						SCREAMING_SNAKE_CASE							=			model(a		,       labels=a)
						self.parent.assertEqual(result.loss.shape		,       ())
						self.parent.assertEqual(result.logits.shape		,       (self.batch_size, self.type_sequence_label_size))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							int:
						SCREAMING_SNAKE_CASE							=			self.num_labels
						SCREAMING_SNAKE_CASE							=			XLMForTokenClassification(a)
						model.to(a)
						model.eval()

						SCREAMING_SNAKE_CASE							=			model(a		,       attention_mask=a		,       labels=a)
						self.parent.assertEqual(result.logits.shape		,       (self.batch_size, self.seq_length, self.num_labels))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       a		,       )   ->							Optional[int]:
						SCREAMING_SNAKE_CASE							=			self.num_choices
						SCREAMING_SNAKE_CASE							=			XLMForMultipleChoice(config=a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE							=			input_ids.unsqueeze(1).expand(-1		,       self.num_choices		,       -1).contiguous()
						SCREAMING_SNAKE_CASE							=			token_type_ids.unsqueeze(1).expand(-1		,       self.num_choices		,       -1).contiguous()
						SCREAMING_SNAKE_CASE							=			input_mask.unsqueeze(1).expand(-1		,       self.num_choices		,       -1).contiguous()
						SCREAMING_SNAKE_CASE							=			model(
						    a		,       attention_mask=a		,       token_type_ids=a		,       labels=a		,       )
						self.parent.assertEqual(result.logits.shape		,       (self.batch_size, self.num_choices))







			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Optional[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
						)					,    (
						    SCREAMING_SNAKE_CASE
						)					,    (
						    SCREAMING_SNAKE_CASE
						)					,    
						)							=			config_and_inputs
						SCREAMING_SNAKE_CASE							=			{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths}
						return config, inputs_dict



@require_torch
class 		_snake_case	(	A__ ,     A__ ,     A__ ,     unittest.TestCase       ):
			_lowercase		:     Optional[int]        =				(
			    (
			        XLMModel,
			        XLMWithLMHeadModel,
			        XLMForQuestionAnswering,
			        XLMForSequenceClassification,
			        XLMForQuestionAnsweringSimple,
			        XLMForTokenClassification,
			        XLMForMultipleChoice,
			    )
			    if is_torch_available()
			    else ()
			)
			_lowercase		:     Union[str, Any]        =				(
			    (XLMWithLMHeadModel,) if is_torch_available() else ()
			)  # TODO (PVP): Check other models whether language generation is also applicable
			_lowercase		:     List[Any]        =				(
			    {
			        '''feature-extraction''': XLMModel,
			        '''fill-mask''': XLMWithLMHeadModel,
			        '''question-answering''': XLMForQuestionAnsweringSimple,
			        '''text-classification''': XLMForSequenceClassification,
			        '''text-generation''': XLMWithLMHeadModel,
			        '''token-classification''': XLMForTokenClassification,
			        '''zero-shot''': XLMForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a)   ->							int:
						if (
						    pipeline_test_casse_name == "QAPipelineTests"
						    and tokenizer_name is not None
						    and not tokenizer_name.endswith('Fast')
						):
									# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
									# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
									# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
									return True

						return False






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a=False)   ->							List[Any]:
						SCREAMING_SNAKE_CASE							=			super()._prepare_for_class(a		,       a		,       return_labels=a)

						if return_labels:
									if model_class.__name__ == "XLMForQuestionAnswering":
												SCREAMING_SNAKE_CASE							=			torch.zeros(
												    self.model_tester.batch_size		,       dtype=torch.long		,       device=a)
												SCREAMING_SNAKE_CASE							=			torch.zeros(
												    self.model_tester.batch_size		,       dtype=torch.long		,       device=a)

						return inputs_dict






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							str:
						SCREAMING_SNAKE_CASE							=			XLMModelTester(self)
						SCREAMING_SNAKE_CASE							=			ConfigTester(self		,       config_class=a		,       emb_dim=37)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						self.config_tester.run_common_tests()






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_model(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_lm_head(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Optional[int]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_simple_qa(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_qa(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_sequence_classif(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							str:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_token_classif(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[str]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_xlm_for_multiple_choice(*a)






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a=False		,       a=1)   ->							List[str]:
						self.assertIsInstance(a		,       a)
						self.assertListEqual(
						    [isinstance(a		,       a) for iter_attentions in attentions]		,       [True] * len(a))
						self.assertEqual(len(a)		,       (max_length - min_length) * num_beam_groups)

						for idx, iter_attentions in enumerate(a):
									# adds PAD dummy token
									SCREAMING_SNAKE_CASE							=			min_length + idx + 1
									SCREAMING_SNAKE_CASE							=			min_length + idx + 1

									SCREAMING_SNAKE_CASE							=			(
									    batch_size * num_beam_groups,
									    config.num_attention_heads,
									    tgt_len,
									    src_len,
									)
									# check attn size
									self.assertListEqual(
									    [layer_attention.shape for layer_attention in iter_attentions]		,       [expected_shape] * len(a))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a		,       a		,       a		,       a=False		,       a=1)   ->							Dict:
						self.assertIsInstance(a		,       a)
						self.assertListEqual(
						    [isinstance(a		,       a) for iter_hidden_states in hidden_states]		,       [True] * len(a)		,       )
						self.assertEqual(len(a)		,       (max_length - min_length) * num_beam_groups)

						for idx, iter_hidden_states in enumerate(a):
									# adds PAD dummy token
									SCREAMING_SNAKE_CASE							=			min_length + idx + 1
									SCREAMING_SNAKE_CASE							=			(batch_size * num_beam_groups, seq_len, config.hidden_size)
									# check hidden size
									self.assertListEqual(
									    [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]		,       [expected_shape] * len(a)		,       )
						pass







			@slow
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Tuple:
						for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									SCREAMING_SNAKE_CASE							=			XLMModel.from_pretrained(a)
									self.assertIsNotNone(a)



@require_torch
class 		_snake_case	(	unittest.TestCase       ):






			@slow
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[str]:
						SCREAMING_SNAKE_CASE							=			XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048')
						model.to(a)
						SCREAMING_SNAKE_CASE							=			torch.tensor([[14, 447]]		,       dtype=torch.long		,       device=a)  # the president
						SCREAMING_SNAKE_CASE							=			[
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						    14,
						    447,
						]  # the president the president the president the president the president the president the president the president the president the president
						# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
						SCREAMING_SNAKE_CASE							=			model.generate(a		,       do_sample=a)
						self.assertListEqual(output_ids[0].cpu().numpy().tolist()		,       a)






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


 def __init__(    self  : str			,							a__  : Union[str, Any]			,							a__  : Union[str, Any]=13			,							a__  : Union[str, Any]=7			,							a__  : Any=True			,							a__  : str=True			,							a__  : Optional[Any]=True			,							a__  : Any=99			,							a__  : Dict=32			,							a__  : Tuple=5			,							a__  : List[Any]=4			,							a__  : List[Any]=37			,							a__  : List[str]="gelu"			,							a__  : Dict=0.1			,							a__  : str=0.1			,							a__  : str=512			,							a__  : List[str]=16			,							a__  : Dict=2			,							a__  : Union[str, Any]=0.02			,							a__  : Dict=3			,							a__  : List[Any]=4			,							a__  : Optional[int]=None			,							):
  '''simple docstring'''

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


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )

  lowerCAmelCase__     :   Dict     		=	None
  if self.use_token_type_ids:
   lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.type_vocab_size    )

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

  lowerCAmelCase__     :   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			,							)

  lowerCAmelCase__     :   Optional[Any]     		=	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    _A	(    self  : Dict			,							a__  : Any			,							a__  : Any			,							a__  : int			,							a__  : str			,							*a__  : Optional[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModel(config=a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							head_mask=a__    )
  lowerCAmelCase__     :   Optional[int]     		=	model(a__			,							token_type_ids=a__    )
  lowerCAmelCase__     :   Any     		=	model(a__    )

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


 def    _A	(    self  : Optional[int]			,							a__  : List[Any]			,							a__  : int			,							a__  : Dict			,							a__  : Any			,							*a__  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	OpenAIGPTLMHeadModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Dict     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : List[str]			,							a__  : str			,							a__  : Dict			,							a__  : Union[str, Any]			,							a__  : int			,							*a__  : Dict    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	OpenAIGPTDoubleHeadsModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : Any			,							a__  : Any			,							a__  : Union[str, Any]			,							a__  : Optional[int]			,							a__  : Any			,							*a__  : List[str]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	self.num_labels
  lowerCAmelCase__     :   Union[str, Any]     		=	OpenAIGPTForSequenceClassification(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
  lowerCAmelCase__     :   Tuple     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.prepare_config_and_inputs()
  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Union[str, Any]     		=	config_and_inputs
  lowerCAmelCase__     :   str     		=	{
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
      "head_mask": head_mask,
  }

  return config, inputs_dict




@require_torch
class    lowerCAmelCase       (     UpperCamelCase_    ,  UpperCamelCase_    ,  UpperCamelCase_    ,  unittest.TestCase  ):
 A_				:				str	=			(
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 A_				:				Any	=			(
     (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
 )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
 A_				:				int	=			(
     {
         """feature-extraction""": OpenAIGPTModel,
         """text-classification""": OpenAIGPTForSequenceClassification,
         """text-generation""": OpenAIGPTLMHeadModel,
         """zero-shot""": OpenAIGPTForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )


 def    _A	(    self  : List[Any]			,							a__  : Optional[Any]			,							a__  : Optional[int]			,							a__  : Optional[Any]			,							a__  : List[Any]			,							a__  : int    ):
  '''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    _A	(    self  : Dict			,							a__  : Optional[int]			,							a__  : List[Any]			,							a__  : List[Any]=False    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	super()._prepare_for_class(a__			,							a__			,							return_labels=a__    )

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


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModelTester(self    )
  lowerCAmelCase__     :   Any     		=	ConfigTester(self			,							config_class=a__			,							n_embd=37    )


 def    _A	(    self  : List[str]    ):
  '''simple docstring'''

  self.config_tester.run_common_tests()


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Dict     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_model(*a__    )


 def    _A	(    self  : Union[str, Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_lm_head_model(*a__    )


 def    _A	(    self  : int    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_double_lm_head_model(*a__    )


 def    _A	(    self  : str    ):
  '''simple docstring'''

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


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase__     :   Any     		=	OpenAIGPTModel.from_pretrained(a__    )
   self.assertIsNotNone(a__    )




@require_torch
class    lowerCAmelCase       (     unittest.TestCase  ):


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   int     		=	OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"    )
  model.to(a__    )
  lowerCAmelCase__     :   Union[str, Any]     		=	torch.tensor([[481, 4735, 544]]			,							dtype=torch.long			,							device=a__    )  # the president is
  lowerCAmelCase__     :   Optional[int]     		=	[
      481,
      4735,
      544,
      246,
      963,
      870,
      762,
      239,
      244,
      4_0477,
      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

  lowerCAmelCase__     :   Optional[int]     		=	model.generate(a__			,							do_sample=a__    )
  self.assertListEqual(output_ids[0].tolist()			,							a__    )





