






'''simple docstring'''
import inspect
import unittest

import numpy as np

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

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


if is_torch_available():
 import torch

 from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

 if is_vision_available():
  from transformers import MaskaFormerImageProcessor

if is_vision_available():
 from PIL import Image


class        _UpperCAmelCase						:




    def __init__(			self  :       Union[str, Any]  ,     a  :       List[Any]  ,     a  :       Dict=2  ,     a  :       int=True  ,     a  :       Optional[Any]=False  ,     a  :       str=1_0  ,     a  :       Union[str, Any]=3  ,     a  :       str=3_2 * 8  ,     a  :       Tuple=3_2 * 8  ,     a  :       Optional[int]=4  ,     a  :       List[str]=6_4  ,     ):






       '''simple docstring'''






       lowercase_	:    Dict           =     parent
       lowercase_	:    List[str]           =     batch_size
       lowercase_	:    Dict           =     is_training
       lowercase_	:    Tuple           =     use_auxiliary_loss
       lowercase_	:    List[Any]           =     num_queries
       lowercase_	:    Any           =     num_channels
       lowercase_	:    Optional[int]           =     min_size
       lowercase_	:    Dict           =     max_size
       lowercase_	:    Tuple           =     num_labels
       lowercase_	:    Optional[int]           =     hidden_dim
       lowercase_	:    Optional[int]           =     hidden_dim




    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    str           =     floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]			).to(
           a			)

       lowercase_	:    Optional[int]           =     torch.ones([self.batch_size, self.min_size, self.max_size]  ,     device=a			)

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

       lowercase_	:    Union[str, Any]           =     self.get_config()
       return config, pixel_values, pixel_mask, mask_labels, class_labels




    def 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






       lowercase_	:    List[Any]           =     MaskaFormerConfig(
           hidden_size=self.hidden_dim  ,     )
       lowercase_	:    Optional[Any]           =     self.num_queries
       lowercase_	:    int           =     self.num_labels

       lowercase_	:    Tuple           =     [1, 1, 1, 1]
       lowercase_	:    Tuple           =     self.num_channels

       lowercase_	:    Dict           =     6_4
       lowercase_	:    Union[str, Any]           =     1_2_8
       lowercase_	:    Tuple           =     self.hidden_dim
       lowercase_	:    Optional[Any]           =     self.hidden_dim
       lowercase_	:    List[Any]           =     self.hidden_dim
       return config




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]			):






       '''simple docstring'''






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




    def 				lowerCAmelCase__				(			self  :       Dict  ,     a  :       int  ,     a  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    int           =     output.encoder_hidden_states
       lowercase_	:    List[Any]           =     output.pixel_decoder_hidden_states
       lowercase_	:    Optional[int]           =     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 				lowerCAmelCase__				(			self  :       int  ,     a  :       str  ,     a  :       Dict  ,     a  :       Dict  ,     a  :       Dict=False			):






       '''simple docstring'''






       with torch.no_grad():
          lowercase_	:    str           =     MaskaFormerModel(config=a			)
          model.to(a			)
          model.eval()

          lowercase_	:    str           =     model(pixel_values=a  ,     pixel_mask=a			)
          lowercase_	:    List[str]           =     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 				lowerCAmelCase__				(			self  :       Optional[int]  ,     a  :       Union[str, Any]  ,     a  :       str  ,     a  :       Tuple  ,     a  :       str  ,     a  :       Dict			):






       '''simple docstring'''






       lowercase_	:    List[str]           =     MaskaFormerForUniversalSegmentation(config=a			)
       model.to(a			)
       model.eval()

       def comm_check_on_output(a  :       Union[str, 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():
          lowercase_	:    Optional[Any]           =     model(pixel_values=a  ,     pixel_mask=a			)
          lowercase_	:    str           =     model(a			)

          comm_check_on_output(a			)

          lowercase_	:    int           =     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						(		snake_case				,					snake_case				,					unittest.TestCase			):
    __lowerCamelCase:   int		       =    (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
    __lowerCamelCase:   Any		       =    {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

    __lowerCamelCase:   Dict		       =    False
    __lowerCamelCase:   int		       =    False
    __lowerCamelCase:   Tuple		       =    False
    __lowerCamelCase:   Dict		       =    False




    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     MaskaFormerModelTester(self			)
       lowercase_	:    Dict           =     ConfigTester(self  ,     config_class=a  ,     has_text_modality=a			)




    def 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






       self.config_tester.run_common_tests()




    def 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    Dict           =     self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskaformer_model(a  ,     **a  ,     output_hidden_states=a			)




    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






       lowercase_	:    Dict           =     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 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






       pass




    @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method"			)
    def 				lowerCAmelCase__				(			self  :       Optional[Any]			):






       '''simple docstring'''






       pass




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






       '''simple docstring'''






       pass




    @unittest.skip(reason="Mask2Former does not use token embeddings"			)
    def 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






       pass




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






       '''simple docstring'''






       pass




    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."			)
    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       pass




    def 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    Optional[int]           =     self.model_tester.prepare_config_and_inputs_for_common()

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

          lowercase_	:    Tuple           =     ["pixel_values"]
          self.assertListEqual(arg_names[:1]  ,     a			)




    @slow
    def 				lowerCAmelCase__				(			self  :       Tuple			):






       '''simple docstring'''






       for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
          lowercase_	:    Union[str, Any]           =     MaskaFormerModel.from_pretrained(a			)
          self.assertIsNotNone(a			)




    def 				lowerCAmelCase__				(			self  :       Tuple			):






       '''simple docstring'''






       lowercase_	:    Union[str, Any]           =     (self.model_tester.min_size,) * 2
       lowercase_	:    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(),
       }
       lowercase_	:    str           =     self.model_tester.get_config()

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




    def 				lowerCAmelCase__				(			self  :       List[str]			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    Dict           =     self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskaformer_model(a  ,     **a  ,     output_hidden_states=a			)




    def 				lowerCAmelCase__				(			self  :       Optional[Any]			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    Union[str, Any]           =     self.model_tester.prepare_config_and_inputs_for_common()

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




    def 				lowerCAmelCase__				(			self  :       Optional[Any]			):






       '''simple docstring'''






       if not self.model_tester.is_training:
          return

       lowercase_	:    Optional[Any]           =     self.all_model_classes[1]
       lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_	:    Optional[int]           =     self.model_tester.prepare_config_and_inputs()

       lowercase_	:    Union[str, Any]           =     model_class(a			)
       model.to(a			)
       model.train()

       lowercase_	:    str           =     model(a  ,     mask_labels=a  ,     class_labels=a			).loss
       loss.backward()





    def 				lowerCAmelCase__				(			self  :       List[str]			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     self.all_model_classes[1]
       lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_	:    Union[str, Any]           =     self.model_tester.prepare_config_and_inputs()
       lowercase_	:    str           =     True
       lowercase_	:    Dict           =     True

       lowercase_	:    Optional[Any]           =     model_class(a			).to(a			)
       model.train()

       lowercase_	:    Tuple           =     model(a  ,     mask_labels=a  ,     class_labels=a			)

       lowercase_	:    int           =     outputs.encoder_hidden_states[0]
       encoder_hidden_states.retain_grad()

       lowercase_	:    Optional[int]           =     outputs.pixel_decoder_hidden_states[0]
       pixel_decoder_hidden_states.retain_grad()

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

       lowercase_	:    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			)


UpperCamelCase__ =			1e-4




def 		__SCREAMING_SNAKE_CASE					(  ):


   """simple docstring"""




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





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




    @cached_property
    def 				lowerCAmelCase__				(			self  :       int			):






       '''simple docstring'''






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




    @cached_property
    def 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






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




    def 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     MaskaFormerModel.from_pretrained(self.model_checkpoints			).to(a			)
       lowercase_	:    Tuple           =     self.default_image_processor
       lowercase_	:    str           =     prepare_img()
       lowercase_	:    List[Any]           =     image_processor(a  ,     return_tensors="pt"			).to(a			)
       lowercase_	:    Optional[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():
          lowercase_	:    int           =     model(**a			)

       lowercase_	:    Dict           =     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			)			)

       lowercase_	:    Optional[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			)			)

       lowercase_	:    List[Any]           =     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 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints			).to(a			).eval()
       lowercase_	:    Optional[int]           =     self.default_image_processor
       lowercase_	:    int           =     prepare_img()
       lowercase_	:    Any           =     image_processor(a  ,     return_tensors="pt"			).to(a			)
       lowercase_	:    List[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():
          lowercase_	:    Tuple           =     model(**a			)
       # masks_queries_logits
       lowercase_	:    Any           =     outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape  ,     (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)			)
       lowercase_	:    Optional[Any]           =     [
           [-8.7839, -9.0056, -8.8121],
           [-7.4104, -7.0313, -6.5401],
           [-6.6105, -6.3427, -6.4675],
       ]
       lowercase_	:    List[Any]           =     torch.tensor(a			).to(a			)
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]  ,     a  ,     atol=a			)			)
       # class_queries_logits
       lowercase_	:    Optional[Any]           =     outputs.class_queries_logits
       self.assertEqual(class_queries_logits.shape  ,     (1, model.config.num_queries, model.config.num_labels + 1)			)
       lowercase_	:    Union[str, Any]           =     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 				lowerCAmelCase__				(			self  :       Union[str, Any]			):






       '''simple docstring'''






       lowercase_	:    Dict           =     MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints			).to(a			).eval()
       lowercase_	:    Optional[int]           =     self.default_image_processor

       lowercase_	:    List[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"  ,     )

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

       with torch.no_grad():
          lowercase_	:    Optional[Any]           =     model(**a			)

       self.assertTrue(outputs.loss is not None			)












'''simple docstring'''
def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




   if number < 0:
      raise ValueError("number must not be negative"							)
   return number & (number - 1) == 0


if __name__ == "__main__":
 import doctest

 doctest.testmod()




