






'''simple docstring'''







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




							def __init__(							self:				List[Any]			,							UpperCamelCase__:				Union[str, Any]			,							UpperCamelCase__:				Dict=2			,							UpperCamelCase__:				Optional[int]=True			,							UpperCamelCase__:				Any=False			,							UpperCamelCase__:				Dict=10			,							UpperCamelCase__:				List[str]=3			,							UpperCamelCase__:				int=32 * 4			,							UpperCamelCase__:				List[str]=32 * 6			,							UpperCamelCase__:				Optional[int]=4			,							UpperCamelCase__:				int=32			,							):
														lowerCamelCase__					:	List[str]         =       parent
														lowerCamelCase__					:	List[Any]         =       batch_size
														lowerCamelCase__					:	Union[str, Any]         =       is_training
														lowerCamelCase__					:	List[Any]         =       use_auxiliary_loss
														lowerCamelCase__					:	List[Any]         =       num_queries
														lowerCamelCase__					:	List[str]         =       num_channels
														lowerCamelCase__					:	Optional[Any]         =       min_size
														lowerCamelCase__					:	List[Any]         =       max_size
														lowerCamelCase__					:	int         =       num_labels
														lowerCamelCase__					:	Optional[int]         =       mask_feature_size




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	Any         =       floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]     ).to(
														    UpperCamelCase__     )

														lowerCamelCase__					:	Optional[int]         =       torch.ones([self.batch_size, self.min_size, self.max_size]			,							device=UpperCamelCase__     )

														lowerCamelCase__					:	Union[str, Any]         =       (
														    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]			,							device=UpperCamelCase__     ) > 0.5
														).float()
														lowerCamelCase__					:	Tuple         =       (torch.rand((self.batch_size, self.num_labels)			,							device=UpperCamelCase__     ) > 0.5).long()

														lowerCamelCase__					:	Tuple         =       self.get_config()
														return config, pixel_values, pixel_mask, mask_labels, class_labels




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														return MaskFormerConfig.from_backbone_and_decoder_configs(
														    backbone_config=SwinConfig(
														        depths=[1, 1, 1, 1]			,							)			,							decoder_config=DetrConfig(
														        decoder_ffn_dim=128			,							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 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	Optional[int]         =       self.prepare_config_and_inputs()
														lowerCamelCase__					:	Tuple         =       {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
														return config, inputs_dict




							def 		lowerCamelCase_				(							self:				Dict			,							UpperCamelCase__:				Union[str, Any]			,							UpperCamelCase__:				Union[str, Any]     ):
														lowerCamelCase__					:	Optional[Any]         =       output.encoder_hidden_states
														lowerCamelCase__					:	List[Any]         =       output.pixel_decoder_hidden_states
														lowerCamelCase__					:	str         =       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_config.decoder_layers     )




							def 		lowerCamelCase_				(							self:				Any			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				Optional[int]			,							UpperCamelCase__:				Optional[int]=False     ):
														with torch.no_grad():
																					lowerCamelCase__					:	Optional[int]         =       MaskFormerModel(config=UpperCamelCase__     )
																					model.to(UpperCamelCase__     )
																					model.eval()

																					lowerCamelCase__					:	Dict         =       model(pixel_values=UpperCamelCase__			,							pixel_mask=UpperCamelCase__     )
																					lowerCamelCase__					:	Optional[int]         =       model(UpperCamelCase__			,							output_hidden_states=UpperCamelCase__     )
														# 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(UpperCamelCase__			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				int			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				Any			,							UpperCamelCase__:				List[str]     ):
														lowerCamelCase__					:	List[Any]         =       MaskFormerForInstanceSegmentation(config=UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()

														def comm_check_on_output(UpperCamelCase__:				List[str]     ):
																					# 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__					:	Optional[int]         =       model(pixel_values=UpperCamelCase__			,							pixel_mask=UpperCamelCase__     )
																					lowerCamelCase__					:	Any         =       model(UpperCamelCase__     )

																					comm_check_on_output(UpperCamelCase__     )

																					lowerCamelCase__					:	Optional[int]         =       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 _lowercase	(				_lowercase				,      _lowercase				,      unittest.TestCase		):
							a				      =       (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
							a				      =       (
							    {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation}
							    if is_torch_available()
							    else {}
							)

							a				      =       False
							a				      =       False
							a				      =       False
							a				      =       False




							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__					:	Any         =       MaskFormerModelTester(self     )
														lowerCamelCase__					:	List[Any]         =       ConfigTester(self			,							config_class=UpperCamelCase__			,							has_text_modality=UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				List[str]     ):
														self.config_tester.run_common_tests()




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	List[str]         =       self.model_tester.prepare_config_and_inputs_for_common()
														self.model_tester.create_and_check_maskformer_model(UpperCamelCase__			,							**UpperCamelCase__			,							output_hidden_states=UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	List[str]         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*UpperCamelCase__     )




							@unittest.skip(reason="""MaskFormer does not use inputs_embeds"""     )
							def 		lowerCamelCase_				(							self:				str     ):
														pass




							@unittest.skip(reason="""MaskFormer does not have a get_input_embeddings method"""     )
							def 		lowerCamelCase_				(							self:				str     ):
														pass




							@unittest.skip(reason="""MaskFormer is not a generative model"""     )
							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														pass




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




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




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	Any         =       self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCamelCase__					:	Union[str, Any]         =       ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]			,							UpperCamelCase__     )




							@slow
							def 		lowerCamelCase_				(							self:				List[str]     ):
														for model_name in ["facebook/maskformer-swin-small-coco"]:
																					lowerCamelCase__					:	Any         =       MaskFormerModel.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__					:	Union[str, Any]         =       (self.model_tester.min_size,) * 2
														lowerCamelCase__					:	Dict         =       {
														    """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(),
														}

														lowerCamelCase__					:	List[str]         =       MaskFormerForInstanceSegmentation(MaskFormerConfig()     ).to(UpperCamelCase__     )
														lowerCamelCase__					:	List[str]         =       model(**UpperCamelCase__     )
														self.assertTrue(outputs.loss is not None     )




							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	Any         =       self.model_tester.prepare_config_and_inputs_for_common()
														self.model_tester.create_and_check_maskformer_model(UpperCamelCase__			,							**UpperCamelCase__			,							output_hidden_states=UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	List[Any]         =       self.model_tester.prepare_config_and_inputs_for_common()

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




							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														if not self.model_tester.is_training:
																					return
														# only MaskFormerForInstanceSegmentation has the loss
														lowerCamelCase__					:	Optional[Any]         =       self.all_model_classes[1]
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	Optional[Any]         =       self.model_tester.prepare_config_and_inputs()

														lowerCamelCase__					:	Dict         =       model_class(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.train()

														lowerCamelCase__					:	Optional[int]         =       model(UpperCamelCase__			,							mask_labels=UpperCamelCase__			,							class_labels=UpperCamelCase__     ).loss
														loss.backward()




							def 		lowerCamelCase_				(							self:				str     ):
														# only MaskFormerForInstanceSegmentation has the loss
														lowerCamelCase__					:	List[str]         =       self.all_model_classes[1]
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	Any         =       self.model_tester.prepare_config_and_inputs()
														lowerCamelCase__					:	List[str]         =       True
														lowerCamelCase__					:	Tuple         =       True

														lowerCamelCase__					:	int         =       model_class(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.train()

														lowerCamelCase__					:	Tuple         =       model(UpperCamelCase__			,							mask_labels=UpperCamelCase__			,							class_labels=UpperCamelCase__     )

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

														lowerCamelCase__					:	Optional[int]         =       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__					:	int         =       outputs.transformer_decoder_hidden_states[0]
														transformer_decoder_hidden_states.retain_grad()

														lowerCamelCase__					:	str         =       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     )



_A	:			Optional[int]         =1e-4





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



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




							@cached_property
							def 		lowerCamelCase_				(							self:				Dict     ):
														return (
														    MaskFormerImageProcessor.from_pretrained("""facebook/maskformer-swin-small-coco"""     )
														    if is_vision_available()
														    else None
														)




							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														lowerCamelCase__					:	Optional[Any]         =       MaskFormerModel.from_pretrained("""facebook/maskformer-swin-small-coco"""     ).to(UpperCamelCase__     )
														lowerCamelCase__					:	str         =       self.default_image_processor
														lowerCamelCase__					:	Dict         =       prepare_img()
														lowerCamelCase__					:	List[str]         =       image_processor(UpperCamelCase__			,							return_tensors="""pt"""     ).to(UpperCamelCase__     )
														lowerCamelCase__					:	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, 800, 1_088)     )

														with torch.no_grad():
																					lowerCamelCase__					:	List[str]         =       model(**UpperCamelCase__     )

														lowerCamelCase__					:	Optional[Any]         =       torch.tensor(
														    [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]     ).to(UpperCamelCase__     )
														self.assertTrue(
														    torch.allclose(
														        outputs.encoder_last_hidden_state[0, 0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )

														lowerCamelCase__					:	Optional[Any]         =       torch.tensor(
														    [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]     ).to(UpperCamelCase__     )
														self.assertTrue(
														    torch.allclose(
														        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )

														lowerCamelCase__					:	List[str]         =       torch.tensor(
														    [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]     ).to(UpperCamelCase__     )
														self.assertTrue(
														    torch.allclose(
														        outputs.transformer_decoder_last_hidden_state[0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Union[str, Any]         =       (
														    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""     )
														    .to(UpperCamelCase__     )
														    .eval()
														)
														lowerCamelCase__					:	Optional[int]         =       self.default_image_processor
														lowerCamelCase__					:	List[Any]         =       prepare_img()
														lowerCamelCase__					:	Tuple         =       image_processor(UpperCamelCase__			,							return_tensors="""pt"""     ).to(UpperCamelCase__     )
														lowerCamelCase__					:	List[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, 800, 1_088)     )

														with torch.no_grad():
																					lowerCamelCase__					:	Dict         =       model(**UpperCamelCase__     )
														# 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__					:	int         =       [
														    [-1.3_737_124, -1.7_724_937, -1.9_364_233],
														    [-1.5_977_281, -1.9_867_939, -2.1_523_695],
														    [-1.5_795_398, -1.9_269_832, -2.093_942],
														]
														lowerCamelCase__					:	int         =       torch.tensor(UpperCamelCase__     ).to(UpperCamelCase__     )
														self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )
														# class_queries_logits
														lowerCamelCase__					:	Any         =       outputs.class_queries_logits
														self.assertEqual(
														    class_queries_logits.shape			,							(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)     )
														lowerCamelCase__					:	Tuple         =       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(UpperCamelCase__     )
														self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )




							def 		lowerCamelCase_				(							self:				List[Any]     ):
														lowerCamelCase__					:	Optional[int]         =       (
														    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-resnet101-coco-stuff"""     )
														    .to(UpperCamelCase__     )
														    .eval()
														)
														lowerCamelCase__					:	str         =       self.default_image_processor
														lowerCamelCase__					:	List[str]         =       prepare_img()
														lowerCamelCase__					:	List[Any]         =       image_processor(UpperCamelCase__			,							return_tensors="""pt"""     ).to(UpperCamelCase__     )
														lowerCamelCase__					:	List[str]         =       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, 800, 1_088)     )

														with torch.no_grad():
																					lowerCamelCase__					:	Any         =       model(**UpperCamelCase__     )
														# masks_queries_logits
														lowerCamelCase__					:	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__					:	Optional[Any]         =       [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
														lowerCamelCase__					:	List[Any]         =       torch.tensor(UpperCamelCase__     ).to(UpperCamelCase__     )
														self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )
														# class_queries_logits
														lowerCamelCase__					:	Dict         =       outputs.class_queries_logits
														self.assertEqual(
														    class_queries_logits.shape			,							(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)     )
														lowerCamelCase__					:	Optional[int]         =       torch.tensor(
														    [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]     ).to(UpperCamelCase__     )
														self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]			,							UpperCamelCase__			,							atol=UpperCamelCase__     )     )




							def 		lowerCamelCase_				(							self:				Tuple     ):
														lowerCamelCase__					:	Optional[int]         =       (
														    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""     )
														    .to(UpperCamelCase__     )
														    .eval()
														)
														lowerCamelCase__					:	Any         =       self.default_image_processor

														lowerCamelCase__					:	Optional[Any]         =       image_processor(
														    [np.zeros((3, 800, 1_333)     ), np.zeros((3, 800, 1_333)     )]			,							segmentation_maps=[np.zeros((384, 384)     ).astype(np.floataa     ), np.zeros((384, 384)     ).astype(np.floataa     )]			,							return_tensors="""pt"""			,							)

														lowerCamelCase__					:	Optional[int]         =       inputs["""pixel_values"""].to(UpperCamelCase__     )
														lowerCamelCase__					:	int         =       [el.to(UpperCamelCase__     ) for el in inputs["""mask_labels"""]]
														lowerCamelCase__					:	int         =       [el.to(UpperCamelCase__     ) for el in inputs["""class_labels"""]]

														with torch.no_grad():
																					lowerCamelCase__					:	List[Any]         =       model(**UpperCamelCase__     )

														self.assertTrue(outputs.loss is not None     )









'''simple docstring'''







import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import MobileNetVaForImageClassification, MobileNetVaModel
			from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileNetVaImageProcessor

class _lowercase	(				_lowercase		):




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	str         =       self.config_class(**self.inputs_dict     )
														self.parent.assertTrue(hasattr(UpperCamelCase__			,							"""tf_padding"""     )     )
														self.parent.assertTrue(hasattr(UpperCamelCase__			,							"""depth_multiplier"""     )     )



class _lowercase	:




							def __init__(							self:				str			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				Tuple=13			,							UpperCamelCase__:				Optional[int]=3			,							UpperCamelCase__:				List[Any]=32			,							UpperCamelCase__:				Optional[Any]=0.25			,							UpperCamelCase__:				int=8			,							UpperCamelCase__:				Any=True			,							UpperCamelCase__:				Dict=1_024			,							UpperCamelCase__:				Optional[int]=32			,							UpperCamelCase__:				Tuple="relu6"			,							UpperCamelCase__:				int=0.1			,							UpperCamelCase__:				List[Any]=0.02			,							UpperCamelCase__:				Optional[Any]=True			,							UpperCamelCase__:				Union[str, Any]=True			,							UpperCamelCase__:				Union[str, Any]=10			,							UpperCamelCase__:				str=None			,							):
														lowerCamelCase__					:	Optional[Any]         =       parent
														lowerCamelCase__					:	List[str]         =       batch_size
														lowerCamelCase__					:	Optional[int]         =       num_channels
														lowerCamelCase__					:	Optional[int]         =       image_size
														lowerCamelCase__					:	Optional[Any]         =       depth_multiplier
														lowerCamelCase__					:	Union[str, Any]         =       min_depth
														lowerCamelCase__					:	Optional[Any]         =       tf_padding
														lowerCamelCase__					:	str         =       int(last_hidden_size * depth_multiplier     )
														lowerCamelCase__					:	Any         =       output_stride
														lowerCamelCase__					:	int         =       hidden_act
														lowerCamelCase__					:	Tuple         =       classifier_dropout_prob
														lowerCamelCase__					:	Dict         =       use_labels
														lowerCamelCase__					:	Tuple         =       is_training
														lowerCamelCase__					:	Optional[Any]         =       num_labels
														lowerCamelCase__					:	Union[str, Any]         =       initializer_range
														lowerCamelCase__					:	Optional[Any]         =       scope




							def 		lowerCamelCase_				(							self:				List[str]     ):
														lowerCamelCase__					:	Optional[Any]         =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

														lowerCamelCase__					:	Optional[Any]         =       None
														lowerCamelCase__					:	Dict         =       None
														if self.use_labels:
																					lowerCamelCase__					:	Union[str, Any]         =       ids_tensor([self.batch_size]			,							self.num_labels     )
																					lowerCamelCase__					:	Dict         =       ids_tensor([self.batch_size, self.image_size, self.image_size]			,							self.num_labels     )

														lowerCamelCase__					:	Dict         =       self.get_config()

														return config, pixel_values, labels, pixel_labels




							def 		lowerCamelCase_				(							self:				str     ):
														return MobileNetVaConfig(
														    num_channels=self.num_channels			,							image_size=self.image_size			,							depth_multiplier=self.depth_multiplier			,							min_depth=self.min_depth			,							tf_padding=self.tf_padding			,							hidden_act=self.hidden_act			,							classifier_dropout_prob=self.classifier_dropout_prob			,							initializer_range=self.initializer_range			,							)




							def 		lowerCamelCase_				(							self:				Tuple			,							UpperCamelCase__:				int			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Any			,							UpperCamelCase__:				Optional[int]     ):
														lowerCamelCase__					:	List[str]         =       MobileNetVaModel(config=UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	List[str]         =       model(UpperCamelCase__     )
														self.parent.assertEqual(
														    result.last_hidden_state.shape			,							(
														        self.batch_size,
														        self.last_hidden_size,
														        self.image_size // self.output_stride,
														        self.image_size // self.output_stride,
														    )			,							)




							def 		lowerCamelCase_				(							self:				str			,							UpperCamelCase__:				Tuple			,							UpperCamelCase__:				Optional[int]			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				Union[str, Any]     ):
														lowerCamelCase__					:	List[str]         =       self.num_labels
														lowerCamelCase__					:	Optional[Any]         =       MobileNetVaForImageClassification(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	List[Any]         =       model(UpperCamelCase__			,							labels=UpperCamelCase__     )
														self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)     )




							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														lowerCamelCase__					:	str         =       self.prepare_config_and_inputs()
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	int         =       config_and_inputs
														lowerCamelCase__					:	Optional[int]         =       {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_torch
class _lowercase	(				_lowercase				,      _lowercase				,      unittest.TestCase		):
							a				      =       (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
							a				      =       (
							    {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							a				      =       False
							a				      =       False
							a				      =       False
							a				      =       False




							def 		lowerCamelCase_				(							self:				List[str]     ):
														lowerCamelCase__					:	Optional[int]         =       MobileNetVaModelTester(self     )
														lowerCamelCase__					:	List[str]         =       MobileNetVaConfigTester(self			,							config_class=UpperCamelCase__			,							has_text_modality=UpperCamelCase__     )




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




							@unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""     )
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														pass




							@unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""     )
							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														pass




							@unittest.skip(reason="""MobileNetV1 does not output attentions"""     )
							def 		lowerCamelCase_				(							self:				Any     ):
														pass




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	Optional[Any]         =       self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCamelCase__					:	Dict         =       ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__					:	Tuple         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														def check_hidden_states_output(UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				List[Any]     ):
																					lowerCamelCase__					:	str         =       model_class(UpperCamelCase__     )
																					model.to(UpperCamelCase__     )
																					model.eval()

																					with torch.no_grad():
																												lowerCamelCase__					:	Union[str, Any]         =       model(**self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__     )     )

																					lowerCamelCase__					:	List[Any]         =       outputs.hidden_states

																					lowerCamelCase__					:	Tuple         =       26
																					self.assertEqual(len(UpperCamelCase__     )			,							UpperCamelCase__     )

														lowerCamelCase__  ,		lowerCamelCase__					:	List[str]         =       self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__					:	List[Any]         =       True
																					check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					lowerCamelCase__					:	Optional[Any]         =       True

																					check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	int         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__     )




							@slow
							def 		lowerCamelCase_				(							self:				List[str]     ):
														for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	Dict         =       MobileNetVaModel.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )





def  SCREAMING_SNAKE_CASE_       ()      ->       Union[str, Any]:
							lowerCamelCase__					:	Optional[int]         =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
							return image



@require_torch
@require_vision
class _lowercase	(				unittest.TestCase		):




							@cached_property
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														return (
														    MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224"""     ) if is_vision_available() else None
														)




							@slow
							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	List[Any]         =       MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""     ).to(UpperCamelCase__     )

														lowerCamelCase__					:	Dict         =       self.default_image_processor
														lowerCamelCase__					:	int         =       prepare_img()
														lowerCamelCase__					:	List[Any]         =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""     ).to(UpperCamelCase__     )

														# forward pass
														with torch.no_grad():
																					lowerCamelCase__					:	str         =       model(**UpperCamelCase__     )

														# verify the logits
														lowerCamelCase__					:	List[str]         =       torch.Size((1, 1_001)     )
														self.assertEqual(outputs.logits.shape			,							UpperCamelCase__     )

														lowerCamelCase__					:	List[str]         =       torch.tensor([-4.1_739, -1.1_233, 3.1_205]     ).to(UpperCamelCase__     )

														self.assertTrue(torch.allclose(outputs.logits[0, :3]			,							UpperCamelCase__			,							atol=1e-4     )     )

