


import argparse

import torch

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt


if __name__ == "__main__":
						_UpperCAmelCase			:  str     =argparse.ArgumentParser()

						parser.add_argument(
						    """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert."""
						)
						# !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
						parser.add_argument(
						    """--original_config_file""",
						    default=None,
						    type=str,
						    help="""The YAML config file corresponding to the original architecture.""",
						)
						parser.add_argument(
						    """--num_in_channels""",
						    default=None,
						    type=int,
						    help="""The number of input channels. If `None` number of input channels will be automatically inferred.""",
						)
						parser.add_argument(
						    """--scheduler_type""",
						    default="""pndm""",
						    type=str,
						    help="""Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']""",
						)
						parser.add_argument(
						    """--pipeline_type""",
						    default=None,
						    type=str,
						    help=(
						        """The pipeline type. One of 'FrozenOpenCLIPEmbedder', 'FrozenCLIPEmbedder', 'PaintByExample'"""
						        """. If `None` pipeline will be automatically inferred."""
						    ),
						)
						parser.add_argument(
						    """--image_size""",
						    default=None,
						    type=int,
						    help=(
						        """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2"""
						        """ Base. Use 768 for Stable Diffusion v2."""
						    ),
						)
						parser.add_argument(
						    """--prediction_type""",
						    default=None,
						    type=str,
						    help=(
						        """The prediction type that the model was trained on. Use 'epsilon' for Stable Diffusion v1.X and Stable"""
						        """ Diffusion v2 Base. Use 'v_prediction' for Stable Diffusion v2."""
						    ),
						)
						parser.add_argument(
						    """--extract_ema""",
						    action="""store_true""",
						    help=(
						        """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"""
						        """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"""
						        """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."""
						    ),
						)
						parser.add_argument(
						    """--upcast_attention""",
						    action="""store_true""",
						    help=(
						        """Whether the attention computation should always be upcasted. This is necessary when running stable"""
						        """ diffusion 2.1."""
						    ),
						)
						parser.add_argument(
						    """--from_safetensors""",
						    action="""store_true""",
						    help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""",
						)
						parser.add_argument(
						    """--to_safetensors""",
						    action="""store_true""",
						    help="""Whether to store pipeline in safetensors format or not.""",
						)
						parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""")
						parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""")
						parser.add_argument(
						    """--stable_unclip""",
						    type=str,
						    default=None,
						    required=False,
						    help="""Set if this is a stable unCLIP model. One of 'txt2img' or 'img2img'.""",
						)
						parser.add_argument(
						    """--stable_unclip_prior""",
						    type=str,
						    default=None,
						    required=False,
						    help="""Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.""",
						)
						parser.add_argument(
						    """--clip_stats_path""",
						    type=str,
						    help="""Path to the clip stats file. Only required if the stable unclip model's config specifies `model.params.noise_aug_config.params.clip_stats_path`.""",
						    required=False,
						)
						parser.add_argument(
						    """--controlnet""", action="""store_true""", default=None, help="""Set flag if this is a controlnet checkpoint."""
						)
						parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
						parser.add_argument(
						    """--vae_path""",
						    type=str,
						    default=None,
						    required=False,
						    help="""Set to a path, hub id to an already converted vae to not convert it again.""",
						)
						_UpperCAmelCase			:  int     =parser.parse_args()

						_UpperCAmelCase			:  Tuple     =download_from_original_stable_diffusion_ckpt(
						    checkpoint_path=args.checkpoint_path,
						    original_config_file=args.original_config_file,
						    image_size=args.image_size,
						    prediction_type=args.prediction_type,
						    model_type=args.pipeline_type,
						    extract_ema=args.extract_ema,
						    scheduler_type=args.scheduler_type,
						    num_in_channels=args.num_in_channels,
						    upcast_attention=args.upcast_attention,
						    from_safetensors=args.from_safetensors,
						    device=args.device,
						    stable_unclip=args.stable_unclip,
						    stable_unclip_prior=args.stable_unclip_prior,
						    clip_stats_path=args.clip_stats_path,
						    controlnet=args.controlnet,
						    vae_path=args.vae_path,
						)

						if args.half:
												pipe.to(torch_dtype=torch.floataa)

						if args.controlnet:
												# only save the controlnet model
												pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
						else:
												pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)



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							)