


import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin







@skip_mps
class 				snake_case__(							UpperCAmelCase__,						UpperCAmelCase__,						unittest.TestCase							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  List[str]					=							IFPipeline
						SCREAMING_SNAKE_CASE__      :  List[str]					=							TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""}
						SCREAMING_SNAKE_CASE__      :  Optional[Any]					=							TEXT_TO_IMAGE_BATCH_PARAMS
						SCREAMING_SNAKE_CASE__      :  int					=							PipelineTesterMixin.required_optional_params - {"""latents"""}




						def 						lowercase_ (				self							)					->    str:
										return self._get_dummy_components()




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase=0							)					->    int:
										if str(__lowercase							).startswith('''mps'''							):
														lowerCAmelCase_ :      Optional[Any]    				=				torch.manual_seed(__lowercase							)
										else:
														lowerCAmelCase_ :      Optional[int]    				=				torch.Generator(device=__lowercase							).manual_seed(__lowercase							)

										lowerCAmelCase_ :      Tuple    				=				{
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''output_type''': '''numpy''',
										}

										return inputs




						def 						lowercase_ (				self							)					->    Dict:
										self._test_save_load_optional_components()




						@unittest.skipIf(torch_device != '''cuda'''   ,						reason='''float16 requires CUDA'''							)
						def 						lowercase_ (				self							)					->    Dict:
										# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
										super().test_save_load_floataa(expected_max_diff=1e-1							)




						def 						lowercase_ (				self							)					->    List[Any]:
										self._test_attention_slicing_forward_pass(expected_max_diff=1e-2							)




						def 						lowercase_ (				self							)					->    List[Any]:
										self._test_save_load_local()




						def 						lowercase_ (				self							)					->    List[str]:
										self._test_inference_batch_single_identical(
										    expected_max_diff=1e-2   ,						)




						@unittest.skipIf(
						    torch_device != '''cuda''' or not is_xformers_available()   ,						reason='''XFormers attention is only available with CUDA and `xformers` installed'''   ,						)
						def 						lowercase_ (				self							)					->    List[Any]:
										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3							)







@slow
@require_torch_gpu
class 				snake_case__(							unittest.TestCase							):







						'''simple docstring'''




						def 						lowercase_ (				self							)					->    Dict:
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




						def 						lowercase_ (				self							)					->    List[Any]:
										# if

										lowerCAmelCase_ :      Optional[Any]    				=				IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0'''   ,						variant='''fp16'''   ,						torch_dtype=torch.floataa							)

										lowerCAmelCase_ :      str    				=				IFSuperResolutionPipeline.from_pretrained(
										    '''DeepFloyd/IF-II-L-v1.0'''   ,						variant='''fp16'''   ,						torch_dtype=torch.floataa   ,						text_encoder=__lowercase   ,						tokenizer=__lowercase							)

										# pre compute text embeddings and remove T5 to save memory

										pipe_a.text_encoder.to('''cuda'''							)

										lowerCAmelCase_				,  lowerCAmelCase_ :      int    				=				pipe_a.encode_prompt('''anime turtle'''   ,						device='''cuda'''							)

										del pipe_a.tokenizer
										del pipe_a.text_encoder
										gc.collect()

										lowerCAmelCase_ :      Tuple    				=				None
										lowerCAmelCase_ :      Dict    				=				None

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if(__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# img2img

										lowerCAmelCase_ :      Optional[Any]    				=				IFImgaImgPipeline(**pipe_a.components							)
										lowerCAmelCase_ :      Tuple    				=				IFImgaImgSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_imgaimg(__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# inpainting

										lowerCAmelCase_ :      List[Any]    				=				IFInpaintingPipeline(**pipe_a.components							)
										lowerCAmelCase_ :      Any    				=				IFInpaintingSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_inpainting(__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)					->    List[Any]:
										# pipeline 1

										_start_torch_memory_measurement()

										lowerCAmelCase_ :      List[Any]    				=				torch.Generator(device='''cpu'''							).manual_seed(0							)
										lowerCAmelCase_ :      List[str]    				=				pipe_a(
										    prompt_embeds=__lowercase   ,						negative_prompt_embeds=__lowercase   ,						num_inference_steps=2   ,						generator=__lowercase   ,						output_type='''np'''   ,						)

										lowerCAmelCase_ :      Tuple    				=				output.images[0]

										assert image.shape == (6_4, 6_4, 3)

										lowerCAmelCase_ :      Dict    				=				torch.cuda.max_memory_allocated()
										assert mem_bytes < 1_3 * 1_0**9

										lowerCAmelCase_ :      str    				=				load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy'''							)
										assert_mean_pixel_difference(__lowercase   ,						__lowercase							)

										# pipeline 2

										_start_torch_memory_measurement()

										lowerCAmelCase_ :      Any    				=				torch.Generator(device='''cpu'''							).manual_seed(0							)

										lowerCAmelCase_ :      Dict    				=				floats_tensor((1, 3, 6_4, 6_4)   ,						rng=random.Random(0							)							).to(__lowercase							)

										lowerCAmelCase_ :      str    				=				pipe_a(
										    prompt_embeds=__lowercase   ,						negative_prompt_embeds=__lowercase   ,						image=__lowercase   ,						generator=__lowercase   ,						num_inference_steps=2   ,						output_type='''np'''   ,						)

										lowerCAmelCase_ :      Optional[int]    				=				output.images[0]

										assert image.shape == (2_5_6, 2_5_6, 3)

										lowerCAmelCase_ :      Tuple    				=				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 1_0**9

										lowerCAmelCase_ :      List[str]    				=				load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy'''							)
										assert_mean_pixel_difference(__lowercase   ,						__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)					->    List[str]:
										# pipeline 1

										_start_torch_memory_measurement()

										lowerCAmelCase_ :      str    				=				floats_tensor((1, 3, 6_4, 6_4)   ,						rng=random.Random(0							)							).to(__lowercase							)

										lowerCAmelCase_ :      Optional[Any]    				=				torch.Generator(device='''cpu'''							).manual_seed(0							)

										lowerCAmelCase_ :      List[Any]    				=				pipe_a(
										    prompt_embeds=__lowercase   ,						negative_prompt_embeds=__lowercase   ,						image=__lowercase   ,						num_inference_steps=2   ,						generator=__lowercase   ,						output_type='''np'''   ,						)

										lowerCAmelCase_ :      Union[str, Any]    				=				output.images[0]

										assert image.shape == (6_4, 6_4, 3)

										lowerCAmelCase_ :      List[str]    				=				torch.cuda.max_memory_allocated()
										assert mem_bytes < 1_0 * 1_0**9

										lowerCAmelCase_ :      Optional[int]    				=				load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy'''							)
										assert_mean_pixel_difference(__lowercase   ,						__lowercase							)

										# pipeline 2

										_start_torch_memory_measurement()

										lowerCAmelCase_ :      int    				=				torch.Generator(device='''cpu'''							).manual_seed(0							)

										lowerCAmelCase_ :      Union[str, Any]    				=				floats_tensor((1, 3, 2_5_6, 2_5_6)   ,						rng=random.Random(0							)							).to(__lowercase							)
										lowerCAmelCase_ :      Union[str, Any]    				=				floats_tensor((1, 3, 6_4, 6_4)   ,						rng=random.Random(0							)							).to(__lowercase							)

										lowerCAmelCase_ :      List[str]    				=				pipe_a(
										    prompt_embeds=__lowercase   ,						negative_prompt_embeds=__lowercase   ,						image=__lowercase   ,						original_image=__lowercase   ,						generator=__lowercase   ,						num_inference_steps=2   ,						output_type='''np'''   ,						)

										lowerCAmelCase_ :      Any    				=				output.images[0]

										assert image.shape == (2_5_6, 2_5_6, 3)

										lowerCAmelCase_ :      List[Any]    				=				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 1_0**9

										lowerCAmelCase_ :      Optional[Any]    				=				load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy'''							)
										assert_mean_pixel_difference(__lowercase   ,						__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)					->    Union[str, Any]:
										# pipeline 1

										_start_torch_memory_measurement()

										lowerCAmelCase_ :      str    				=				floats_tensor((1, 3, 6_4, 6_4)   ,						rng=random.Random(0							)							).to(__lowercase							)
										lowerCAmelCase_ :      List[Any]    				=				floats_tensor((1, 3, 6_4, 6_4)   ,						rng=random.Random(1							)							).to(__lowercase							)

										lowerCAmelCase_ :      Optional[int]    				=				torch.Generator(device='''cpu'''							).manual_seed(0							)
										lowerCAmelCase_ :      Dict    				=				pipe_a(
										    prompt_embeds=__lowercase   ,						negative_prompt_embeds=__lowercase   ,						image=__lowercase   ,						mask_image=__lowercase   ,						num_inference_steps=2   ,						generator=__lowercase   ,						output_type='''np'''   ,						)

										lowerCAmelCase_ :      Dict    				=				output.images[0]

										assert image.shape == (6_4, 6_4, 3)

										lowerCAmelCase_ :      Optional[int]    				=				torch.cuda.max_memory_allocated()
										assert mem_bytes < 1_0 * 1_0**9

										lowerCAmelCase_ :      int    				=				load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy'''							)
										assert_mean_pixel_difference(__lowercase   ,						__lowercase							)

										# pipeline 2

										_start_torch_memory_measurement()

										lowerCAmelCase_ :      Union[str, Any]    				=				torch.Generator(device='''cpu'''							).manual_seed(0							)

										lowerCAmelCase_ :      List[Any]    				=				floats_tensor((1, 3, 6_4, 6_4)   ,						rng=random.Random(0							)							).to(__lowercase							)
										lowerCAmelCase_ :      Any    				=				floats_tensor((1, 3, 2_5_6, 2_5_6)   ,						rng=random.Random(0							)							).to(__lowercase							)
										lowerCAmelCase_ :      List[str]    				=				floats_tensor((1, 3, 2_5_6, 2_5_6)   ,						rng=random.Random(1							)							).to(__lowercase							)

										lowerCAmelCase_ :      Union[str, Any]    				=				pipe_a(
										    prompt_embeds=__lowercase   ,						negative_prompt_embeds=__lowercase   ,						image=__lowercase   ,						mask_image=__lowercase   ,						original_image=__lowercase   ,						generator=__lowercase   ,						num_inference_steps=2   ,						output_type='''np'''   ,						)

										lowerCAmelCase_ :      Dict    				=				output.images[0]

										assert image.shape == (2_5_6, 2_5_6, 3)

										lowerCAmelCase_ :      Optional[Any]    				=				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 1_0**9

										lowerCAmelCase_ :      Dict    				=				load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy'''							)
										assert_mean_pixel_difference(__lowercase   ,						__lowercase							)






def 			lowerCAmelCase (		)-> Dict:
				torch.cuda.empty_cache()
				torch.cuda.reset_max_memory_allocated()
				torch.cuda.reset_peak_memory_stats()



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 				snake_case__:







						'''simple docstring'''




						def __init__(				self   ,						__lowercase   ,						__lowercase=2   ,						__lowercase=True   ,						__lowercase=False   ,						__lowercase=1_0   ,						__lowercase=3   ,						__lowercase=3_2 * 4   ,						__lowercase=3_2 * 6   ,						__lowercase=4   ,						__lowercase=3_2   ,						)					->    Union[str, Any]:
										lowerCAmelCase_ :      str    				=				parent
										lowerCAmelCase_ :      Optional[Any]    				=				batch_size
										lowerCAmelCase_ :      List[Any]    				=				is_training
										lowerCAmelCase_ :      Optional[Any]    				=				use_auxiliary_loss
										lowerCAmelCase_ :      List[Any]    				=				num_queries
										lowerCAmelCase_ :      str    				=				num_channels
										lowerCAmelCase_ :      Dict    				=				min_size
										lowerCAmelCase_ :      List[str]    				=				max_size
										lowerCAmelCase_ :      Any    				=				num_labels
										lowerCAmelCase_ :      str    				=				mask_feature_size




						def 						lowercase_ (				self							)					->    List[Any]:
										lowerCAmelCase_ :      Optional[Any]    				=				floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]							).to(
										    __lowercase							)

										lowerCAmelCase_ :      Optional[Any]    				=				torch.ones([self.batch_size, self.min_size, self.max_size]   ,						device=__lowercase							)

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

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




						def 						lowercase_ (				self							)					->    List[str]:
										return MaskFormerConfig.from_backbone_and_decoder_configs(
										    backbone_config=SwinConfig(
										        depths=[1, 1, 1, 1]   ,						)   ,						decoder_config=DetrConfig(
										        decoder_ffn_dim=1_2_8   ,						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 						lowercase_ (				self							)					->    Union[str, Any]:
										lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_ :      int    				=				self.prepare_config_and_inputs()
										lowerCAmelCase_ :      Union[str, Any]    				=				{'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
										return config, inputs_dict




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase							)					->    Any:
										lowerCAmelCase_ :      Optional[int]    				=				output.encoder_hidden_states
										lowerCAmelCase_ :      List[Any]    				=				output.pixel_decoder_hidden_states
										lowerCAmelCase_ :      Optional[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_config.decoder_layers							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase=False							)					->    int:
										with torch.no_grad():
														lowerCAmelCase_ :      List[Any]    				=				MaskFormerModel(config=__lowercase							)
														model.to(__lowercase							)
														model.eval()

														lowerCAmelCase_ :      Optional[Any]    				=				model(pixel_values=__lowercase   ,						pixel_mask=__lowercase							)
														lowerCAmelCase_ :      Optional[int]    				=				model(__lowercase   ,						output_hidden_states=__lowercase							)
										# 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(__lowercase   ,						__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase							)					->    Any:
										lowerCAmelCase_ :      Any    				=				MaskFormerForInstanceSegmentation(config=__lowercase							)
										model.to(__lowercase							)
										model.eval()

										def comm_check_on_output(__lowercase							):
														# 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():
														lowerCAmelCase_ :      int    				=				model(pixel_values=__lowercase   ,						pixel_mask=__lowercase							)
														lowerCAmelCase_ :      Any    				=				model(__lowercase							)

														comm_check_on_output(__lowercase							)

														lowerCAmelCase_ :      List[Any]    				=				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 				snake_case__(							UpperCAmelCase__,						UpperCAmelCase__,						unittest.TestCase							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  List[str]					=							(MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
						SCREAMING_SNAKE_CASE__      :  Tuple					=							(
						    {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation}
						    if is_torch_available()
						    else {}
						)

						SCREAMING_SNAKE_CASE__      :  Tuple					=							False
						SCREAMING_SNAKE_CASE__      :  Dict					=							False
						SCREAMING_SNAKE_CASE__      :  Tuple					=							False
						SCREAMING_SNAKE_CASE__      :  List[str]					=							False




						def 						lowercase_ (				self							)					->    List[Any]:
										lowerCAmelCase_ :      Any    				=				MaskFormerModelTester(self							)
										lowerCAmelCase_ :      str    				=				ConfigTester(self   ,						config_class=__lowercase   ,						has_text_modality=__lowercase							)




						def 						lowercase_ (				self							)					->    Any:
										self.config_tester.run_common_tests()




						def 						lowercase_ (				self							)					->    List[str]:
										lowerCAmelCase_				,  lowerCAmelCase_ :      Any    				=				self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.create_and_check_maskformer_model(__lowercase   ,						**__lowercase   ,						output_hidden_states=__lowercase							)




						def 						lowercase_ (				self							)					->    Optional[Any]:
										lowerCAmelCase_ :      Optional[Any]    				=				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__lowercase							)




						@unittest.skip(reason='''MaskFormer does not use inputs_embeds'''							)
						def 						lowercase_ (				self							)					->    str:
										pass




						@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method'''							)
						def 						lowercase_ (				self							)					->    Optional[Any]:
										pass




						@unittest.skip(reason='''MaskFormer is not a generative model'''							)
						def 						lowercase_ (				self							)					->    Optional[Any]:
										pass




						@unittest.skip(reason='''MaskFormer does not use token embeddings'''							)
						def 						lowercase_ (				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 						lowercase_ (				self							)					->    Optional[Any]:
										pass




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




						def 						lowercase_ (				self							)					->    List[str]:
										lowerCAmelCase_				,  lowerCAmelCase_ :      str    				=				self.model_tester.prepare_config_and_inputs_for_common()

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

														lowerCAmelCase_ :      Tuple    				=				['''pixel_values''']
														self.assertListEqual(arg_names[:1]   ,						__lowercase							)




						@slow
						def 						lowercase_ (				self							)					->    Optional[int]:
										for model_name in ["facebook/maskformer-swin-small-coco"]:
														lowerCAmelCase_ :      str    				=				MaskFormerModel.from_pretrained(__lowercase							)
														self.assertIsNotNone(__lowercase							)




						def 						lowercase_ (				self							)					->    List[Any]:
										lowerCAmelCase_ :      Tuple    				=				(self.model_tester.min_size,) * 2
										lowerCAmelCase_ :      List[Any]    				=				{
										    '''pixel_values''': torch.randn((2, 3, *size)   ,						device=__lowercase							),
										    '''mask_labels''': torch.randn((2, 1_0, *size)   ,						device=__lowercase							),
										    '''class_labels''': torch.zeros(2   ,						1_0   ,						device=__lowercase							).long(),
										}

										lowerCAmelCase_ :      Tuple    				=				MaskFormerForInstanceSegmentation(MaskFormerConfig()							).to(__lowercase							)
										lowerCAmelCase_ :      Dict    				=				model(**__lowercase							)
										self.assertTrue(outputs.loss is not None							)




						def 						lowercase_ (				self							)					->    Dict:
										lowerCAmelCase_				,  lowerCAmelCase_ :      List[Any]    				=				self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.create_and_check_maskformer_model(__lowercase   ,						**__lowercase   ,						output_hidden_states=__lowercase							)




						def 						lowercase_ (				self							)					->    int:
										lowerCAmelCase_				,  lowerCAmelCase_ :      Tuple    				=				self.model_tester.prepare_config_and_inputs_for_common()

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




						def 						lowercase_ (				self							)					->    List[str]:
										if not self.model_tester.is_training:
														return
										# only MaskFormerForInstanceSegmentation has the loss
										lowerCAmelCase_ :      int    				=				self.all_model_classes[1]
										lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_ :      str    				=				self.model_tester.prepare_config_and_inputs()

										lowerCAmelCase_ :      Optional[Any]    				=				model_class(__lowercase							)
										model.to(__lowercase							)
										model.train()

										lowerCAmelCase_ :      Optional[Any]    				=				model(__lowercase   ,						mask_labels=__lowercase   ,						class_labels=__lowercase							).loss
										loss.backward()




						def 						lowercase_ (				self							)					->    Optional[int]:
										# only MaskFormerForInstanceSegmentation has the loss
										lowerCAmelCase_ :      Any    				=				self.all_model_classes[1]
										lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_ :      List[str]    				=				self.model_tester.prepare_config_and_inputs()
										lowerCAmelCase_ :      Tuple    				=				True
										lowerCAmelCase_ :      Tuple    				=				True

										lowerCAmelCase_ :      Any    				=				model_class(__lowercase							)
										model.to(__lowercase							)
										model.train()

										lowerCAmelCase_ :      Any    				=				model(__lowercase   ,						mask_labels=__lowercase   ,						class_labels=__lowercase							)

										lowerCAmelCase_ :      Union[str, Any]    				=				outputs.encoder_hidden_states[0]
										encoder_hidden_states.retain_grad()

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

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






_UpperCAmelCase			:  Dict     =1E-4



def 			lowerCAmelCase (		)-> Any:
				lowerCAmelCase_ :      Optional[int]    				=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
				return image







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







						'''simple docstring'''




						@cached_property
						def 						lowercase_ (				self							)					->    Union[str, Any]:
										return (
										    MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco'''							)
										    if is_vision_available()
										    else None
										)




						def 						lowercase_ (				self							)					->    Any:
										lowerCAmelCase_ :      Optional[Any]    				=				MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco'''							).to(__lowercase							)
										lowerCAmelCase_ :      Dict    				=				self.default_image_processor
										lowerCAmelCase_ :      int    				=				prepare_img()
										lowerCAmelCase_ :      Any    				=				image_processor(__lowercase   ,						return_tensors='''pt'''							).to(__lowercase							)
										lowerCAmelCase_ :      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(__lowercase   ,						(1, 3, 8_0_0, 1_0_8_8)							)

										with torch.no_grad():
														lowerCAmelCase_ :      List[str]    				=				model(**__lowercase							)

										lowerCAmelCase_ :      Union[str, Any]    				=				torch.tensor(
										    [[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]]							).to(__lowercase							)
										self.assertTrue(
										    torch.allclose(
										        outputs.encoder_last_hidden_state[0, 0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)

										lowerCAmelCase_ :      List[Any]    				=				torch.tensor(
										    [[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]]							).to(__lowercase							)
										self.assertTrue(
										    torch.allclose(
										        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)

										lowerCAmelCase_ :      int    				=				torch.tensor(
										    [[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]]							).to(__lowercase							)
										self.assertTrue(
										    torch.allclose(
										        outputs.transformer_decoder_last_hidden_state[0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)




						def 						lowercase_ (				self							)					->    Dict:
										lowerCAmelCase_ :      Optional[Any]    				=				(
										    MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''							)
										    .to(__lowercase							)
										    .eval()
										)
										lowerCAmelCase_ :      Tuple    				=				self.default_image_processor
										lowerCAmelCase_ :      Optional[Any]    				=				prepare_img()
										lowerCAmelCase_ :      int    				=				image_processor(__lowercase   ,						return_tensors='''pt'''							).to(__lowercase							)
										lowerCAmelCase_ :      Tuple    				=				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(__lowercase   ,						(1, 3, 8_0_0, 1_0_8_8)							)

										with torch.no_grad():
														lowerCAmelCase_ :      Dict    				=				model(**__lowercase							)
										# masks_queries_logits
										lowerCAmelCase_ :      Optional[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)   ,						)
										lowerCAmelCase_ :      Tuple    				=				[
										    [-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33],
										    [-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95],
										    [-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42],
										]
										lowerCAmelCase_ :      int    				=				torch.tensor(__lowercase							).to(__lowercase							)
										self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)
										# class_queries_logits
										lowerCAmelCase_ :      List[Any]    				=				outputs.class_queries_logits
										self.assertEqual(
										    class_queries_logits.shape   ,						(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)							)
										lowerCAmelCase_ :      Dict    				=				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(__lowercase							)
										self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)




						def 						lowercase_ (				self							)					->    Optional[Any]:
										lowerCAmelCase_ :      str    				=				(
										    MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff'''							)
										    .to(__lowercase							)
										    .eval()
										)
										lowerCAmelCase_ :      int    				=				self.default_image_processor
										lowerCAmelCase_ :      Optional[Any]    				=				prepare_img()
										lowerCAmelCase_ :      Dict    				=				image_processor(__lowercase   ,						return_tensors='''pt'''							).to(__lowercase							)
										lowerCAmelCase_ :      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(__lowercase   ,						(1, 3, 8_0_0, 1_0_8_8)							)

										with torch.no_grad():
														lowerCAmelCase_ :      str    				=				model(**__lowercase							)
										# masks_queries_logits
										lowerCAmelCase_ :      List[str]    				=				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)   ,						)
										lowerCAmelCase_ :      Any    				=				[[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]]
										lowerCAmelCase_ :      str    				=				torch.tensor(__lowercase							).to(__lowercase							)
										self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)
										# class_queries_logits
										lowerCAmelCase_ :      Optional[int]    				=				outputs.class_queries_logits
										self.assertEqual(
										    class_queries_logits.shape   ,						(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)							)
										lowerCAmelCase_ :      int    				=				torch.tensor(
										    [[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]]							).to(__lowercase							)
										self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]   ,						__lowercase   ,						atol=__lowercase							)							)




						def 						lowercase_ (				self							)					->    Optional[Any]:
										lowerCAmelCase_ :      Dict    				=				(
										    MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''							)
										    .to(__lowercase							)
										    .eval()
										)
										lowerCAmelCase_ :      str    				=				self.default_image_processor

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

										lowerCAmelCase_ :      Optional[Any]    				=				inputs['''pixel_values'''].to(__lowercase							)
										lowerCAmelCase_ :      int    				=				[el.to(__lowercase							) for el in inputs['''mask_labels''']]
										lowerCAmelCase_ :      Optional[Any]    				=				[el.to(__lowercase							) for el in inputs['''class_labels''']]

										with torch.no_grad():
														lowerCAmelCase_ :      str    				=				model(**__lowercase							)

										self.assertTrue(outputs.loss is not None							)