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



     def __init__(							self :Any      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Any=2      ,  _lowerCamelCase :Union[str, Any]=True      ,  _lowerCamelCase :Dict=False      ,  _lowerCamelCase :List[str]=10      ,  _lowerCamelCase :Optional[int]=3      ,  _lowerCamelCase :List[Any]=32 * 8      ,  _lowerCamelCase :Optional[int]=32 * 8      ,  _lowerCamelCase :Union[str, Any]=4      ,  _lowerCamelCase :Union[str, Any]=64      ,  ):







      '''simple docstring'''



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



     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]   ).to(
          _lowercase   )

      UpperCamelCase_     :					List[str]   	=torch.ones([self.batch_size, self.min_size, self.max_size]      ,  device=_lowercase   )

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

      UpperCamelCase_     :					Dict   	=self.get_config()
      return config, pixel_values, pixel_mask, mask_labels, class_labels



     def  lowerCamelCase_						(							self :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=MaskaFormerConfig(
          hidden_size=self.hidden_dim      ,  )
      UpperCamelCase_     :					Union[str, Any]   	=self.num_queries
      UpperCamelCase_     :					Optional[int]   	=self.num_labels

      UpperCamelCase_     :					Any   	=[1, 1, 1, 1]
      UpperCamelCase_     :					str   	=self.num_channels

      UpperCamelCase_     :					int   	=64
      UpperCamelCase_     :					Any   	=128
      UpperCamelCase_     :					Optional[Any]   	=self.hidden_dim
      UpperCamelCase_     :					Optional[int]   	=self.hidden_dim
      UpperCamelCase_     :					Any   	=self.hidden_dim
      return config



     def  lowerCamelCase_						(							self :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_     :					Optional[Any]   	=self.prepare_config_and_inputs()
      UpperCamelCase_     :					Union[str, Any]   	={'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
      return config, inputs_dict



     def  lowerCamelCase_						(							self :Dict      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=output.encoder_hidden_states
      UpperCamelCase_     :					int   	=output.pixel_decoder_hidden_states
      UpperCamelCase_     :					List[Any]   	=output.transformer_decoder_hidden_states

      self.parent.assertTrue(len(_lowercase   )      ,  len(config.backbone_config.depths   )   )
      self.parent.assertTrue(len(_lowercase   )      ,  len(config.backbone_config.depths   )   )
      self.parent.assertTrue(len(_lowercase   )      ,  config.decoder_layers   )



     def  lowerCamelCase_						(							self :Optional[Any]      ,  _lowerCamelCase :Optional[int]      ,  _lowerCamelCase :List[str]      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :Tuple=False   ):







      '''simple docstring'''



      with torch.no_grad():
       UpperCamelCase_     :					Tuple   	=MaskaFormerModel(config=_lowercase   )
       model.to(_lowercase   )
       model.eval()

       UpperCamelCase_     :					int   	=model(pixel_values=_lowercase      ,  pixel_mask=_lowercase   )
       UpperCamelCase_     :					List[str]   	=model(_lowercase      ,  output_hidden_states=_lowercase   )

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




     def  lowerCamelCase_						(							self :List[Any]      ,  _lowerCamelCase :int      ,  _lowerCamelCase :Any      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=MaskaFormerForUniversalSegmentation(config=_lowercase   )
      model.to(_lowercase   )
      model.eval()

      def comm_check_on_output(_lowerCamelCase :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():
       UpperCamelCase_     :					Optional[Any]   	=model(pixel_values=_lowercase      ,  pixel_mask=_lowercase   )
       UpperCamelCase_     :					List[Any]   	=model(_lowercase   )

       comm_check_on_output(_lowercase   )

       UpperCamelCase_     :					Dict   	=model(
           pixel_values=_lowercase      ,  pixel_mask=_lowercase      ,  mask_labels=_lowercase      ,  class_labels=_lowercase   )

      comm_check_on_output(_lowercase   )

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

     UpperCAmelCase__         =      False
     UpperCAmelCase__         =      False
     UpperCAmelCase__         =      False
     UpperCAmelCase__         =      False



     def  lowerCamelCase_						(							self :int   ):







      '''simple docstring'''



      UpperCamelCase_     :					Any   	=MaskaFormerModelTester(self   )
      UpperCamelCase_     :					Optional[Any]   	=ConfigTester(self      ,  config_class=_lowercase      ,  has_text_modality=_lowercase   )



     def  lowerCamelCase_						(							self :str   ):







      '''simple docstring'''



      self.config_tester.run_common_tests()



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_	,     UpperCamelCase_     :					Optional[int]   	=self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskaformer_model(_lowercase      ,  **_lowercase      ,  output_hidden_states=_lowercase   )



     def  lowerCamelCase_						(							self :Dict   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_lowercase   )



     @unittest.skip(reason='Mask2Former does not use inputs_embeds'   )
     def  lowerCamelCase_						(							self :List[Any]   ):







      '''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 :Optional[Any]   ):







      '''simple docstring'''



      pass



     @unittest.skip(reason='Mask2Former does not use token embeddings'   )
     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      pass



     @require_torch_multi_gpu
     @unittest.skip(
         reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'   )
     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      pass



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







      '''simple docstring'''



      pass



     def  lowerCamelCase_						(							self :int   ):







      '''simple docstring'''



      UpperCamelCase_	,     UpperCamelCase_     :					Optional[Any]   	=self.model_tester.prepare_config_and_inputs_for_common()

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

       UpperCamelCase_     :					Dict   	=['pixel_values']
       self.assertListEqual(arg_names[:1]      ,  _lowercase   )



     @slow
     def  lowerCamelCase_						(							self :int   ):







      '''simple docstring'''



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



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=(self.model_tester.min_size,) * 2
      UpperCamelCase_     :					Dict   	={
          'pixel_values': torch.randn((2, 3, *size)      ,  device=_lowercase   ),
          'mask_labels': torch.randn((2, 10, *size)      ,  device=_lowercase   ),
          'class_labels': torch.zeros(2      ,  10      ,  device=_lowercase   ).long(),
      }
      UpperCamelCase_     :					List[str]   	=self.model_tester.get_config()

      UpperCamelCase_     :					Optional[Any]   	=MaskaFormerForUniversalSegmentation(_lowercase   ).to(_lowercase   )
      UpperCamelCase_     :					int   	=model(**_lowercase   )
      self.assertTrue(outputs.loss is not None   )



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_	,     UpperCamelCase_     :					Any   	=self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskaformer_model(_lowercase      ,  **_lowercase      ,  output_hidden_states=_lowercase   )



     def  lowerCamelCase_						(							self :str   ):







      '''simple docstring'''



      UpperCamelCase_	,     UpperCamelCase_     :					Dict   	=self.model_tester.prepare_config_and_inputs_for_common()

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



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







      '''simple docstring'''



      if not self.model_tester.is_training:
       return

      UpperCamelCase_     :					Dict   	=self.all_model_classes[1]
      UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_     :					Union[str, Any]   	=self.model_tester.prepare_config_and_inputs()

      UpperCamelCase_     :					Optional[Any]   	=model_class(_lowercase   )
      model.to(_lowercase   )
      model.train()

      UpperCamelCase_     :					str   	=model(_lowercase      ,  mask_labels=_lowercase      ,  class_labels=_lowercase   ).loss
      loss.backward()




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







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	=self.all_model_classes[1]
      UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_     :					Tuple   	=self.model_tester.prepare_config_and_inputs()
      UpperCamelCase_     :					Tuple   	=True
      UpperCamelCase_     :					Tuple   	=True

      UpperCamelCase_     :					Any   	=model_class(_lowercase   ).to(_lowercase   )
      model.train()

      UpperCamelCase_     :					Union[str, Any]   	=model(_lowercase      ,  mask_labels=_lowercase      ,  class_labels=_lowercase   )

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

      UpperCamelCase_     :					List[Any]   	=outputs.pixel_decoder_hidden_states[0]
      pixel_decoder_hidden_states.retain_grad()

      UpperCamelCase_     :					Optional[Any]   	=outputs.transformer_decoder_hidden_states[0]
      transformer_decoder_hidden_states.retain_grad()

      UpperCamelCase_     :					Any   	=outputs.attentions[0]
      attentions.retain_grad()

      outputs.loss.backward(retain_graph=_lowercase   )

      self.assertIsNotNone(encoder_hidden_states.grad   )
      self.assertIsNotNone(pixel_decoder_hidden_states.grad   )
      self.assertIsNotNone(transformer_decoder_hidden_states.grad   )
      self.assertIsNotNone(attentions.grad   )


__SCREAMING_SNAKE_CASE							=     1e-4




def       A_  (				):
 UpperCamelCase_     :					str   	=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
 return image





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



     @cached_property
     def  lowerCamelCase_						(							self :Dict   ):







      '''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 :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=MaskaFormerModel.from_pretrained(self.model_checkpoints   ).to(_lowercase   )
      UpperCamelCase_     :					Tuple   	=self.default_image_processor
      UpperCamelCase_     :					List[str]   	=prepare_img()
      UpperCamelCase_     :					int   	=image_processor(_lowercase      ,  return_tensors='pt'   ).to(_lowercase   )
      UpperCamelCase_     :					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(_lowercase      ,  (1, 3, 384, 384)   )

      with torch.no_grad():
       UpperCamelCase_     :					Optional[Any]   	=model(**_lowercase   )

      UpperCamelCase_     :					Any   	=torch.tensor(
          [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]   ).to(_lowercase   )
      self.assertTrue(
          torch.allclose(
              outputs.encoder_last_hidden_state[0, 0, :3, :3]      ,  _lowercase      ,  atol=_lowercase   )   )

      UpperCamelCase_     :					Union[str, Any]   	=torch.tensor(
          [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]   ).to(_lowercase   )
      self.assertTrue(
          torch.allclose(
              outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]      ,  _lowercase      ,  atol=_lowercase   )   )

      UpperCamelCase_     :					List[str]   	=torch.tensor(
          [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]   ).to(_lowercase   )
      self.assertTrue(
          torch.allclose(
              outputs.transformer_decoder_last_hidden_state[0, :3, :3]      ,  _lowercase      ,  atol=_lowercase   )   )



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints   ).to(_lowercase   ).eval()
      UpperCamelCase_     :					Tuple   	=self.default_image_processor
      UpperCamelCase_     :					List[Any]   	=prepare_img()
      UpperCamelCase_     :					Any   	=image_processor(_lowercase      ,  return_tensors='pt'   ).to(_lowercase   )
      UpperCamelCase_     :					Optional[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(_lowercase      ,  (1, 3, 384, 384)   )

      with torch.no_grad():
       UpperCamelCase_     :					Any   	=model(**_lowercase   )
      # masks_queries_logits
      UpperCamelCase_     :					Union[str, Any]   	=outputs.masks_queries_logits
      self.assertEqual(
          masks_queries_logits.shape      ,  (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)   )
      UpperCamelCase_     :					Optional[int]   	=[
          [-8.7839, -9.0056, -8.8121],
          [-7.4104, -7.0313, -6.5401],
          [-6.6105, -6.3427, -6.4675],
      ]
      UpperCamelCase_     :					List[str]   	=torch.tensor(_lowercase   ).to(_lowercase   )
      self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]      ,  _lowercase      ,  atol=_lowercase   )   )
      # class_queries_logits
      UpperCamelCase_     :					Optional[Any]   	=outputs.class_queries_logits
      self.assertEqual(class_queries_logits.shape      ,  (1, model.config.num_queries, model.config.num_labels + 1)   )
      UpperCamelCase_     :					Optional[int]   	=torch.tensor(
          [
              [1.8324, -8.0835, -4.1922],
              [0.8450, -9.0050, -3.6053],
              [0.3045, -7.7293, -3.0275],
          ]   ).to(_lowercase   )
      self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]      ,  _lowercase      ,  atol=_lowercase   )   )




     def  lowerCamelCase_						(							self :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints   ).to(_lowercase   ).eval()
      UpperCamelCase_     :					List[Any]   	=self.default_image_processor

      UpperCamelCase_     :					Union[str, Any]   	=image_processor(
          [np.zeros((3, 800, 1_333)   ), np.zeros((3, 800, 1_333)   )]      ,  segmentation_maps=[np.zeros((384, 384)   ).astype(np.floataa   ), np.zeros((384, 384)   ).astype(np.floataa   )]      ,  return_tensors='pt'      ,  )

      UpperCamelCase_     :					Union[str, Any]   	=inputs['pixel_values'].to(_lowercase   )
      UpperCamelCase_     :					Optional[int]   	=[el.to(_lowercase   ) for el in inputs['mask_labels']]
      UpperCamelCase_     :					str   	=[el.to(_lowercase   ) for el in inputs['class_labels']]

      with torch.no_grad():
       UpperCamelCase_     :					Optional[int]   	=model(**_lowercase   )

      self.assertTrue(outputs.loss is not None   )






'''simple docstring'''
def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )		->		tuple[float, float]:

			# Check if the input is valid
			if not len(SCREAMING_SNAKE_CASE_     ) == len(SCREAMING_SNAKE_CASE_     ) == 3:
						raise ValueError('Please enter a valid equation.'     )
			if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0:
						raise ValueError('Both a & b of two equations can\'t be zero.'     )

			# Extract the coefficients
			A_		, A_		, A_									= equationa
			A_		, A_		, A_									= equationa

			# Calculate the determinants of the matrices
			A_									= aa * ba - aa * ba
			A_									= ca * ba - ca * ba
			A_									= aa * ca - aa * ca

			# Check if the system of linear equations has a solution (using Cramer's rule)
			if determinant == 0:
						if determinant_x == determinant_y == 0:
									raise ValueError('Infinite solutions. (Consistent system)'     )
						else:
									raise ValueError('No solution. (Inconsistent system)'     )
			else:
						if determinant_x == determinant_y == 0:
									# Trivial solution (Inconsistent system)
									return (0.0, 0.0)
						else:
									A_									= determinant_x / determinant
									A_									= determinant_y / determinant
									# Non-Trivial Solution (Consistent system)
									return (x, y)




