


"""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 						_A  :







    """simple docstring"""




    def __init__(					self				:    List[str]				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    str=2				, __UpperCAmelCase				:    Any=True				, __UpperCAmelCase				:    List[Any]=False				, __UpperCAmelCase				:    Optional[int]=10				, __UpperCAmelCase				:    List[str]=3				, __UpperCAmelCase				:    Union[str, Any]=32 * 8				, __UpperCAmelCase				:    Tuple=32 * 8				, __UpperCAmelCase				:    Dict=4				, __UpperCAmelCase				:    Dict=64				, ):
      a						:		Union[str, Any]      							=			parent
      a						:		Dict      							=			batch_size
      a						:		List[str]      							=			is_training
      a						:		str      							=			use_auxiliary_loss
      a						:		Union[str, Any]      							=			num_queries
      a						:		List[Any]      							=			num_channels
      a						:		Union[str, Any]      							=			min_size
      a						:		Dict      							=			max_size
      a						:		str      							=			num_labels
      a						:		Optional[Any]      							=			hidden_dim
      a						:		str      							=			hidden_dim






    def 	__snake_case							(					self				:    str):
      a						:		Any      							=			floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
          __UpperCAmelCase)

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

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

      a						:		str      							=			self.get_config()
      return config, pixel_values, pixel_mask, mask_labels, class_labels






    def 	__snake_case							(					self				:    Union[str, Any]):
      a						:		Any      							=			MaskaFormerConfig(
          hidden_size=self.hidden_dim				, )
      a						:		Optional[Any]      							=			self.num_queries
      a						:		Union[str, Any]      							=			self.num_labels

      a						:		List[Any]      							=			[1, 1, 1, 1]
      a						:		Union[str, Any]      							=			self.num_channels

      a						:		Union[str, Any]      							=			64
      a						:		List[str]      							=			128
      a						:		Dict      							=			self.hidden_dim
      a						:		Any      							=			self.hidden_dim
      a						:		Optional[int]      							=			self.hidden_dim
      return config






    def 	__snake_case							(					self				:    str):
      a							,		a							,		a							,		a							,		a						:		Optional[int]      							=			self.prepare_config_and_inputs()
      a						:		Optional[int]      							=			{"pixel_values": pixel_values, "pixel_mask": pixel_mask}
      return config, inputs_dict






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    Tuple				, __UpperCAmelCase				:    Optional[int]):
      a						:		Union[str, Any]      							=			output.encoder_hidden_states
      a						:		int      							=			output.pixel_decoder_hidden_states
      a						:		Optional[int]      							=			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_layers)






    def 	__snake_case							(					self				:    Tuple				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    Any				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    str=False):
      with torch.no_grad():
        a						:		Union[str, Any]      							=			MaskaFormerModel(config=__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.eval()

        a						:		Union[str, Any]      							=			model(pixel_values=__UpperCAmelCase				, pixel_mask=__UpperCAmelCase)
        a						:		Dict      							=			model(__UpperCAmelCase				, output_hidden_states=__UpperCAmelCase)

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






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    str):
      a						:		str      							=			MaskaFormerForUniversalSegmentation(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()

      def comm_check_on_output(__UpperCAmelCase				:    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():
        a						:		List[Any]      							=			model(pixel_values=__UpperCAmelCase				, pixel_mask=__UpperCAmelCase)
        a						:		List[Any]      							=			model(__UpperCAmelCase)

        comm_check_on_output(__UpperCAmelCase)

        a						:		Optional[int]      							=			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 						_A  (  _a    ,_a    ,unittest.TestCase  ):







    """simple docstring"""




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

    UpperCAmelCase       :							Any	=       False
    UpperCAmelCase       :							Any	=       False
    UpperCAmelCase       :							int	=       False
    UpperCAmelCase       :							List[Any]	=       False






    def 	__snake_case							(					self				:    str):
      a						:		Tuple      							=			MaskaFormerModelTester(self)
      a						:		Union[str, Any]      							=			ConfigTester(self				, config_class=__UpperCAmelCase				, has_text_modality=__UpperCAmelCase)






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






    def 	__snake_case							(					self				:    List[Any]):
      a							,		a						:		Any      							=			self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase				, **__UpperCAmelCase				, output_hidden_states=__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[Any]):
      a						:		int      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__UpperCAmelCase)






    @unittest.skip(reason="Mask2Former does not use inputs_embeds")
    def 	__snake_case							(					self				:    Any):
      pass






    @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method")
    def 	__snake_case							(					self				:    Any):
      pass






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






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






    @require_torch_multi_gpu
    @unittest.skip(
        reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`")
    def 	__snake_case							(					self				:    str):
      pass






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






    def 	__snake_case							(					self				:    List[str]):
      a							,		a						:		Tuple      							=			self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		Union[str, Any]      							=			["pixel_values"]
        self.assertListEqual(arg_names[:1]				, __UpperCAmelCase)






    @slow
    def 	__snake_case							(					self				:    List[Any]):
      for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
        a						:		Any      							=			MaskaFormerModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		int      							=			(self.model_tester.min_size,) * 2
      a						:		Dict      							=			{
          "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(),
      }
      a						:		Any      							=			self.model_tester.get_config()

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






    def 	__snake_case							(					self				:    Union[str, Any]):
      a							,		a						:		int      							=			self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase				, **__UpperCAmelCase				, output_hidden_states=__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[Any]):
      a							,		a						:		Dict      							=			self.model_tester.prepare_config_and_inputs_for_common()

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






    def 	__snake_case							(					self				:    Tuple):
      if not self.model_tester.is_training:
        return

      a						:		Tuple      							=			self.all_model_classes[1]
      a							,		a							,		a							,		a							,		a						:		List[str]      							=			self.model_tester.prepare_config_and_inputs()

      a						:		Dict      							=			model_class(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.train()

      a						:		Optional[int]      							=			model(__UpperCAmelCase				, mask_labels=__UpperCAmelCase				, class_labels=__UpperCAmelCase).loss
      loss.backward()






    def 	__snake_case							(					self				:    str):
      a						:		str      							=			self.all_model_classes[1]
      a							,		a							,		a							,		a							,		a						:		Union[str, Any]      							=			self.model_tester.prepare_config_and_inputs()
      a						:		Dict      							=			True
      a						:		str      							=			True

      a						:		Tuple      							=			model_class(__UpperCAmelCase).to(__UpperCAmelCase)
      model.train()

      a						:		Union[str, Any]      							=			model(__UpperCAmelCase				, mask_labels=__UpperCAmelCase				, class_labels=__UpperCAmelCase)

      a						:		List[Any]      							=			outputs.encoder_hidden_states[0]
      encoder_hidden_states.retain_grad()

      a						:		str      							=			outputs.pixel_decoder_hidden_states[0]
      pixel_decoder_hidden_states.retain_grad()

      a						:		int      							=			outputs.transformer_decoder_hidden_states[0]
      transformer_decoder_hidden_states.retain_grad()

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






__lowercase    					=      1e-4


def      lowercase			(				)->      Union[str, Any]:
  '''simple docstring'''







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







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







    """simple docstring"""




    @cached_property
    def 	__snake_case							(					self				:    Any):
      return "facebook/mask2former-swin-small-coco-instance"






    @cached_property
    def 	__snake_case							(					self				:    Dict):
      return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None






    def 	__snake_case							(					self				:    Union[str, Any]):
      a						:		str      							=			MaskaFormerModel.from_pretrained(self.model_checkpoints).to(__UpperCAmelCase)
      a						:		List[str]      							=			self.default_image_processor
      a						:		int      							=			prepare_img()
      a						:		Union[str, Any]      							=			image_processor(__UpperCAmelCase				, return_tensors="pt").to(__UpperCAmelCase)
      a						:		Optional[int]      							=			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, 384, 384))

      with torch.no_grad():
        a						:		int      							=			model(**__UpperCAmelCase)

      a						:		Tuple      							=			torch.tensor(
          [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]]).to(__UpperCAmelCase)
      self.assertTrue(
          torch.allclose(
              outputs.encoder_last_hidden_state[0, 0, :3, :3]				, __UpperCAmelCase				, atol=__UpperCAmelCase))

      a						:		Union[str, Any]      							=			torch.tensor(
          [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]]).to(__UpperCAmelCase)
      self.assertTrue(
          torch.allclose(
              outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]				, __UpperCAmelCase				, atol=__UpperCAmelCase))

      a						:		Dict      							=			torch.tensor(
          [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]]).to(__UpperCAmelCase)
      self.assertTrue(
          torch.allclose(
              outputs.transformer_decoder_last_hidden_state[0, :3, :3]				, __UpperCAmelCase				, atol=__UpperCAmelCase))






    def 	__snake_case							(					self				:    Optional[Any]):
      a						:		int      							=			MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(__UpperCAmelCase).eval()
      a						:		List[str]      							=			self.default_image_processor
      a						:		Optional[Any]      							=			prepare_img()
      a						:		Dict      							=			image_processor(__UpperCAmelCase				, return_tensors="pt").to(__UpperCAmelCase)
      a						:		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, 384, 384))

      with torch.no_grad():
        a						:		Optional[int]      							=			model(**__UpperCAmelCase)
      # masks_queries_logits
      a						:		Optional[Any]      							=			outputs.masks_queries_logits
      self.assertEqual(
          masks_queries_logits.shape				, (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4))
      a						:		List[Any]      							=			[
          [-8.7_839, -9.0_056, -8.8_121],
          [-7.4_104, -7.0_313, -6.5_401],
          [-6.6_105, -6.3_427, -6.4_675],
      ]
      a						:		int      							=			torch.tensor(__UpperCAmelCase).to(__UpperCAmelCase)
      self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]				, __UpperCAmelCase				, atol=__UpperCAmelCase))
      # class_queries_logits
      a						:		int      							=			outputs.class_queries_logits
      self.assertEqual(class_queries_logits.shape				, (1, model.config.num_queries, model.config.num_labels + 1))
      a						:		Optional[Any]      							=			torch.tensor(
          [
              [1.8_324, -8.0_835, -4.1_922],
              [0.8_450, -9.0_050, -3.6_053],
              [0.3_045, -7.7_293, -3.0_275],
          ]).to(__UpperCAmelCase)
      self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]				, __UpperCAmelCase				, atol=__UpperCAmelCase))






    def 	__snake_case							(					self				:    List[Any]):
      a						:		Any      							=			MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(__UpperCAmelCase).eval()
      a						:		int      							=			self.default_image_processor

      a						:		Dict      							=			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"				, )

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

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

      self.assertTrue(outputs.loss is not None)










"""simple docstring"""







def      lowercase			(				A_  ,   A_       )->      float:
  '''simple docstring'''







  if mass < 0:
    raise ValueError("The mass of a body cannot be negative"       )
  return 0.5 * mass * abs(A_       ) * abs(A_       )


if __name__ == "__main__":
 import doctest

 doctest.testmod(verbose=True)






