





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     :Union[str, Any]				,					__A     :List[Any]				,					__A     :List[Any]=2				,					__A     :Tuple=True				,					__A     :Any=False				,					__A     :Dict=10				,					__A     :Optional[int]=3				,					__A     :Union[str, Any]=32 * 8				,					__A     :Optional[Any]=32 * 8				,					__A     :List[str]=4				,					__A     :Dict=64				,					) -> str:



									"""simple docstring"""



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


							def   _snake_case	(				self     :List[Any]		) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]		).to(
									    _A		)

									SCREAMING_SNAKE_CASE__								=   torch.ones([self.batch_size, self.min_size, self.max_size]				,					device=_A		)

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

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


							def   _snake_case	(				self     :int		) -> Optional[Any]:



									"""simple docstring"""



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

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

									SCREAMING_SNAKE_CASE__								=   64
									SCREAMING_SNAKE_CASE__								=   128
									SCREAMING_SNAKE_CASE__								=   self.hidden_dim
									SCREAMING_SNAKE_CASE__								=   self.hidden_dim
									SCREAMING_SNAKE_CASE__								=   self.hidden_dim
									return config


							def   _snake_case	(				self     :List[str]		) -> Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE__								=   {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
									return config, inputs_dict


							def   _snake_case	(				self     :List[str]				,					__A     :Optional[int]				,					__A     :Union[str, Any]		) -> Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   output.encoder_hidden_states
									SCREAMING_SNAKE_CASE__								=   output.pixel_decoder_hidden_states
									SCREAMING_SNAKE_CASE__								=   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   _snake_case	(				self     :Union[str, Any]				,					__A     :List[Any]				,					__A     :Dict				,					__A     :int				,					__A     :List[Any]=False		) -> int:



									"""simple docstring"""



									with torch.no_grad():
											SCREAMING_SNAKE_CASE__								=   MaskaFormerModel(config=_A		)
											model.to(_A		)
											model.eval()

											SCREAMING_SNAKE_CASE__								=   model(pixel_values=_A				,					pixel_mask=_A		)
											SCREAMING_SNAKE_CASE__								=   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   _snake_case	(				self     :Union[str, Any]				,					__A     :Optional[Any]				,					__A     :Any				,					__A     :Any				,					__A     :Any				,					__A     :Tuple		) -> Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   MaskaFormerForUniversalSegmentation(config=_A		)
									model.to(_A		)
									model.eval()

									def comm_check_on_output(__A     :List[Any]		):
											# 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():
											SCREAMING_SNAKE_CASE__								=   model(pixel_values=_A				,					pixel_mask=_A		)
											SCREAMING_SNAKE_CASE__								=   model(_A		)

											comm_check_on_output(_A		)

											SCREAMING_SNAKE_CASE__								=   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     ):
							lowerCamelCase_							     =       (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
							lowerCamelCase_							     =       {"feature-extraction": MaskaFormerModel} if is_torch_available() else {}

							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False


							def   _snake_case	(				self     :Union[str, Any]		) -> Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   MaskaFormerModelTester(self		)
									SCREAMING_SNAKE_CASE__								=   ConfigTester(self				,					config_class=_A				,					has_text_modality=_A		)


							def   _snake_case	(				self     :Optional[Any]		) -> str:



									"""simple docstring"""



									self.config_tester.run_common_tests()


							def   _snake_case	(				self     :List[str]		) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.create_and_check_maskaformer_model(_A				,					**_A				,					output_hidden_states=_A		)


							def   _snake_case	(				self     :Tuple		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   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   _snake_case	(				self     :Dict		) -> List[Any]:



									"""simple docstring"""



									pass


							@unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""		)
							def   _snake_case	(				self     :str		) -> int:



									"""simple docstring"""



									pass


							@unittest.skip(reason="""Mask2Former is not a generative model"""		)
							def   _snake_case	(				self     :Union[str, Any]		) -> str:



									"""simple docstring"""



									pass


							@unittest.skip(reason="""Mask2Former does not use token embeddings"""		)
							def   _snake_case	(				self     :List[str]		) -> Any:



									"""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   _snake_case	(				self     :Tuple		) -> int:



									"""simple docstring"""



									pass


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



									"""simple docstring"""



									pass


							def   _snake_case	(				self     :Optional[int]		) -> List[str]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()

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

											SCREAMING_SNAKE_CASE__								=   ["""pixel_values"""]
											self.assertListEqual(arg_names[:1]				,					_A		)


							@slow
							def   _snake_case	(				self     :int		) -> List[str]:



									"""simple docstring"""



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


							def   _snake_case	(				self     :Union[str, Any]		) -> List[Any]:



									"""simple docstring"""



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

									SCREAMING_SNAKE_CASE__								=   MaskaFormerForUniversalSegmentation(_A		).to(_A		)
									SCREAMING_SNAKE_CASE__								=   model(**_A		)
									self.assertTrue(outputs.loss is not None		)


							def   _snake_case	(				self     :Tuple		) -> Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.create_and_check_maskaformer_model(_A				,					**_A				,					output_hidden_states=_A		)


							def   _snake_case	(				self     :List[str]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()

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


							def   _snake_case	(				self     :Optional[Any]		) -> Dict:



									"""simple docstring"""



									if not self.model_tester.is_training:
											return

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

									SCREAMING_SNAKE_CASE__								=   model_class(_A		)
									model.to(_A		)
									model.train()

									SCREAMING_SNAKE_CASE__								=   model(_A				,					mask_labels=_A				,					class_labels=_A		).loss
									loss.backward()


							def   _snake_case	(				self     :Tuple		) -> List[str]:



									"""simple docstring"""



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

									SCREAMING_SNAKE_CASE__								=   model_class(_A		).to(_A		)
									model.train()

									SCREAMING_SNAKE_CASE__								=   model(_A				,					mask_labels=_A				,					class_labels=_A		)

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

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

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

									SCREAMING_SNAKE_CASE__								=   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		)



_lowerCamelCase 					=      1e-4






def 					SCREAMING_SNAKE_CASE__				(							):
		SCREAMING_SNAKE_CASE__								=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
		return image




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


							@cached_property
							def   _snake_case	(				self     :Any		) -> Any:



									"""simple docstring"""



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


							@cached_property
							def   _snake_case	(				self     :Union[str, Any]		) -> Any:



									"""simple docstring"""



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


							def   _snake_case	(				self     :Optional[Any]		) -> List[str]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   MaskaFormerModel.from_pretrained(self.model_checkpoints		).to(_A		)
									SCREAMING_SNAKE_CASE__								=   self.default_image_processor
									SCREAMING_SNAKE_CASE__								=   prepare_img()
									SCREAMING_SNAKE_CASE__								=   image_processor(_A				,					return_tensors="""pt"""		).to(_A		)
									SCREAMING_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(_A				,					(1, 3, 384, 384)		)

									with torch.no_grad():
											SCREAMING_SNAKE_CASE__								=   model(**_A		)

									SCREAMING_SNAKE_CASE__								=   torch.tensor(
									    [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]]		).to(_A		)
									self.assertTrue(
									    torch.allclose(
									        outputs.encoder_last_hidden_state[0, 0, :3, :3]				,					_A				,					atol=_A		)		)

									SCREAMING_SNAKE_CASE__								=   torch.tensor(
									    [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]]		).to(_A		)
									self.assertTrue(
									    torch.allclose(
									        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]				,					_A				,					atol=_A		)		)

									SCREAMING_SNAKE_CASE__								=   torch.tensor(
									    [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]]		).to(_A		)
									self.assertTrue(
									    torch.allclose(
									        outputs.transformer_decoder_last_hidden_state[0, :3, :3]				,					_A				,					atol=_A		)		)


							def   _snake_case	(				self     :List[Any]		) -> int:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints		).to(_A		).eval()
									SCREAMING_SNAKE_CASE__								=   self.default_image_processor
									SCREAMING_SNAKE_CASE__								=   prepare_img()
									SCREAMING_SNAKE_CASE__								=   image_processor(_A				,					return_tensors="""pt"""		).to(_A		)
									SCREAMING_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(_A				,					(1, 3, 384, 384)		)

									with torch.no_grad():
											SCREAMING_SNAKE_CASE__								=   model(**_A		)
									# masks_queries_logits
									SCREAMING_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)		)
									SCREAMING_SNAKE_CASE__								=   [
									    [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1],
									    [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1],
									    [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5],
									]
									SCREAMING_SNAKE_CASE__								=   torch.tensor(_A		).to(_A		)
									self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]				,					_A				,					atol=_A		)		)
									# class_queries_logits
									SCREAMING_SNAKE_CASE__								=   outputs.class_queries_logits
									self.assertEqual(class_queries_logits.shape				,					(1, model.config.num_queries, model.config.num_labels + 1)		)
									SCREAMING_SNAKE_CASE__								=   torch.tensor(
									    [
									        [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2],
									        [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3],
									        [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5],
									    ]		).to(_A		)
									self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]				,					_A				,					atol=_A		)		)


							def   _snake_case	(				self     :str		) -> int:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints		).to(_A		).eval()
									SCREAMING_SNAKE_CASE__								=   self.default_image_processor

									SCREAMING_SNAKE_CASE__								=   image_processor(
									    [np.zeros((3, 800, 1333)		), np.zeros((3, 800, 1333)		)]				,					segmentation_maps=[np.zeros((384, 384)		).astype(np.floataa		), np.zeros((384, 384)		).astype(np.floataa		)]				,					return_tensors="""pt"""				,					)

									SCREAMING_SNAKE_CASE__								=   inputs["""pixel_values"""].to(_A		)
									SCREAMING_SNAKE_CASE__								=   [el.to(_A		) for el in inputs["""mask_labels"""]]
									SCREAMING_SNAKE_CASE__								=   [el.to(_A		) for el in inputs["""class_labels"""]]

									with torch.no_grad():
											SCREAMING_SNAKE_CASE__								=   model(**_A		)

									self.assertTrue(outputs.loss is not None		)
import inspect
import warnings
from typing import Any, Dict, Optional, Union

from packaging import version
def 					_snake_case	(  *__snake_case  ,     __snake_case = None  ,     __snake_case=True  ,     __snake_case=2						):
					from .. import __version__

					_UpperCamelCase			     =     take_from
					_UpperCamelCase			     =     ()
					if not isinstance(args[0]  ,     __snake_case						):
										_UpperCamelCase			     =     (args,)

					for attribute, version_name, message in args:
										if version.parse(version.parse(__snake_case						).base_version						) >= version.parse(__snake_case						):
															raise ValueError(
															    f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'"""
															    f""" version {__version__} is >= {version_name}"""						)

										_UpperCamelCase			     =     None
										if isinstance(__snake_case  ,     __snake_case						) and attribute in deprecated_kwargs:
															values += (deprecated_kwargs.pop(__snake_case						),)
															_UpperCamelCase			     =     f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}."""
										elif hasattr(__snake_case  ,     __snake_case						):
															values += (getattr(__snake_case  ,     __snake_case						),)
															_UpperCamelCase			     =     f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}."""
										elif deprecated_kwargs is None:
															_UpperCamelCase			     =     f"""`{attribute}` is deprecated and will be removed in version {version_name}."""

										if warning is not None:
															_UpperCamelCase			     =     warning + ''' ''' if standard_warn else ''''''
															warnings.warn(warning + message  ,     __snake_case  ,     stacklevel=__snake_case						)

					if isinstance(__snake_case  ,     __snake_case						) and len(__snake_case						) > 0:
										_UpperCamelCase			     =     inspect.getouterframes(inspect.currentframe()						)[1]
										_UpperCamelCase			     =     call_frame.filename
										_UpperCamelCase			     =     call_frame.lineno
										_UpperCamelCase			     =     call_frame.function
										_UpperCamelCase     ,    _UpperCamelCase			     =     next(iter(deprecated_kwargs.items()						)						)
										raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`"""						)

					if len(__snake_case						) == 0:
										return
					elif len(__snake_case						) == 1:
										return values[0]
					return values
