
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import MobileViTImageProcessor





class  snake_case     (							unittest.TestCase   ):

							def __init__(self       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_=7       ,       SCREAMING_SNAKE_CASE_=3       ,       SCREAMING_SNAKE_CASE_=18       ,       SCREAMING_SNAKE_CASE_=30       ,       SCREAMING_SNAKE_CASE_=4_00       ,       SCREAMING_SNAKE_CASE_=True       ,       SCREAMING_SNAKE_CASE_=None       ,       SCREAMING_SNAKE_CASE_=True       ,       SCREAMING_SNAKE_CASE_=None       ,       SCREAMING_SNAKE_CASE_=True       ,       ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = size if size is not None else {"shortest_edge": 20}
									SCREAMING_SNAKE_CASE_						 = crop_size if crop_size is not None else {"height": 18, "width": 18}
									SCREAMING_SNAKE_CASE_						 = parent
									SCREAMING_SNAKE_CASE_						 = batch_size
									SCREAMING_SNAKE_CASE_						 = num_channels
									SCREAMING_SNAKE_CASE_						 = image_size
									SCREAMING_SNAKE_CASE_						 = min_resolution
									SCREAMING_SNAKE_CASE_						 = max_resolution
									SCREAMING_SNAKE_CASE_						 = do_resize
									SCREAMING_SNAKE_CASE_						 = size
									SCREAMING_SNAKE_CASE_						 = do_center_crop
									SCREAMING_SNAKE_CASE_						 = crop_size
									SCREAMING_SNAKE_CASE_						 = do_flip_channel_order







							def _lowercase					(self    ):

									"""simple docstring"""







									return {
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "do_center_crop": self.do_center_crop,
									    "crop_size": self.crop_size,
									    "do_flip_channel_order": self.do_flip_channel_order,
									}







@require_torch
@require_vision
class  snake_case     (							UpperCamelCase_       ,			unittest.TestCase   ):
							UpperCAmelCase__						     =      MobileViTImageProcessor if is_vision_available() else None

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = MobileViTImageProcessingTester(self    )

							@property
							def _lowercase					(self    ):

									"""simple docstring"""







									return self.image_processor_tester.prepare_image_processor_dict()

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									self.assertTrue(hasattr(__A       ,       '''do_resize'''    )    )
									self.assertTrue(hasattr(__A       ,       '''size'''    )    )
									self.assertTrue(hasattr(__A       ,       '''do_center_crop'''    )    )
									self.assertTrue(hasattr(__A       ,       '''center_crop'''    )    )
									self.assertTrue(hasattr(__A       ,       '''do_flip_channel_order'''    )    )

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class.from_dict(self.image_processor_dict    )
									self.assertEqual(image_processor.size       ,       {'''shortest_edge''': 20}    )
									self.assertEqual(image_processor.crop_size       ,       {'''height''': 18, '''width''': 18}    )

									SCREAMING_SNAKE_CASE_						 = self.image_processing_class.from_dict(self.image_processor_dict       ,       size=42       ,       crop_size=84    )
									self.assertEqual(image_processor.size       ,       {'''shortest_edge''': 42}    )
									self.assertEqual(image_processor.crop_size       ,       {'''height''': 84, '''width''': 84}    )

							def _lowercase					(self    ):

									"""simple docstring"""







									pass

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									# create random PIL images
									SCREAMING_SNAKE_CASE_						 = prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=__A    )
									for image in image_inputs:
											self.assertIsInstance(__A       ,       Image.Image    )

									# Test not batched input
									SCREAMING_SNAKE_CASE_						 = image_processing(image_inputs[0]       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

									# Test batched
									SCREAMING_SNAKE_CASE_						 = image_processing(__A       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									# create random numpy tensors
									SCREAMING_SNAKE_CASE_						 = prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=__A       ,       numpify=__A    )
									for image in image_inputs:
											self.assertIsInstance(__A       ,       np.ndarray    )

									# Test not batched input
									SCREAMING_SNAKE_CASE_						 = image_processing(image_inputs[0]       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

									# Test batched
									SCREAMING_SNAKE_CASE_						 = image_processing(__A       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )







							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									# create random PyTorch tensors
									SCREAMING_SNAKE_CASE_						 = prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=__A       ,       torchify=__A    )
									for image in image_inputs:
											self.assertIsInstance(__A       ,       torch.Tensor    )

									# Test not batched input
									SCREAMING_SNAKE_CASE_						 = image_processing(image_inputs[0]       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

									# Test batched
									SCREAMING_SNAKE_CASE_						 = image_processing(__A       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

"""simple docstring"""




import copy
from typing import Dict, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
from ..detr import DetrConfig
from ..swin import SwinConfig


lowerCAmelCase__							=				{
    'facebook/maskformer-swin-base-ade': (
        'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json'
    )
    # See all MaskFormer models at https://huggingface.co/models?filter=maskformer
}

lowerCAmelCase__							=				logging.get_logger(__name__)





class  snake_case     (							__lowercase   ):
							UpperCAmelCase__						     =      '''maskformer'''
							UpperCAmelCase__						     =      {'''hidden_size''': '''mask_feature_size'''}
							UpperCAmelCase__						     =      ['''resnet''', '''swin''']
							UpperCAmelCase__						     =      ['''detr''']

							def __init__(self       ,       SCREAMING_SNAKE_CASE_ = 2_56       ,       SCREAMING_SNAKE_CASE_ = 2_56       ,       SCREAMING_SNAKE_CASE_ = 0.1       ,       SCREAMING_SNAKE_CASE_ = False       ,       SCREAMING_SNAKE_CASE_ = None       ,       SCREAMING_SNAKE_CASE_ = None       ,       SCREAMING_SNAKE_CASE_ = 0.02       ,       SCREAMING_SNAKE_CASE_ = 1.0       ,       SCREAMING_SNAKE_CASE_ = 1.0       ,       SCREAMING_SNAKE_CASE_ = 1.0       ,       SCREAMING_SNAKE_CASE_ = 20.0       ,       SCREAMING_SNAKE_CASE_ = None       ,       **SCREAMING_SNAKE_CASE_       ,       ):

									"""simple docstring"""







									if backbone_config is None:
											# fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k
											SCREAMING_SNAKE_CASE_						 = SwinConfig(
											    image_size=3_84       ,       in_channels=3       ,       patch_size=4       ,       embed_dim=1_28       ,       depths=[2, 2, 18, 2]       ,       num_heads=[4, 8, 16, 32]       ,       window_size=12       ,       drop_path_rate=0.3       ,       out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4''']       ,       )

									if isinstance(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ):
											SCREAMING_SNAKE_CASE_						 = backbone_config.pop('''model_type'''    )
											SCREAMING_SNAKE_CASE_						 = CONFIG_MAPPING[backbone_model_type]
											SCREAMING_SNAKE_CASE_						 = config_class.from_dict(SCREAMING_SNAKE_CASE_    )

									# verify that the backbone is supported
									if backbone_config.model_type not in self.backbones_supported:
											logger.warning_once(
											    f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. '
											    f'Supported model types: {",".join(self.backbones_supported    )}'    )

									if decoder_config is None:
											# fall back to https://huggingface.co/facebook/detr-resnet-50
											SCREAMING_SNAKE_CASE_						 = DetrConfig()
									else:
											# verify that the decoder is supported
											SCREAMING_SNAKE_CASE_						 = (
											    decoder_config.pop('''model_type'''    ) if isinstance(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ) else decoder_config.model_type
											)
											if decoder_type not in self.decoders_supported:
													raise ValueError(
													    f'Transformer Decoder {decoder_type} not supported, please use one of'
													    f' {",".join(self.decoders_supported    )}'    )
											if isinstance(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ):
													SCREAMING_SNAKE_CASE_						 = CONFIG_MAPPING[decoder_type]
													SCREAMING_SNAKE_CASE_						 = config_class.from_dict(SCREAMING_SNAKE_CASE_    )

									SCREAMING_SNAKE_CASE_						 = backbone_config
									SCREAMING_SNAKE_CASE_						 = decoder_config
									# main feature dimension for the model
									SCREAMING_SNAKE_CASE_						 = fpn_feature_size
									SCREAMING_SNAKE_CASE_						 = mask_feature_size
									# initializer
									SCREAMING_SNAKE_CASE_						 = init_std
									SCREAMING_SNAKE_CASE_						 = init_xavier_std
									# Hungarian matcher && loss
									SCREAMING_SNAKE_CASE_						 = cross_entropy_weight
									SCREAMING_SNAKE_CASE_						 = dice_weight
									SCREAMING_SNAKE_CASE_						 = mask_weight
									SCREAMING_SNAKE_CASE_						 = use_auxiliary_loss
									SCREAMING_SNAKE_CASE_						 = no_object_weight
									SCREAMING_SNAKE_CASE_						 = output_auxiliary_logits

									SCREAMING_SNAKE_CASE_						 = self.decoder_config.encoder_attention_heads
									SCREAMING_SNAKE_CASE_						 = self.decoder_config.num_hidden_layers
									super().__init__(**SCREAMING_SNAKE_CASE_    )

							@classmethod
							def _lowercase					(cls       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       **SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									return cls(
									    backbone_config=SCREAMING_SNAKE_CASE_       ,       decoder_config=SCREAMING_SNAKE_CASE_       ,       **SCREAMING_SNAKE_CASE_       ,       )







							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = copy.deepcopy(self.__dict__    )
									SCREAMING_SNAKE_CASE_						 = self.backbone_config.to_dict()
									SCREAMING_SNAKE_CASE_						 = self.decoder_config.to_dict()
									SCREAMING_SNAKE_CASE_						 = self.__class__.model_type
									return output