


'''simple docstring'''







import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

					if is_vision_available():
										from transformers import MaskaFormerImageProcessor

if is_vision_available():
					from PIL import Image


class 		__UpperCAmelCase   :


							def __init__( self					,     lowerCAmelCase_					,     lowerCAmelCase_=2					,     lowerCAmelCase_=True					,     lowerCAmelCase_=False					,     lowerCAmelCase_=10					,     lowerCAmelCase_=3					,     lowerCAmelCase_=32 * 8					,     lowerCAmelCase_=32 * 8					,     lowerCAmelCase_=4					,     lowerCAmelCase_=64					,     ):





								"""simple docstring"""






								_snake_case     		=	parent
								_snake_case     		=	batch_size
								_snake_case     		=	is_training
								_snake_case     		=	use_auxiliary_loss
								_snake_case     		=	num_queries
								_snake_case     		=	num_channels
								_snake_case     		=	min_size
								_snake_case     		=	max_size
								_snake_case     		=	num_labels
								_snake_case     		=	hidden_dim
								_snake_case     		=	hidden_dim


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]						).to(
								    _SCREAMING_SNAKE_CASE						)

								_snake_case     		=	torch.ones([self.batch_size, self.min_size, self.max_size]					,     device=_SCREAMING_SNAKE_CASE						)

								_snake_case     		=	(
								    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]					,     device=_SCREAMING_SNAKE_CASE						) > 0.5
								).float()
								_snake_case     		=	(torch.rand((self.batch_size, self.num_labels)					,     device=_SCREAMING_SNAKE_CASE						) > 0.5).long()

								_snake_case     		=	self.get_config()
								return config, pixel_values, pixel_mask, mask_labels, class_labels


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	MaskaFormerConfig(
								    hidden_size=self.hidden_dim					,     )
								_snake_case     		=	self.num_queries
								_snake_case     		=	self.num_labels

								_snake_case     		=	[1, 1, 1, 1]
								_snake_case     		=	self.num_channels

								_snake_case     		=	64
								_snake_case     		=	1_28
								_snake_case     		=	self.hidden_dim
								_snake_case     		=	self.hidden_dim
								_snake_case     		=	self.hidden_dim
								return config


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case		,				_snake_case		,				_snake_case		,				_snake_case		,				_snake_case     		=	self.prepare_config_and_inputs()
								_snake_case     		=	{'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
								return config, inputs_dict


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	output.encoder_hidden_states
								_snake_case     		=	output.pixel_decoder_hidden_states
								_snake_case     		=	output.transformer_decoder_hidden_states

								self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE						)					,     len(config.backbone_config.depths						)						)
								self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE						)					,     len(config.backbone_config.depths						)						)
								self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE						)					,     config.decoder_layers						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_=False						):





								"""simple docstring"""






								with torch.no_grad():
									_snake_case     		=	MaskaFormerModel(config=_SCREAMING_SNAKE_CASE						)
									model.to(_SCREAMING_SNAKE_CASE						)
									model.eval()

									_snake_case     		=	model(pixel_values=_SCREAMING_SNAKE_CASE					,     pixel_mask=_SCREAMING_SNAKE_CASE						)
									_snake_case     		=	model(_SCREAMING_SNAKE_CASE					,     output_hidden_states=_SCREAMING_SNAKE_CASE						)

								self.parent.assertEqual(
								    output.transformer_decoder_last_hidden_state.shape					,     (self.batch_size, self.num_queries, self.hidden_dim)					,     )
								# let's ensure the other two hidden state exists
								self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None						)
								self.parent.assertTrue(output.encoder_last_hidden_state is not None						)

								if output_hidden_states:
									self.check_output_hidden_state(_SCREAMING_SNAKE_CASE					,     _SCREAMING_SNAKE_CASE						)




							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	MaskaFormerForUniversalSegmentation(config=_SCREAMING_SNAKE_CASE						)
								model.to(_SCREAMING_SNAKE_CASE						)
								model.eval()

								def comm_check_on_output(lowerCAmelCase_						):
									# let's still check that all the required stuff is there
									self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None						)
									self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None						)
									self.parent.assertTrue(result.encoder_last_hidden_state is not None						)
									# okay, now we need to check the logits shape
									# due to the encoder compression, masks have a //4 spatial size
									self.parent.assertEqual(
									    result.masks_queries_logits.shape					,     (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)					,     )
									# + 1 for null class
									self.parent.assertEqual(
									    result.class_queries_logits.shape					,     (self.batch_size, self.num_queries, self.num_labels + 1)						)

								with torch.no_grad():
									_snake_case     		=	model(pixel_values=_SCREAMING_SNAKE_CASE					,     pixel_mask=_SCREAMING_SNAKE_CASE						)
									_snake_case     		=	model(_SCREAMING_SNAKE_CASE						)

									comm_check_on_output(_SCREAMING_SNAKE_CASE						)

									_snake_case     		=	model(
									    pixel_values=_SCREAMING_SNAKE_CASE					,     pixel_mask=_SCREAMING_SNAKE_CASE					,     mask_labels=_SCREAMING_SNAKE_CASE					,     class_labels=_SCREAMING_SNAKE_CASE						)

								comm_check_on_output(_SCREAMING_SNAKE_CASE						)

								self.parent.assertTrue(result.loss is not None						)
								self.parent.assertEqual(result.loss.shape					,     torch.Size([1]						)						)


@require_torch
class 		__UpperCAmelCase   (      _lowerCamelCase		,     _lowerCamelCase		,     unittest.TestCase		):
							__lowercase   	= (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
							__lowercase   	= {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

							__lowercase   	= False
							__lowercase   	= False
							__lowercase   	= False
							__lowercase   	= False


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	MaskaFormerModelTester(self						)
								_snake_case     		=	ConfigTester(self					,     config_class=_SCREAMING_SNAKE_CASE					,     has_text_modality=_SCREAMING_SNAKE_CASE						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								self.config_tester.run_common_tests()


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case		,				_snake_case     		=	self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.create_and_check_maskaformer_model(_SCREAMING_SNAKE_CASE					,     **_SCREAMING_SNAKE_CASE					,     output_hidden_states=_SCREAMING_SNAKE_CASE						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_SCREAMING_SNAKE_CASE						)


							@unittest.skip(reason='Mask2Former does not use inputs_embeds'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							@unittest.skip(reason='Mask2Former does not have a get_input_embeddings method'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							@unittest.skip(reason='Mask2Former is not a generative model'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							@unittest.skip(reason='Mask2Former does not use token embeddings'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							@require_torch_multi_gpu
							@unittest.skip(
							    reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case		,				_snake_case     		=	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									_snake_case     		=	model_class(_SCREAMING_SNAKE_CASE						)
									_snake_case     		=	inspect.signature(model.forward						)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									_snake_case     		=	[*signature.parameters.keys()]

									_snake_case     		=	['pixel_values']
									self.assertListEqual(arg_names[:1]					,     _SCREAMING_SNAKE_CASE						)


							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
									_snake_case     		=	MaskaFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE						)
									self.assertIsNotNone(_SCREAMING_SNAKE_CASE						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	(self.model_tester.min_size,) * 2
								_snake_case     		=	{
								    'pixel_values': torch.randn((2, 3, *size)					,     device=_SCREAMING_SNAKE_CASE						),
								    'mask_labels': torch.randn((2, 10, *size)					,     device=_SCREAMING_SNAKE_CASE						),
								    'class_labels': torch.zeros(2					,     10					,     device=_SCREAMING_SNAKE_CASE						).long(),
								}
								_snake_case     		=	self.model_tester.get_config()

								_snake_case     		=	MaskaFormerForUniversalSegmentation(_SCREAMING_SNAKE_CASE						).to(_SCREAMING_SNAKE_CASE						)
								_snake_case     		=	model(**_SCREAMING_SNAKE_CASE						)
								self.assertTrue(outputs.loss is not None						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case		,				_snake_case     		=	self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.create_and_check_maskaformer_model(_SCREAMING_SNAKE_CASE					,     **_SCREAMING_SNAKE_CASE					,     output_hidden_states=_SCREAMING_SNAKE_CASE						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case		,				_snake_case     		=	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									_snake_case     		=	model_class(_SCREAMING_SNAKE_CASE						).to(_SCREAMING_SNAKE_CASE						)
									_snake_case     		=	model(**_SCREAMING_SNAKE_CASE					,     output_attentions=_SCREAMING_SNAKE_CASE						)
									self.assertTrue(outputs.attentions is not None						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								if not self.model_tester.is_training:
									return

								_snake_case     		=	self.all_model_classes[1]
								_snake_case		,				_snake_case		,				_snake_case		,				_snake_case		,				_snake_case     		=	self.model_tester.prepare_config_and_inputs()

								_snake_case     		=	model_class(_SCREAMING_SNAKE_CASE						)
								model.to(_SCREAMING_SNAKE_CASE						)
								model.train()

								_snake_case     		=	model(_SCREAMING_SNAKE_CASE					,     mask_labels=_SCREAMING_SNAKE_CASE					,     class_labels=_SCREAMING_SNAKE_CASE						).loss
								loss.backward()




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.all_model_classes[1]
								_snake_case		,				_snake_case		,				_snake_case		,				_snake_case		,				_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								_snake_case     		=	True
								_snake_case     		=	True

								_snake_case     		=	model_class(_SCREAMING_SNAKE_CASE						).to(_SCREAMING_SNAKE_CASE						)
								model.train()

								_snake_case     		=	model(_SCREAMING_SNAKE_CASE					,     mask_labels=_SCREAMING_SNAKE_CASE					,     class_labels=_SCREAMING_SNAKE_CASE						)

								_snake_case     		=	outputs.encoder_hidden_states[0]
								encoder_hidden_states.retain_grad()

								_snake_case     		=	outputs.pixel_decoder_hidden_states[0]
								pixel_decoder_hidden_states.retain_grad()

								_snake_case     		=	outputs.transformer_decoder_hidden_states[0]
								transformer_decoder_hidden_states.retain_grad()

								_snake_case     		=	outputs.attentions[0]
								attentions.retain_grad()

								outputs.loss.backward(retain_graph=_SCREAMING_SNAKE_CASE						)

								self.assertIsNotNone(encoder_hidden_states.grad						)
								self.assertIsNotNone(pixel_decoder_hidden_states.grad						)
								self.assertIsNotNone(transformer_decoder_hidden_states.grad						)
								self.assertIsNotNone(attentions.grad						)
lowercase					:							Tuple   =      1E-4







def        SCREAMING_SNAKE_CASE__			(     ) ->			Dict:
	_snake_case     		=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
	return image





@require_vision
@slow
class 		__UpperCAmelCase   (      unittest.TestCase		):


							@cached_property
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								return "facebook/mask2former-swin-small-coco-instance"


							@cached_property
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints						) if is_vision_available() else None


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	MaskaFormerModel.from_pretrained(self.model_checkpoints						).to(_SCREAMING_SNAKE_CASE						)
								_snake_case     		=	self.default_image_processor
								_snake_case     		=	prepare_img()
								_snake_case     		=	image_processor(_SCREAMING_SNAKE_CASE					,     return_tensors='pt'						).to(_SCREAMING_SNAKE_CASE						)
								_snake_case     		=	inputs['pixel_values'].shape
								# check size is divisible by 32
								self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0						)
								# check size
								self.assertEqual(_SCREAMING_SNAKE_CASE					,     (1, 3, 3_84, 3_84)						)

								with torch.no_grad():
									_snake_case     		=	model(**_SCREAMING_SNAKE_CASE						)

								_snake_case     		=	torch.tensor(
								    [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]						).to(_SCREAMING_SNAKE_CASE						)
								self.assertTrue(
								    torch.allclose(
								        outputs.encoder_last_hidden_state[0, 0, :3, :3]					,     _SCREAMING_SNAKE_CASE					,     atol=_SCREAMING_SNAKE_CASE						)						)

								_snake_case     		=	torch.tensor(
								    [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]						).to(_SCREAMING_SNAKE_CASE						)
								self.assertTrue(
								    torch.allclose(
								        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]					,     _SCREAMING_SNAKE_CASE					,     atol=_SCREAMING_SNAKE_CASE						)						)

								_snake_case     		=	torch.tensor(
								    [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]						).to(_SCREAMING_SNAKE_CASE						)
								self.assertTrue(
								    torch.allclose(
								        outputs.transformer_decoder_last_hidden_state[0, :3, :3]					,     _SCREAMING_SNAKE_CASE					,     atol=_SCREAMING_SNAKE_CASE						)						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints						).to(_SCREAMING_SNAKE_CASE						).eval()
								_snake_case     		=	self.default_image_processor
								_snake_case     		=	prepare_img()
								_snake_case     		=	image_processor(_SCREAMING_SNAKE_CASE					,     return_tensors='pt'						).to(_SCREAMING_SNAKE_CASE						)
								_snake_case     		=	inputs['pixel_values'].shape
								# check size is divisible by 32
								self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0						)
								# check size
								self.assertEqual(_SCREAMING_SNAKE_CASE					,     (1, 3, 3_84, 3_84)						)

								with torch.no_grad():
									_snake_case     		=	model(**_SCREAMING_SNAKE_CASE						)
								# masks_queries_logits
								_snake_case     		=	outputs.masks_queries_logits
								self.assertEqual(
								    masks_queries_logits.shape					,     (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)						)
								_snake_case     		=	[
								    [-8.7839, -9.0056, -8.8121],
								    [-7.4104, -7.0313, -6.5401],
								    [-6.6105, -6.3427, -6.4675],
								]
								_snake_case     		=	torch.tensor(_SCREAMING_SNAKE_CASE						).to(_SCREAMING_SNAKE_CASE						)
								self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]					,     _SCREAMING_SNAKE_CASE					,     atol=_SCREAMING_SNAKE_CASE						)						)
								# class_queries_logits
								_snake_case     		=	outputs.class_queries_logits
								self.assertEqual(class_queries_logits.shape					,     (1, model.config.num_queries, model.config.num_labels + 1)						)
								_snake_case     		=	torch.tensor(
								    [
								        [1.8324, -8.0835, -4.1922],
								        [0.8450, -9.0050, -3.6053],
								        [0.3045, -7.7293, -3.0275],
								    ]						).to(_SCREAMING_SNAKE_CASE						)
								self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]					,     _SCREAMING_SNAKE_CASE					,     atol=_SCREAMING_SNAKE_CASE						)						)




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints						).to(_SCREAMING_SNAKE_CASE						).eval()
								_snake_case     		=	self.default_image_processor

								_snake_case     		=	image_processor(
								    [np.zeros((3, 8_00, 13_33)						), np.zeros((3, 8_00, 13_33)						)]					,     segmentation_maps=[np.zeros((3_84, 3_84)						).astype(np.floataa						), np.zeros((3_84, 3_84)						).astype(np.floataa						)]					,     return_tensors='pt'					,     )

								_snake_case     		=	inputs['pixel_values'].to(_SCREAMING_SNAKE_CASE						)
								_snake_case     		=	[el.to(_SCREAMING_SNAKE_CASE						) for el in inputs['mask_labels']]
								_snake_case     		=	[el.to(_SCREAMING_SNAKE_CASE						) for el in inputs['class_labels']]

								with torch.no_grad():
									_snake_case     		=	model(**_SCREAMING_SNAKE_CASE						)

								self.assertTrue(outputs.loss is not None						)



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





								"""simple docstring"""






								_snake_case     		=	parent
								_snake_case     		=	batch_size
								_snake_case     		=	seq_length
								_snake_case     		=	is_training
								_snake_case     		=	use_token_type_ids
								_snake_case     		=	use_labels
								_snake_case     		=	vocab_size
								_snake_case     		=	hidden_size
								_snake_case     		=	num_hidden_layers
								_snake_case     		=	num_attention_heads
								_snake_case     		=	intermediate_size
								_snake_case     		=	hidden_act
								_snake_case     		=	hidden_dropout_prob
								_snake_case     		=	attention_probs_dropout_prob
								_snake_case     		=	max_position_embeddings
								_snake_case     		=	type_vocab_size
								_snake_case     		=	type_sequence_label_size
								_snake_case     		=	initializer_range
								_snake_case     		=	num_labels
								_snake_case     		=	num_choices
								_snake_case     		=	scope
								_snake_case     		=	self.vocab_size - 1


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	ids_tensor([self.batch_size, self.seq_length]					,     self.vocab_size						)

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

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

								_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					,     )

								_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 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModel(config=lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     head_mask=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_						)

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


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.loss.shape					,     ()						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTDoubleHeadsModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.loss.shape					,     ()						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	self.num_labels
								_snake_case     		=	OpenAIGPTForSequenceClassification(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

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




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.prepare_config_and_inputs()
								(
								    (
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				
								)     		=	config_and_inputs
								_snake_case     		=	{
								    'input_ids': input_ids,
								    'token_type_ids': token_type_ids,
								    'head_mask': head_mask,
								}

								return config, inputs_dict


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


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""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					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_=False						):





								"""simple docstring"""






								_snake_case     		=	super()._prepare_for_class(lowerCAmelCase_					,     lowerCAmelCase_					,     return_labels=lowerCAmelCase_						)

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


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModelTester(self						)
								_snake_case     		=	ConfigTester(self					,     config_class=lowerCAmelCase_					,     n_embd=37						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								self.config_tester.run_common_tests()


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_double_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCAmelCase_						)




							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






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


@require_torch
class 		__UpperCAmelCase   (      unittest.TestCase		):


							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'						)
								model.to(lowerCAmelCase_						)
								_snake_case     		=	torch.tensor([[4_81, 47_35, 5_44]]					,     dtype=torch.long					,     device=lowerCAmelCase_						)  # the president is
								_snake_case     		=	[
								    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

								_snake_case     		=	model.generate(lowerCAmelCase_					,     do_sample=lowerCAmelCase_						)
								self.assertListEqual(output_ids[0].tolist()					,     lowerCAmelCase_						)

