






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 			SCREAMING_SNAKE_CASE      :
     '''simple docstring'''


     def __init__(					self							:						Optional[int]       ,			UpperCAmelCase_							:						int       ,			UpperCAmelCase_							:						int=2       ,			UpperCAmelCase_							:						Optional[Any]=True       ,			UpperCAmelCase_							:						Any=False       ,			UpperCAmelCase_							:						Dict=10       ,			UpperCAmelCase_							:						Any=3       ,			UpperCAmelCase_							:						int=32 * 4       ,			UpperCAmelCase_							:						str=32 * 6       ,			UpperCAmelCase_							:						Optional[Any]=4       ,			UpperCAmelCase_							:						Tuple=32       ,			):
       SCREAMING_SNAKE_CASE							:   str						    =     parent
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     batch_size
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     is_training
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     use_auxiliary_loss
       SCREAMING_SNAKE_CASE							:   Tuple						    =     num_queries
       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     num_channels
       SCREAMING_SNAKE_CASE							:   Any						    =     min_size
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     max_size
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     num_labels
       SCREAMING_SNAKE_CASE							:   Tuple						    =     mask_feature_size


     def 					_A							(					self							:						Dict   ):
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]   ).to(
           UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   Tuple						    =     torch.ones([self.batch_size, self.min_size, self.max_size]       ,			device=UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   Tuple						    =     (
           torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]       ,			device=UpperCAmelCase_   ) > 0.5
       ).float()
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     (torch.rand((self.batch_size, self.num_labels)       ,			device=UpperCAmelCase_   ) > 0.5).long()

       SCREAMING_SNAKE_CASE							:   List[str]						    =     self.get_config()
       return config, pixel_values, pixel_mask, mask_labels, class_labels


     def 					_A							(					self							:						Any   ):
       return MaskFormerConfig.from_backbone_and_decoder_configs(
           backbone_config=SwinConfig(
               depths=[1, 1, 1, 1]       ,			)       ,			decoder_config=DetrConfig(
               decoder_ffn_dim=128       ,			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 					_A							(					self							:						List[str]   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   List[str]						    =     self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE							:   Dict						    =     {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
       return config, inputs_dict


     def 					_A							(					self							:						Tuple       ,			UpperCAmelCase_							:						int       ,			UpperCAmelCase_							:						Optional[Any]   ):
       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     output.encoder_hidden_states
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     output.pixel_decoder_hidden_states
       SCREAMING_SNAKE_CASE							:   str						    =     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 					_A							(					self							:						List[Any]       ,			UpperCAmelCase_							:						Dict       ,			UpperCAmelCase_							:						List[Any]       ,			UpperCAmelCase_							:						Union[str, Any]       ,			UpperCAmelCase_							:						List[str]=False   ):
       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   Optional[int]						    =     MaskFormerModel(config=UpperCAmelCase_   )
         model.to(UpperCAmelCase_   )
         model.eval()

         SCREAMING_SNAKE_CASE							:   List[str]						    =     model(pixel_values=UpperCAmelCase_       ,			pixel_mask=UpperCAmelCase_   )
         SCREAMING_SNAKE_CASE							:   List[Any]						    =     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 					_A							(					self							:						Any       ,			UpperCAmelCase_							:						Union[str, Any]       ,			UpperCAmelCase_							:						List[Any]       ,			UpperCAmelCase_							:						Union[str, Any]       ,			UpperCAmelCase_							:						List[Any]       ,			UpperCAmelCase_							:						str   ):
       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     MaskFormerForInstanceSegmentation(config=UpperCAmelCase_   )
       model.to(UpperCAmelCase_   )
       model.eval()

       def comm_check_on_output(UpperCAmelCase_							:						int   ):
         # 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							:   Dict						    =     model(pixel_values=UpperCAmelCase_       ,			pixel_mask=UpperCAmelCase_   )
         SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     model(UpperCAmelCase_   )

         comm_check_on_output(UpperCAmelCase_   )

         SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     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 			SCREAMING_SNAKE_CASE      (      lowerCAmelCase   ,		lowerCAmelCase   ,		unittest.TestCase       ):
     '''simple docstring'''


     UpperCamelCase_				:		Union[str, Any]								=						(MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
     UpperCamelCase_				:		List[str]								=						(
         {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
         if is_torch_available()
         else {}
     )

     UpperCamelCase_				:		int								=						False
     UpperCamelCase_				:		Union[str, Any]								=						False
     UpperCamelCase_				:		int								=						False
     UpperCamelCase_				:		Optional[Any]								=						False


     def 					_A							(					self							:						Dict   ):
       SCREAMING_SNAKE_CASE							:   Any						    =     MaskFormerModelTester(self   )
       SCREAMING_SNAKE_CASE							:   Tuple						    =     ConfigTester(self       ,			config_class=UpperCAmelCase_       ,			has_text_modality=UpperCAmelCase_   )


     def 					_A							(					self							:						List[str]   ):
       self.config_tester.run_common_tests()


     def 					_A							(					self							:						Dict   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   Optional[int]						    =     self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(UpperCAmelCase_       ,			**UpperCAmelCase_       ,			output_hidden_states=UpperCAmelCase_   )


     def 					_A							(					self							:						Union[str, Any]   ):
       SCREAMING_SNAKE_CASE							:   List[str]						    =     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 					_A							(					self							:						List[str]   ):
       pass


     @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method"   )
     def 					_A							(					self							:						Optional[int]   ):
       pass


     @unittest.skip(reason="MaskFormer is not a generative model"   )
     def 					_A							(					self							:						List[str]   ):
       pass


     @unittest.skip(reason="MaskFormer does not use token embeddings"   )
     def 					_A							(					self							:						Union[str, Any]   ):
       pass


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


     @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."   )
     def 					_A							(					self							:						Tuple   ):
       pass


     def 					_A							(					self							:						Any   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   Any						    =     self.model_tester.prepare_config_and_inputs_for_common()

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

         SCREAMING_SNAKE_CASE							:   Optional[int]						    =     ["pixel_values"]
         self.assertListEqual(arg_names[:1]       ,			UpperCAmelCase_   )


     @slow
     def 					_A							(					self							:						List[Any]   ):
       for model_name in ["facebook/maskformer-swin-small-coco"]:
         SCREAMING_SNAKE_CASE							:   Any						    =     MaskFormerModel.from_pretrained(UpperCAmelCase_   )
         self.assertIsNotNone(UpperCAmelCase_   )


     def 					_A							(					self							:						Tuple   ):
       SCREAMING_SNAKE_CASE							:   List[str]						    =     (self.model_tester.min_size,) * 2
       SCREAMING_SNAKE_CASE							:   Any						    =     {
           "pixel_values": torch.randn((2, 3, *size)       ,			device=UpperCAmelCase_   ),
           "mask_labels": torch.randn((2, 10, *size)       ,			device=UpperCAmelCase_   ),
           "class_labels": torch.zeros(2       ,			10       ,			device=UpperCAmelCase_   ).long(),
       }

       SCREAMING_SNAKE_CASE							:   Tuple						    =     MaskFormerForInstanceSegmentation(MaskFormerConfig()   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   int						    =     model(**UpperCAmelCase_   )
       self.assertTrue(outputs.loss is not None   )


     def 					_A							(					self							:						List[Any]   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   Optional[int]						    =     self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(UpperCAmelCase_       ,			**UpperCAmelCase_       ,			output_hidden_states=UpperCAmelCase_   )


     def 					_A							(					self							:						List[str]   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   int						    =     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         SCREAMING_SNAKE_CASE							:   List[Any]						    =     model_class(UpperCAmelCase_   ).to(UpperCAmelCase_   )
         SCREAMING_SNAKE_CASE							:   Any						    =     model(**UpperCAmelCase_       ,			output_attentions=UpperCAmelCase_   )
         self.assertTrue(outputs.attentions is not None   )


     def 					_A							(					self							:						Tuple   ):
       if not self.model_tester.is_training:
         return
       # only MaskFormerForInstanceSegmentation has the loss
       SCREAMING_SNAKE_CASE							:   str						    =     self.all_model_classes[1]
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   int						    =     self.model_tester.prepare_config_and_inputs()

       SCREAMING_SNAKE_CASE							:   Dict						    =     model_class(UpperCAmelCase_   )
       model.to(UpperCAmelCase_   )
       model.train()

       SCREAMING_SNAKE_CASE							:   Dict						    =     model(UpperCAmelCase_       ,			mask_labels=UpperCAmelCase_       ,			class_labels=UpperCAmelCase_   ).loss
       loss.backward()






     def 					_A							(					self							:						Optional[Any]   ):
       # only MaskFormerForInstanceSegmentation has the loss
       SCREAMING_SNAKE_CASE							:   str						    =     self.all_model_classes[1]
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   int						    =     self.model_tester.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     True
       SCREAMING_SNAKE_CASE							:   Dict						    =     True

       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     model_class(UpperCAmelCase_   )
       model.to(UpperCAmelCase_   )
       model.train()

       SCREAMING_SNAKE_CASE							:   Tuple						    =     model(UpperCAmelCase_       ,			mask_labels=UpperCAmelCase_       ,			class_labels=UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   str						    =     outputs.encoder_hidden_states[0]
       encoder_hidden_states.retain_grad()

       SCREAMING_SNAKE_CASE							:   str						    =     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							:   List[Any]						    =     outputs.transformer_decoder_hidden_states[0]
       transformer_decoder_hidden_states.retain_grad()

       SCREAMING_SNAKE_CASE							:   List[Any]						    =     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   )





snake_case     					=		1e-4


def 	lowerCamelCase__      (  ):

  """simple docstring"""






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


@require_vision
@slow
class 			SCREAMING_SNAKE_CASE      (      unittest.TestCase       ):
     '''simple docstring'''


     @cached_property
     def 					_A							(					self							:						Tuple   ):
       return (
           MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco"   )
           if is_vision_available()
           else None
       )


     def 					_A							(					self							:						Optional[int]   ):
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco"   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Tuple						    =     self.default_image_processor
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     prepare_img()
       SCREAMING_SNAKE_CASE							:   Any						    =     image_processor(UpperCAmelCase_       ,			return_tensors="pt"   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     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(UpperCAmelCase_       ,			(1, 3, 800, 1088)   )

       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   Optional[int]						    =     model(**UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   List[str]						    =     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							:   int						    =     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							:   List[str]						    =     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 					_A							(					self							:						Optional[Any]   ):
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     (
           MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"   )
           .to(UpperCAmelCase_   )
           .eval()
       )
       SCREAMING_SNAKE_CASE							:   Dict						    =     self.default_image_processor
       SCREAMING_SNAKE_CASE							:   List[str]						    =     prepare_img()
       SCREAMING_SNAKE_CASE							:   List[str]						    =     image_processor(UpperCAmelCase_       ,			return_tensors="pt"   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   List[str]						    =     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(UpperCAmelCase_       ,			(1, 3, 800, 1088)   )

       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   List[Any]						    =     model(**UpperCAmelCase_   )
       # masks_queries_logits
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     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							:   Optional[int]						    =     [
           [-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							:   List[Any]						    =     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							:   int						    =     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							:   Union[str, Any]						    =     torch.tensor(
           [
               [1.6_512E00, -5.2_572E00, -3.3_519E00],
               [3.6_169E-02, -5.9_025E00, -2.9_313E00],
               [1.0_766E-04, -7.7_630E00, -5.1_263E00],
           ]   ).to(UpperCAmelCase_   )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       ,			UpperCAmelCase_       ,			atol=UpperCAmelCase_   )   )


     def 					_A							(					self							:						int   ):
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     (
           MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff"   )
           .to(UpperCAmelCase_   )
           .eval()
       )
       SCREAMING_SNAKE_CASE							:   int						    =     self.default_image_processor
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     prepare_img()
       SCREAMING_SNAKE_CASE							:   Any						    =     image_processor(UpperCAmelCase_       ,			return_tensors="pt"   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   List[str]						    =     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(UpperCAmelCase_       ,			(1, 3, 800, 1088)   )

       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   Dict						    =     model(**UpperCAmelCase_   )
       # masks_queries_logits
       SCREAMING_SNAKE_CASE							:   int						    =     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							:   Dict						    =     [[-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							:   Optional[int]						    =     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							:   str						    =     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							:   Dict						    =     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 					_A							(					self							:						List[Any]   ):
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     (
           MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"   )
           .to(UpperCAmelCase_   )
           .eval()
       )
       SCREAMING_SNAKE_CASE							:   Dict						    =     self.default_image_processor

       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     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							:   Dict						    =     inputs["pixel_values"].to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     [el.to(UpperCAmelCase_   ) for el in inputs["mask_labels"]]
       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     [el.to(UpperCAmelCase_   ) for el in inputs["class_labels"]]

       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   Any						    =     model(**UpperCAmelCase_   )

       self.assertTrue(outputs.loss is not None   )







"""simple docstring"""






import math


def      UpperCAmelCase__			(							lowerCAmelCase__	:int						)					->       bool:
      '''simple docstring'''


      lowercase								=      math.loga(math.sqrt(4 * positive_integer + 1						) / 2 + 1 / 2						)

      return exponent == int(lowerCAmelCase__						)


def      UpperCAmelCase__			(							lowerCAmelCase__	:float = 1 / 1_2_3_4_5						)					->       int:
      '''simple docstring'''


      lowercase								=      0
      lowercase								=      0

      lowercase								=      3
      while True:
            lowercase								=      (integer**2 - 1) / 4
            # if candidate is an integer, then there is a partition for k
            if partition_candidate == int(lowerCAmelCase__						):
                  lowercase								=      int(lowerCAmelCase__						)
                  total_partitions += 1
                  if check_partition_perfect(lowerCAmelCase__						):
                        perfect_partitions += 1
            if perfect_partitions > 0:
                  if perfect_partitions / total_partitions < max_proportion:
                        return int(lowerCAmelCase__						)
            integer += 1


if __name__ == "__main__":
       print(F"""{solution() = }""")



