



'''simple docstring'''

# Author: OMKAR PATHAK, Nwachukwu Chidiebere

# Use a Python dictionary to construct the graph.
from __future__ import annotations

from pprint import pformat
from typing import Generic, TypeVar

__lowerCAmelCase		     =  TypeVar('''T''')

class       __magic_name__		(       Generic[T]  ):







							def __init__(				self   :			int      ,_UpperCAmelCase   :			bool = True						):
									_a	: dict[T, list[T]]								=				{}  # dictionary of lists
									_a	: Tuple								=				directed







							def 				__lowercase     (				self   :			Union[str, Any]      ,_UpperCAmelCase   :			T      ,_UpperCAmelCase   :			T						):

									if not self.directed:  # For undirected graphs
											# if both source vertex and destination vertex are both present in the
											# adjacency list, add destination vertex to source vertex list of adjacent
											# vertices and add source vertex to destination vertex list of adjacent
											# vertices.
											if source_vertex in self.adj_list and destination_vertex in self.adj_list:
													self.adj_list[source_vertex].append(_UpperCAmelCase						)
													self.adj_list[destination_vertex].append(_UpperCAmelCase						)
											# if only source vertex is present in adjacency list, add destination vertex
											# to source vertex list of adjacent vertices, then create a new vertex with
											# destination vertex as key and assign a list containing the source vertex
											# as it's first adjacent vertex.
											elif source_vertex in self.adj_list:
													self.adj_list[source_vertex].append(_UpperCAmelCase						)
													_a	: Optional[Any]								=				[source_vertex]
											# if only destination vertex is present in adjacency list, add source vertex
											# to destination vertex list of adjacent vertices, then create a new vertex
											# with source vertex as key and assign a list containing the source vertex
											# as it's first adjacent vertex.
											elif destination_vertex in self.adj_list:
													self.adj_list[destination_vertex].append(_UpperCAmelCase						)
													_a	: Union[str, Any]								=				[destination_vertex]
											# if both source vertex and destination vertex are not present in adjacency
											# list, create a new vertex with source vertex as key and assign a list
											# containing the destination vertex as it's first adjacent vertex also
											# create a new vertex with destination vertex as key and assign a list
											# containing the source vertex as it's first adjacent vertex.
											else:
													_a	: Union[str, Any]								=				[destination_vertex]
													_a	: Optional[int]								=				[source_vertex]
									else:  # For directed graphs
											# if both source vertex and destination vertex are present in adjacency
											# list, add destination vertex to source vertex list of adjacent vertices.
											if source_vertex in self.adj_list and destination_vertex in self.adj_list:
													self.adj_list[source_vertex].append(_UpperCAmelCase						)
											# if only source vertex is present in adjacency list, add destination
											# vertex to source vertex list of adjacent vertices and create a new vertex
											# with destination vertex as key, which has no adjacent vertex
											elif source_vertex in self.adj_list:
													self.adj_list[source_vertex].append(_UpperCAmelCase						)
													_a	: int								=				[]
											# if only destination vertex is present in adjacency list, create a new
											# vertex with source vertex as key and assign a list containing destination
											# vertex as first adjacent vertex
											elif destination_vertex in self.adj_list:
													_a	: Tuple								=				[destination_vertex]
											# if both source vertex and destination vertex are not present in adjacency
											# list, create a new vertex with source vertex as key and a list containing
											# destination vertex as it's first adjacent vertex. Then create a new vertex
											# with destination vertex as key, which has no adjacent vertex
											else:
													_a	: Tuple								=				[destination_vertex]
													_a	: str								=				[]

									return self







							def __repr__(				self   :			int						):
									return pformat(self.adj_list						)









'''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       __magic_name__		:







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







							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a	: Union[str, Any]								=				floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]						).to(
									    _UpperCAmelCase						)

									_a	: int								=				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	: Union[str, Any]								=				self.get_config()
									return config, pixel_values, pixel_mask, mask_labels, class_labels







							def 				__lowercase     (				self   :			List[str]						):
									_a	: int								=				MaskaFormerConfig(
									    hidden_size=self.hidden_dim      ,)
									_a	: List[str]								=				self.num_queries
									_a	: List[Any]								=				self.num_labels

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

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







							def 				__lowercase     (				self   :			str						):
									_a			,   _a			,   _a			,   _a			,   _a	: Tuple								=				self.prepare_config_and_inputs()
									_a	: List[Any]								=				{'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
									return config, inputs_dict







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

											_a	: Tuple								=				model(pixel_values=_UpperCAmelCase      ,pixel_mask=_UpperCAmelCase						)
											_a	: Tuple								=				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 				__lowercase     (				self   :			List[Any]      ,_UpperCAmelCase   :			Dict      ,_UpperCAmelCase   :			int      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			str      ,_UpperCAmelCase   :			Any						):
									_a	: List[Any]								=				MaskaFormerForUniversalSegmentation(config=_UpperCAmelCase						)
									model.to(_UpperCAmelCase						)
									model.eval()

									def comm_check_on_output(_UpperCAmelCase   :			Tuple						):
											# 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	: str								=				model(pixel_values=_UpperCAmelCase      ,pixel_mask=_UpperCAmelCase						)
											_a	: int								=				model(_UpperCAmelCase						)

											comm_check_on_output(_UpperCAmelCase						)

											_a	: str								=				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       __magic_name__		(       _UpperCamelCase     ,		_UpperCamelCase     ,		unittest.TestCase  ):
							lowerCAmelCase			:       Union[str, Any]  							=   (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
							lowerCAmelCase			:       Optional[Any]  							=   {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

							lowerCAmelCase			:       Any  							=   False
							lowerCAmelCase			:       Any  							=   False
							lowerCAmelCase			:       str  							=   False
							lowerCAmelCase			:       str  							=   False







							def 				__lowercase     (				self   :			Dict						):
									_a	: int								=				MaskaFormerModelTester(self						)
									_a	: Tuple								=				ConfigTester(self      ,config_class=_UpperCAmelCase      ,has_text_modality=_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Optional[Any]						):
									self.config_tester.run_common_tests()







							def 				__lowercase     (				self   :			Dict						):
									_a			,   _a	: Union[str, 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 				__lowercase     (				self   :			Optional[int]						):
									_a	: List[Any]								=				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 				__lowercase     (				self   :			Tuple						):
									pass







							@unittest.skip(reason='Mask2Former does not have a get_input_embeddings method'						)
							def 				__lowercase     (				self   :			Union[str, Any]						):
									pass







							@unittest.skip(reason='Mask2Former is not a generative model'						)
							def 				__lowercase     (				self   :			Tuple						):
									pass







							@unittest.skip(reason='Mask2Former does not use token embeddings'						)
							def 				__lowercase     (				self   :			Tuple						):
									pass







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







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







							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a			,   _a	: List[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()

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

											_a	: Optional[int]								=				['pixel_values']
											self.assertListEqual(arg_names[:1]      ,_UpperCAmelCase						)







							@slow
							def 				__lowercase     (				self   :			List[str]						):
									for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
											_a	: Union[str, Any]								=				MaskaFormerModel.from_pretrained(_UpperCAmelCase						)
											self.assertIsNotNone(_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Dict						):
									_a	: Dict								=				(self.model_tester.min_size,) * 2
									_a	: Union[str, 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(),
									}
									_a	: Dict								=				self.model_tester.get_config()

									_a	: List[str]								=				MaskaFormerForUniversalSegmentation(_UpperCAmelCase						).to(_UpperCAmelCase						)
									_a	: Tuple								=				model(**_UpperCAmelCase						)
									self.assertTrue(outputs.loss is not None						)







							def 				__lowercase     (				self   :			List[Any]						):
									_a			,   _a	: Dict								=				self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.create_and_check_maskaformer_model(_UpperCAmelCase      ,**_UpperCAmelCase      ,output_hidden_states=_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a			,   _a	: str								=				self.model_tester.prepare_config_and_inputs_for_common()

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







							def 				__lowercase     (				self   :			List[Any]						):
									if not self.model_tester.is_training:
											return

									_a	: List[Any]								=				self.all_model_classes[1]
									_a			,   _a			,   _a			,   _a			,   _a	: int								=				self.model_tester.prepare_config_and_inputs()

									_a	: Any								=				model_class(_UpperCAmelCase						)
									model.to(_UpperCAmelCase						)
									model.train()

									_a	: int								=				model(_UpperCAmelCase      ,mask_labels=_UpperCAmelCase      ,class_labels=_UpperCAmelCase						).loss
									loss.backward()







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Optional[int]								=				self.all_model_classes[1]
									_a			,   _a			,   _a			,   _a			,   _a	: Any								=				self.model_tester.prepare_config_and_inputs()
									_a	: Optional[Any]								=				True
									_a	: Tuple								=				True

									_a	: int								=				model_class(_UpperCAmelCase						).to(_UpperCAmelCase						)
									model.train()

									_a	: int								=				model(_UpperCAmelCase      ,mask_labels=_UpperCAmelCase      ,class_labels=_UpperCAmelCase						)

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

									_a	: Tuple								=				outputs.pixel_decoder_hidden_states[0]
									pixel_decoder_hidden_states.retain_grad()

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

									_a	: Optional[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						)
__lowerCAmelCase		     =  1e-4



def 	__lowerCamelCase	( )     -> Any:
		_a	: Union[str, Any]								=				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
		return image

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







							@cached_property
							def 				__lowercase     (				self   :			Union[str, Any]						):
									return "facebook/mask2former-swin-small-coco-instance"







							@cached_property
							def 				__lowercase     (				self   :			List[Any]						):
									return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints						) if is_vision_available() else None







							def 				__lowercase     (				self   :			int						):
									_a	: Tuple								=				MaskaFormerModel.from_pretrained(self.model_checkpoints						).to(_UpperCAmelCase						)
									_a	: Optional[int]								=				self.default_image_processor
									_a	: List[str]								=				prepare_img()
									_a	: int								=				image_processor(_UpperCAmelCase      ,return_tensors='pt'						).to(_UpperCAmelCase						)
									_a	: 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	: List[str]								=				model(**_UpperCAmelCase						)

									_a	: Dict								=				torch.tensor(
									    [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]						).to(_UpperCAmelCase						)
									self.assertTrue(
									    torch.allclose(
									        outputs.encoder_last_hidden_state[0, 0, :3, :3]      ,_UpperCAmelCase      ,atol=_UpperCAmelCase						)						)

									_a	: List[str]								=				torch.tensor(
									    [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]						).to(_UpperCAmelCase						)
									self.assertTrue(
									    torch.allclose(
									        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]      ,_UpperCAmelCase      ,atol=_UpperCAmelCase						)						)

									_a	: Any								=				torch.tensor(
									    [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]						).to(_UpperCAmelCase						)
									self.assertTrue(
									    torch.allclose(
									        outputs.transformer_decoder_last_hidden_state[0, :3, :3]      ,_UpperCAmelCase      ,atol=_UpperCAmelCase						)						)







							def 				__lowercase     (				self   :			List[Any]						):
									_a	: Tuple								=				MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints						).to(_UpperCAmelCase						).eval()
									_a	: List[str]								=				self.default_image_processor
									_a	: Union[str, Any]								=				prepare_img()
									_a	: Optional[Any]								=				image_processor(_UpperCAmelCase      ,return_tensors='pt'						).to(_UpperCAmelCase						)
									_a	: 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	: Any								=				model(**_UpperCAmelCase						)
									# masks_queries_logits
									_a	: List[str]								=				outputs.masks_queries_logits
									self.assertEqual(
									    masks_queries_logits.shape      ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)						)
									_a	: Optional[Any]								=				[
									    [-8.78_39, -9.00_56, -8.81_21],
									    [-7.41_04, -7.03_13, -6.54_01],
									    [-6.61_05, -6.34_27, -6.46_75],
									]
									_a	: List[str]								=				torch.tensor(_UpperCAmelCase						).to(_UpperCAmelCase						)
									self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]      ,_UpperCAmelCase      ,atol=_UpperCAmelCase						)						)
									# class_queries_logits
									_a	: Any								=				outputs.class_queries_logits
									self.assertEqual(class_queries_logits.shape      ,(1, model.config.num_queries, model.config.num_labels + 1)						)
									_a	: Dict								=				torch.tensor(
									    [
									        [1.83_24, -8.08_35, -4.19_22],
									        [0.84_50, -9.00_50, -3.60_53],
									        [0.30_45, -7.72_93, -3.02_75],
									    ]						).to(_UpperCAmelCase						)
									self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]      ,_UpperCAmelCase      ,atol=_UpperCAmelCase						)						)







							def 				__lowercase     (				self   :			Tuple						):
									_a	: str								=				MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints						).to(_UpperCAmelCase						).eval()
									_a	: List[Any]								=				self.default_image_processor

									_a	: Union[str, 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'      ,)

									_a	: int								=				inputs['pixel_values'].to(_UpperCAmelCase						)
									_a	: List[Any]								=				[el.to(_UpperCAmelCase						) for el in inputs['mask_labels']]
									_a	: Any								=				[el.to(_UpperCAmelCase						) for el in inputs['class_labels']]

									with torch.no_grad():
											_a	: Optional[int]								=				model(**_UpperCAmelCase						)

									self.assertTrue(outputs.loss is not None						)




