

"""simple docstring"""




import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, 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 MaskFormerForInstanceSegmentation, MaskFormerModel

						if is_vision_available():
												from transformers import MaskFormerImageProcessor

if is_vision_available():
						from PIL import Image





class  lowerCamelCase    :

			def __init__(       self					:    Dict     ,					__UpperCAmelCase					:    Dict     ,					__UpperCAmelCase					:    str=2     ,					__UpperCAmelCase					:    Any=True     ,					__UpperCAmelCase					:    Dict=False     ,					__UpperCAmelCase					:    str=1_0     ,					__UpperCAmelCase					:    Optional[Any]=3     ,					__UpperCAmelCase					:    str=3_2 * 4     ,					__UpperCAmelCase					:    Any=3_2 * 6     ,					__UpperCAmelCase					:    Optional[Any]=4     ,					__UpperCAmelCase					:    List[Any]=3_2     ,					) ->     Any:
						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__										=   mask_feature_size

			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Optional[int]:
						SCREAMING_SNAKE_CASE__										=   floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]							).to(
						    __UpperCAmelCase							)

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

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

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

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]							) ->     Optional[int]:
						return MaskFormerConfig.from_backbone_and_decoder_configs(
						    backbone_config=SwinConfig(
						        depths=[1, 1, 1, 1]     ,					)     ,					decoder_config=DetrConfig(
						        decoder_ffn_dim=1_2_8     ,					num_queries=self.num_queries     ,					decoder_attention_heads=2     ,					d_model=self.mask_feature_size     ,					)     ,					mask_feature_size=self.mask_feature_size     ,					fpn_feature_size=self.mask_feature_size     ,					num_channels=self.num_channels     ,					num_labels=self.num_labels     ,					)

			def        SCREAMING_SNAKE_CASE					(       self					:    str							) ->     Dict:
						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        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]     ,					__UpperCAmelCase					:    Union[str, Any]     ,					__UpperCAmelCase					:    str							) ->     Optional[Any]:
						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(__UpperCAmelCase							)     ,					len(config.backbone_config.depths							)							)
						self.parent.assertTrue(len(__UpperCAmelCase							)     ,					len(config.backbone_config.depths							)							)
						self.parent.assertTrue(len(__UpperCAmelCase							)     ,					config.decoder_config.decoder_layers							)

			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]     ,					__UpperCAmelCase					:    List[str]     ,					__UpperCAmelCase					:    Tuple     ,					__UpperCAmelCase					:    Tuple     ,					__UpperCAmelCase					:    Optional[int]=False							) ->     Any:
						with torch.no_grad():
									SCREAMING_SNAKE_CASE__										=   MaskFormerModel(config=__UpperCAmelCase							)
									model.to(__UpperCAmelCase							)
									model.eval()

									SCREAMING_SNAKE_CASE__										=   model(pixel_values=__UpperCAmelCase     ,					pixel_mask=__UpperCAmelCase							)
									SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase     ,					output_hidden_states=__UpperCAmelCase							)
						# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
						# encoder and pixel decoder
						self.parent.assertEqual(
						    output.transformer_decoder_last_hidden_state.shape     ,					(self.batch_size, self.num_queries, self.mask_feature_size)     ,					)
						# 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(__UpperCAmelCase     ,					__UpperCAmelCase							)





			def        SCREAMING_SNAKE_CASE					(       self					:    int     ,					__UpperCAmelCase					:    Dict     ,					__UpperCAmelCase					:    Tuple     ,					__UpperCAmelCase					:    Optional[Any]     ,					__UpperCAmelCase					:    str     ,					__UpperCAmelCase					:    Optional[Any]							) ->     Dict:
						SCREAMING_SNAKE_CASE__										=   MaskFormerForInstanceSegmentation(config=__UpperCAmelCase							)
						model.to(__UpperCAmelCase							)
						model.eval()

						def comm_check_on_output(__UpperCAmelCase					:    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=__UpperCAmelCase     ,					pixel_mask=__UpperCAmelCase							)
									SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)

									comm_check_on_output(__UpperCAmelCase							)

									SCREAMING_SNAKE_CASE__										=   model(
									    pixel_values=__UpperCAmelCase     ,					pixel_mask=__UpperCAmelCase     ,					mask_labels=__UpperCAmelCase     ,					class_labels=__UpperCAmelCase							)

						comm_check_on_output(__UpperCAmelCase							)

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





@require_torch
class  lowerCamelCase    (A__      ,A__      ,unittest.TestCase      ):
			lowerCamelCase__ :		Tuple       		=				(MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
			lowerCamelCase__ :		str       		=				(
			    {'feature-extraction': MaskFormerModel, 'image-segmentation': MaskFormerForInstanceSegmentation}
			    if is_torch_available()
			    else {}
			)

			lowerCamelCase__ :		Optional[Any]       		=				False
			lowerCamelCase__ :		List[Any]       		=				False
			lowerCamelCase__ :		int       		=				False
			lowerCamelCase__ :		List[Any]       		=				False

			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   MaskFormerModelTester(self							)
						SCREAMING_SNAKE_CASE__										=   ConfigTester(self     ,					config_class=__UpperCAmelCase     ,					has_text_modality=__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    str							) ->     Optional[int]:
						self.config_tester.run_common_tests()

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     int:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.create_and_check_maskformer_model(__UpperCAmelCase     ,					**__UpperCAmelCase     ,					output_hidden_states=__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Dict:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__UpperCAmelCase							)

			@unittest.skip(reason="""MaskFormer does not use inputs_embeds"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Optional[int]:
						pass

			@unittest.skip(reason="""MaskFormer does not have a get_input_embeddings method"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]							) ->     Union[str, Any]:
						pass

			@unittest.skip(reason="""MaskFormer is not a generative model"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[int]							) ->     List[str]:
						pass

			@unittest.skip(reason="""MaskFormer does not use token embeddings"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Optional[int]:
						pass

			@require_torch_multi_gpu
			@unittest.skip(
			    reason="""MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]							) ->     List[str]:
						pass

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

			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     Optional[Any]:
						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(__UpperCAmelCase							)
									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]     ,					__UpperCAmelCase							)

			@slow
			def        SCREAMING_SNAKE_CASE					(       self					:    str							) ->     Any:
						for model_name in ["facebook/maskformer-swin-small-coco"]:
									SCREAMING_SNAKE_CASE__										=   MaskFormerModel.from_pretrained(__UpperCAmelCase							)
									self.assertIsNotNone(__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     int:
						SCREAMING_SNAKE_CASE__										=   (self.model_tester.min_size,) * 2
						SCREAMING_SNAKE_CASE__										=   {
						    """pixel_values""": torch.randn((2, 3, *size)     ,					device=__UpperCAmelCase							),
						    """mask_labels""": torch.randn((2, 1_0, *size)     ,					device=__UpperCAmelCase							),
						    """class_labels""": torch.zeros(2     ,					1_0     ,					device=__UpperCAmelCase							).long(),
						}

						SCREAMING_SNAKE_CASE__										=   MaskFormerForInstanceSegmentation(MaskFormerConfig()							).to(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   model(**__UpperCAmelCase							)
						self.assertTrue(outputs.loss is not None							)

			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     int:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.create_and_check_maskformer_model(__UpperCAmelCase     ,					**__UpperCAmelCase     ,					output_hidden_states=__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Optional[Any]:
						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(__UpperCAmelCase							).to(__UpperCAmelCase							)
									SCREAMING_SNAKE_CASE__										=   model(**__UpperCAmelCase     ,					output_attentions=__UpperCAmelCase							)
									self.assertTrue(outputs.attentions is not None							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Optional[Any]:
						if not self.model_tester.is_training:
									return
						# only MaskFormerForInstanceSegmentation has the loss
						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(__UpperCAmelCase							)
						model.to(__UpperCAmelCase							)
						model.train()

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





			def        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]							) ->     str:
						# only MaskFormerForInstanceSegmentation has the loss
						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(__UpperCAmelCase							)
						model.to(__UpperCAmelCase							)
						model.train()

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

						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()
						# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
						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=__UpperCAmelCase							)

						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_				:      Optional[Any]           =			1E-4

def 						A							(  ):




			'''simple docstring'''


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





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

			@cached_property
			def        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]							) ->     str:
						return (
						    MaskFormerImageProcessor.from_pretrained("""facebook/maskformer-swin-small-coco"""							)
						    if is_vision_available()
						    else None
						)

			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   MaskFormerModel.from_pretrained("""facebook/maskformer-swin-small-coco"""							).to(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   self.default_image_processor
						SCREAMING_SNAKE_CASE__										=   prepare_img()
						SCREAMING_SNAKE_CASE__										=   image_processor(__UpperCAmelCase     ,					return_tensors="""pt"""							).to(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   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(__UpperCAmelCase     ,					(1, 3, 8_0_0, 1_0_8_8)							)

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

						SCREAMING_SNAKE_CASE__										=   torch.tensor(
						    [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]							).to(__UpperCAmelCase							)
						self.assertTrue(
						    torch.allclose(
						        outputs.encoder_last_hidden_state[0, 0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)

						SCREAMING_SNAKE_CASE__										=   torch.tensor(
						    [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]							).to(__UpperCAmelCase							)
						self.assertTrue(
						    torch.allclose(
						        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)

						SCREAMING_SNAKE_CASE__										=   torch.tensor(
						    [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]							).to(__UpperCAmelCase							)
						self.assertTrue(
						    torch.allclose(
						        outputs.transformer_decoder_last_hidden_state[0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   (
						    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""							)
						    .to(__UpperCAmelCase							)
						    .eval()
						)
						SCREAMING_SNAKE_CASE__										=   self.default_image_processor
						SCREAMING_SNAKE_CASE__										=   prepare_img()
						SCREAMING_SNAKE_CASE__										=   image_processor(__UpperCAmelCase     ,					return_tensors="""pt"""							).to(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   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(__UpperCAmelCase     ,					(1, 3, 8_0_0, 1_0_8_8)							)

						with torch.no_grad():
									SCREAMING_SNAKE_CASE__										=   model(**__UpperCAmelCase							)
						# masks_queries_logits
						SCREAMING_SNAKE_CASE__										=   outputs.masks_queries_logits
						self.assertEqual(
						    masks_queries_logits.shape     ,					(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)     ,					)
						SCREAMING_SNAKE_CASE__										=   [
						    [-1.3_737_124, -1.7_724_937, -1.9_364_233],
						    [-1.5_977_281, -1.9_867_939, -2.1_523_695],
						    [-1.5_795_398, -1.9_269_832, -2.093_942],
						]
						SCREAMING_SNAKE_CASE__										=   torch.tensor(__UpperCAmelCase							).to(__UpperCAmelCase							)
						self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)
						# class_queries_logits
						SCREAMING_SNAKE_CASE__										=   outputs.class_queries_logits
						self.assertEqual(
						    class_queries_logits.shape     ,					(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)							)
						SCREAMING_SNAKE_CASE__										=   torch.tensor(
						    [
						        [1.6512e00, -5.2572e00, -3.3519e00],
						        [3.6169e-02, -5.9025e00, -2.9313e00],
						        [1.0766e-04, -7.7630e00, -5.1263e00],
						    ]							).to(__UpperCAmelCase							)
						self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Dict:
						SCREAMING_SNAKE_CASE__										=   (
						    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-resnet101-coco-stuff"""							)
						    .to(__UpperCAmelCase							)
						    .eval()
						)
						SCREAMING_SNAKE_CASE__										=   self.default_image_processor
						SCREAMING_SNAKE_CASE__										=   prepare_img()
						SCREAMING_SNAKE_CASE__										=   image_processor(__UpperCAmelCase     ,					return_tensors="""pt"""							).to(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   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(__UpperCAmelCase     ,					(1, 3, 8_0_0, 1_0_8_8)							)

						with torch.no_grad():
									SCREAMING_SNAKE_CASE__										=   model(**__UpperCAmelCase							)
						# masks_queries_logits
						SCREAMING_SNAKE_CASE__										=   outputs.masks_queries_logits
						self.assertEqual(
						    masks_queries_logits.shape     ,					(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)     ,					)
						SCREAMING_SNAKE_CASE__										=   [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
						SCREAMING_SNAKE_CASE__										=   torch.tensor(__UpperCAmelCase							).to(__UpperCAmelCase							)
						self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)
						# class_queries_logits
						SCREAMING_SNAKE_CASE__										=   outputs.class_queries_logits
						self.assertEqual(
						    class_queries_logits.shape     ,					(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)							)
						SCREAMING_SNAKE_CASE__										=   torch.tensor(
						    [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]							).to(__UpperCAmelCase							)
						self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,					__UpperCAmelCase     ,					atol=__UpperCAmelCase							)							)





			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   (
						    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""							)
						    .to(__UpperCAmelCase							)
						    .eval()
						)
						SCREAMING_SNAKE_CASE__										=   self.default_image_processor

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

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

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

						self.assertTrue(outputs.loss is not None							)





"""simple docstring"""




from typing import List

from .keymap import KEYMAP, get_character

def 						A							(  snake_case__     ):




			'''simple docstring'''


			def decorator(snake_case__     ):
						SCREAMING_SNAKE_CASE__										=   getattr(snake_case__		,					"""handle_key"""		,					[]     )
						handle += [key]
						setattr(snake_case__		,					"""handle_key"""		,					snake_case__     )
						return func

			return decorator

def 						A							(  *snake_case__     ):




			'''simple docstring'''


			def decorator(snake_case__     ):
						SCREAMING_SNAKE_CASE__										=   getattr(snake_case__		,					"""handle_key"""		,					[]     )
						handle += keys
						setattr(snake_case__		,					"""handle_key"""		,					snake_case__     )
						return func

			return decorator





class  lowerCamelCase    (A__      ):

			def __new__(       cls					:    Dict     ,					__UpperCAmelCase					:    Tuple     ,					__UpperCAmelCase					:    Any     ,					__UpperCAmelCase					:    Optional[Any]							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   super().__new__(cls     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase							)
						if not hasattr(__UpperCAmelCase     ,					"""key_handler"""							):
									setattr(__UpperCAmelCase     ,					"""key_handler"""     ,					{}							)
						setattr(__UpperCAmelCase     ,					"""handle_input"""     ,					KeyHandler.handle_input							)

						for value in attrs.values():
									SCREAMING_SNAKE_CASE__										=   getattr(__UpperCAmelCase     ,					"""handle_key"""     ,					[]							)
									for key in handled_keys:
												SCREAMING_SNAKE_CASE__										=   value
						return new_cls





			@staticmethod
			def        SCREAMING_SNAKE_CASE					(       cls					:    Tuple							) ->     Dict:
						SCREAMING_SNAKE_CASE__										=   get_character()
						if char != KEYMAP["undefined"]:
									SCREAMING_SNAKE_CASE__										=   ord(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   cls.key_handler.get(__UpperCAmelCase							)
						if handler:
									SCREAMING_SNAKE_CASE__										=   char
									return handler(cls							)
						else:
									return None

def 						A							(  cls     ):




			'''simple docstring'''


			return KeyHandler(cls.__name__		,					cls.__bases__		,					cls.__dict__.copy()     )


