

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







							def __init__(			self       ,							_a       ,							_a=2       ,							_a=True       ,							_a=False       ,							_a=1_0       ,							_a=3       ,							_a=3_2 * 8       ,							_a=3_2 * 8       ,							_a=4       ,							_a=6_4       ,							)    ->    str:
												_a	:    Union[str, Any]         =		parent
												_a	:    Dict         =		batch_size
												_a	:    Union[str, Any]         =		is_training
												_a	:    int         =		use_auxiliary_loss
												_a	:    Tuple         =		num_queries
												_a	:    int         =		num_channels
												_a	:    Any         =		min_size
												_a	:    Optional[Any]         =		max_size
												_a	:    Optional[Any]         =		num_labels
												_a	:    List[str]         =		hidden_dim
												_a	:    int         =		hidden_dim


							def 				__lowercase				(			self       )    ->    List[Any]:
												_a	:    Optional[int]         =		floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]       ).to(
												    _a       )

												_a	:    str         =		torch.ones([self.batch_size, self.min_size, self.max_size]       ,							device=_a       )

												_a	:    Dict         =		(
												    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]       ,							device=_a       ) > 0.5
												).float()
												_a	:    Union[str, Any]         =		(torch.rand((self.batch_size, self.num_labels)       ,							device=_a       ) > 0.5).long()

												_a	:    Tuple         =		self.get_config()
												return config, pixel_values, pixel_mask, mask_labels, class_labels


							def 				__lowercase				(			self       )    ->    Optional[int]:
												_a	:    Union[str, Any]         =		MaskaFormerConfig(
												    hidden_size=self.hidden_dim       ,							)
												_a	:    Dict         =		self.num_queries
												_a	:    Optional[int]         =		self.num_labels

												_a	:    int         =		[1, 1, 1, 1]
												_a	:    Any         =		self.num_channels

												_a	:    Union[str, Any]         =		6_4
												_a	:    List[Any]         =		1_2_8
												_a	:    Optional[int]         =		self.hidden_dim
												_a	:    Any         =		self.hidden_dim
												_a	:    str         =		self.hidden_dim
												return config


							def 				__lowercase				(			self       )    ->    Dict:
												_a      ,					_a      ,					_a      ,					_a      ,					_a	:    Dict         =		self.prepare_config_and_inputs()
												_a	:    List[Any]         =		{'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
												return config, inputs_dict


							def 				__lowercase				(			self       ,							_a       ,							_a       )    ->    Optional[Any]:
												_a	:    Optional[int]         =		output.encoder_hidden_states
												_a	:    Tuple         =		output.pixel_decoder_hidden_states
												_a	:    Dict         =		output.transformer_decoder_hidden_states

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


							def 				__lowercase				(			self       ,							_a       ,							_a       ,							_a       ,							_a=False       )    ->    Optional[Any]:
												with torch.no_grad():
																	_a	:    int         =		MaskaFormerModel(config=_a       )
																	model.to(_a       )
																	model.eval()

																	_a	:    Union[str, Any]         =		model(pixel_values=_a       ,							pixel_mask=_a       )
																	_a	:    Any         =		model(_a       ,							output_hidden_states=_a       )

												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(_a       ,							_a       )




							def 				__lowercase				(			self       ,							_a       ,							_a       ,							_a       ,							_a       ,							_a       )    ->    Tuple:
												_a	:    int         =		MaskaFormerForUniversalSegmentation(config=_a       )
												model.to(_a       )
												model.eval()

												def comm_check_on_output(_a       ):
																	# 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():
																	_a	:    Any         =		model(pixel_values=_a       ,							pixel_mask=_a       )
																	_a	:    Optional[int]         =		model(_a       )

																	comm_check_on_output(_a       )

																	_a	:    Union[str, Any]         =		model(
																	    pixel_values=_a       ,							pixel_mask=_a       ,							mask_labels=_a       ,							class_labels=_a       )

												comm_check_on_output(_a       )

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



@require_torch
class 				UpperCAmelCase_		(			__lowercase				,       __lowercase				,       unittest.TestCase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						Optional[Any]	    =    (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
							UpperCAmelCase__       :						Dict	    =    {"feature-extraction": MaskaFormerModel} if is_torch_available() else {}

							UpperCAmelCase__       :						Tuple	    =    False
							UpperCAmelCase__       :						Dict	    =    False
							UpperCAmelCase__       :						List[Any]	    =    False
							UpperCAmelCase__       :						Optional[Any]	    =    False


							def 				__lowercase				(			self       )    ->    Union[str, Any]:
												_a	:    Dict         =		MaskaFormerModelTester(self       )
												_a	:    Optional[int]         =		ConfigTester(self       ,							config_class=_a       ,							has_text_modality=_a       )


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


							def 				__lowercase				(			self       )    ->    Tuple:
												_a      ,					_a	:    Optional[Any]         =		self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.create_and_check_maskaformer_model(_a       ,							**_a       ,							output_hidden_states=_a       )


							def 				__lowercase				(			self       )    ->    str:
												_a	:    Optional[Any]         =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_a       )


							@unittest.skip(reason='''Mask2Former does not use inputs_embeds'''       )
							def 				__lowercase				(			self       )    ->    Dict:
												pass


							@unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method'''       )
							def 				__lowercase				(			self       )    ->    Dict:
												pass


							@unittest.skip(reason='''Mask2Former is not a generative model'''       )
							def 				__lowercase				(			self       )    ->    List[str]:
												pass


							@unittest.skip(reason='''Mask2Former does not use token embeddings'''       )
							def 				__lowercase				(			self       )    ->    Dict:
												pass


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


							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''       )
							def 				__lowercase				(			self       )    ->    Union[str, Any]:
												pass


							def 				__lowercase				(			self       )    ->    int:
												_a      ,					_a	:    Dict         =		self.model_tester.prepare_config_and_inputs_for_common()

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

																	_a	:    Optional[int]         =		['''pixel_values''']
																	self.assertListEqual(arg_names[:1]       ,							_a       )


							@slow
							def 				__lowercase				(			self       )    ->    Any:
												for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
																	_a	:    Tuple         =		MaskaFormerModel.from_pretrained(_a       )
																	self.assertIsNotNone(_a       )


							def 				__lowercase				(			self       )    ->    Optional[Any]:
												_a	:    Dict         =		(self.model_tester.min_size,) * 2
												_a	:    Tuple         =		{
												    '''pixel_values''': torch.randn((2, 3, *size)       ,							device=_a       ),
												    '''mask_labels''': torch.randn((2, 1_0, *size)       ,							device=_a       ),
												    '''class_labels''': torch.zeros(2       ,							1_0       ,							device=_a       ).long(),
												}
												_a	:    Union[str, Any]         =		self.model_tester.get_config()

												_a	:    List[Any]         =		MaskaFormerForUniversalSegmentation(_a       ).to(_a       )
												_a	:    str         =		model(**_a       )
												self.assertTrue(outputs.loss is not None       )


							def 				__lowercase				(			self       )    ->    Optional[int]:
												_a      ,					_a	:    Tuple         =		self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.create_and_check_maskaformer_model(_a       ,							**_a       ,							output_hidden_states=_a       )


							def 				__lowercase				(			self       )    ->    Union[str, Any]:
												_a      ,					_a	:    Union[str, Any]         =		self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_a	:    List[str]         =		model_class(_a       ).to(_a       )
																	_a	:    Optional[int]         =		model(**_a       ,							output_attentions=_a       )
																	self.assertTrue(outputs.attentions is not None       )


							def 				__lowercase				(			self       )    ->    str:
												if not self.model_tester.is_training:
																	return

												_a	:    List[Any]         =		self.all_model_classes[1]
												_a      ,					_a      ,					_a      ,					_a      ,					_a	:    Dict         =		self.model_tester.prepare_config_and_inputs()

												_a	:    Any         =		model_class(_a       )
												model.to(_a       )
												model.train()

												_a	:    Optional[Any]         =		model(_a       ,							mask_labels=_a       ,							class_labels=_a       ).loss
												loss.backward()




							def 				__lowercase				(			self       )    ->    Optional[int]:
												_a	:    int         =		self.all_model_classes[1]
												_a      ,					_a      ,					_a      ,					_a      ,					_a	:    Optional[Any]         =		self.model_tester.prepare_config_and_inputs()
												_a	:    Tuple         =		True
												_a	:    Optional[int]         =		True

												_a	:    str         =		model_class(_a       ).to(_a       )
												model.train()

												_a	:    List[str]         =		model(_a       ,							mask_labels=_a       ,							class_labels=_a       )

												_a	:    Optional[Any]         =		outputs.encoder_hidden_states[0]
												encoder_hidden_states.retain_grad()

												_a	:    Union[str, Any]         =		outputs.pixel_decoder_hidden_states[0]
												pixel_decoder_hidden_states.retain_grad()

												_a	:    List[str]         =		outputs.transformer_decoder_hidden_states[0]
												transformer_decoder_hidden_states.retain_grad()

												_a	:    Optional[Any]         =		outputs.attentions[0]
												attentions.retain_grad()

												outputs.loss.backward(retain_graph=_a       )

												self.assertIsNotNone(encoder_hidden_states.grad       )
												self.assertIsNotNone(pixel_decoder_hidden_states.grad       )
												self.assertIsNotNone(transformer_decoder_hidden_states.grad       )
												self.assertIsNotNone(attentions.grad       )



a__				=		1E-4



def    __UpperCAmelCase (	)			->     int:

					"""simple docstring"""

					_a	:    Optional[Any]         =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
					return image







@require_vision
@slow
class 				UpperCAmelCase_		(			unittest.TestCase   ):
							"""simple docstring"""







							@cached_property
							def 				__lowercase				(			self       )    ->    str:
												return "facebook/mask2former-swin-small-coco-instance"


							@cached_property
							def 				__lowercase				(			self       )    ->    int:
												return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints       ) if is_vision_available() else None


							def 				__lowercase				(			self       )    ->    Dict:
												_a	:    Tuple         =		MaskaFormerModel.from_pretrained(self.model_checkpoints       ).to(_a       )
												_a	:    List[str]         =		self.default_image_processor
												_a	:    Tuple         =		prepare_img()
												_a	:    List[str]         =		image_processor(_a       ,							return_tensors='''pt'''       ).to(_a       )
												_a	:    Any         =		inputs['''pixel_values'''].shape
												# check size is divisible by 32
												self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0       )
												# check size
												self.assertEqual(_a       ,							(1, 3, 3_8_4, 3_8_4)       )

												with torch.no_grad():
																	_a	:    Union[str, Any]         =		model(**_a       )

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

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

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


							def 				__lowercase				(			self       )    ->    List[str]:
												_a	:    Optional[int]         =		MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints       ).to(_a       ).eval()
												_a	:    str         =		self.default_image_processor
												_a	:    List[Any]         =		prepare_img()
												_a	:    List[Any]         =		image_processor(_a       ,							return_tensors='''pt'''       ).to(_a       )
												_a	:    Union[str, Any]         =		inputs['''pixel_values'''].shape
												# check size is divisible by 32
												self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0       )
												# check size
												self.assertEqual(_a       ,							(1, 3, 3_8_4, 3_8_4)       )

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




							def 				__lowercase				(			self       )    ->    List[str]:
												_a	:    str         =		MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints       ).to(_a       ).eval()
												_a	:    Union[str, Any]         =		self.default_image_processor

												_a	:    Any         =		image_processor(
												    [np.zeros((3, 8_0_0, 1_3_3_3)       ), np.zeros((3, 8_0_0, 1_3_3_3)       )]       ,							segmentation_maps=[np.zeros((3_8_4, 3_8_4)       ).astype(np.floataa       ), np.zeros((3_8_4, 3_8_4)       ).astype(np.floataa       )]       ,							return_tensors='''pt'''       ,							)

												_a	:    Optional[int]         =		inputs['''pixel_values'''].to(_a       )
												_a	:    Any         =		[el.to(_a       ) for el in inputs['''mask_labels''']]
												_a	:    Union[str, Any]         =		[el.to(_a       ) for el in inputs['''class_labels''']]

												with torch.no_grad():
																	_a	:    List[str]         =		model(**_a       )

												self.assertTrue(outputs.loss is not None       )






from math import ceil



def    __UpperCAmelCase (	__a      :			int = 1_001	)			->     int:

					"""simple docstring"""

					_a	:    List[Any]         =		1

					for i in range(1		,int(ceil(n / 2.0	)	)	):
										_a	:    Optional[Any]         =		2 * i + 1
										_a	:    Optional[int]         =		2 * i
										_a	:    str         =		total + 4 * odd**2 - 6 * even

					return total


if __name__ == "__main__":
			import sys

			if len(sys.argv) == 1:
						print(solution())
			else:
						try:
									a__				=		int(sys.argv[1])
									print(solution(n))
						except ValueError:
									print('''Invalid entry - please enter a number''')



