





"""simple docstring"""





import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
						from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import MobileViTImageProcessor





class        _lowerCamelCase      (       _lowercase ):


						def     snake_case_   (self		) ->   Union[str, Any]:
								UpperCamelCase   =	self.config_class(**self.inputs_dict		)
								self.parent.assertTrue(hasattr(__a   ,							"hidden_sizes"		)		)
								self.parent.assertTrue(hasattr(__a   ,							"neck_hidden_sizes"		)		)
								self.parent.assertTrue(hasattr(__a   ,							"num_attention_heads"		)		)





class        _lowerCamelCase      :


						def __init__(self   ,							__a   ,							__a=13   ,							__a=32   ,							__a=2   ,							__a=3   ,							__a=6_40   ,							__a=4   ,							__a="silu"   ,							__a=3   ,							__a=32   ,							__a=0.1   ,							__a=0.1   ,							__a=0.1   ,							__a=0.02   ,							__a=True   ,							__a=True   ,							__a=10   ,							__a=None   ,							) ->   List[str]:
								UpperCamelCase   =	parent
								UpperCamelCase   =	batch_size
								UpperCamelCase   =	image_size
								UpperCamelCase   =	patch_size
								UpperCamelCase   =	num_channels
								UpperCamelCase   =	last_hidden_size
								UpperCamelCase   =	num_attention_heads
								UpperCamelCase   =	hidden_act
								UpperCamelCase   =	conv_kernel_size
								UpperCamelCase   =	output_stride
								UpperCamelCase   =	hidden_dropout_prob
								UpperCamelCase   =	attention_probs_dropout_prob
								UpperCamelCase   =	classifier_dropout_prob
								UpperCamelCase   =	use_labels
								UpperCamelCase   =	is_training
								UpperCamelCase   =	num_labels
								UpperCamelCase   =	initializer_range
								UpperCamelCase   =	scope


						def     snake_case_   (self		) ->   Dict:
								UpperCamelCase   =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

								UpperCamelCase   =	None
								UpperCamelCase   =	None
								if self.use_labels:
										UpperCamelCase   =	ids_tensor([self.batch_size]   ,							self.num_labels		)
										UpperCamelCase   =	ids_tensor([self.batch_size, self.image_size, self.image_size]   ,							self.num_labels		)

								UpperCamelCase   =	self.get_config()

								return config, pixel_values, labels, pixel_labels


						def     snake_case_   (self		) ->   List[Any]:
								return MobileViTConfig(
								    image_size=self.image_size   ,							patch_size=self.patch_size   ,							num_channels=self.num_channels   ,							num_attention_heads=self.num_attention_heads   ,							hidden_act=self.hidden_act   ,							conv_kernel_size=self.conv_kernel_size   ,							output_stride=self.output_stride   ,							hidden_dropout_prob=self.hidden_dropout_prob   ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,							classifier_dropout_prob=self.classifier_dropout_prob   ,							initializer_range=self.initializer_range   ,							)


						def     snake_case_   (self   ,							__a   ,							__a   ,							__a   ,							__a		) ->   Union[str, Any]:
								UpperCamelCase   =	MobileViTModel(config=__a		)
								model.to(__a		)
								model.eval()
								UpperCamelCase   =	model(__a		)
								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     snake_case_   (self   ,							__a   ,							__a   ,							__a   ,							__a		) ->   Any:
								UpperCamelCase   =	self.num_labels
								UpperCamelCase   =	MobileViTForImageClassification(__a		)
								model.to(__a		)
								model.eval()
								UpperCamelCase   =	model(__a   ,							labels=__a		)
								self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.num_labels)		)


						def     snake_case_   (self   ,							__a   ,							__a   ,							__a   ,							__a		) ->   List[str]:
								UpperCamelCase   =	self.num_labels
								UpperCamelCase   =	MobileViTForSemanticSegmentation(__a		)
								model.to(__a		)
								model.eval()
								UpperCamelCase   =	model(__a		)
								self.parent.assertEqual(
								    result.logits.shape   ,							(
								        self.batch_size,
								        self.num_labels,
								        self.image_size // self.output_stride,
								        self.image_size // self.output_stride,
								    )   ,							)
								UpperCamelCase   =	model(__a   ,							labels=__a		)
								self.parent.assertEqual(
								    result.logits.shape   ,							(
								        self.batch_size,
								        self.num_labels,
								        self.image_size // self.output_stride,
								        self.image_size // self.output_stride,
								    )   ,							)




						def     snake_case_   (self		) ->   Tuple:
								UpperCamelCase   =	self.prepare_config_and_inputs()
								UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   =	config_and_inputs
								UpperCamelCase   =	{"pixel_values": pixel_values}
								return config, inputs_dict





@require_torch
class        _lowerCamelCase      (       _lowercase  ,			_lowercase  ,			unittest.TestCase ):
						UpperCAmelCase_ =			(
						    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						UpperCAmelCase_ =			(
						    {
						        "feature-extraction": MobileViTModel,
						        "image-classification": MobileViTForImageClassification,
						        "image-segmentation": MobileViTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						UpperCAmelCase_ =			False
						UpperCAmelCase_ =			False
						UpperCAmelCase_ =			False
						UpperCAmelCase_ =			False


						def     snake_case_   (self		) ->   str:
								UpperCamelCase   =	MobileViTModelTester(self		)
								UpperCamelCase   =	MobileViTConfigTester(self   ,							config_class=__a   ,							has_text_modality=__a		)


						def     snake_case_   (self		) ->   str:
								self.config_tester.run_common_tests()


						@unittest.skip(reason="MobileViT does not use inputs_embeds"		)
						def     snake_case_   (self		) ->   List[Any]:
								pass


						@unittest.skip(reason="MobileViT does not support input and output embeddings"		)
						def     snake_case_   (self		) ->   List[Any]:
								pass


						@unittest.skip(reason="MobileViT does not output attentions"		)
						def     snake_case_   (self		) ->   Dict:
								pass


						def     snake_case_   (self		) ->   Optional[Any]:
								UpperCamelCase   ,				UpperCamelCase   =	self.model_tester.prepare_config_and_inputs_for_common()

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

										UpperCamelCase   =	["pixel_values"]
										self.assertListEqual(arg_names[:1]   ,							__a		)


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


						def     snake_case_   (self		) ->   Optional[int]:
								UpperCamelCase   =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__a		)


						def     snake_case_   (self		) ->   int:
								def check_hidden_states_output(__a   ,							__a   ,							__a		):
										UpperCamelCase   =	model_class(__a		)
										model.to(__a		)
										model.eval()

										with torch.no_grad():
												UpperCamelCase   =	model(**self._prepare_for_class(__a   ,							__a		)		)

										UpperCamelCase   =	outputs.hidden_states

										UpperCamelCase   =	5
										self.assertEqual(len(__a		)   ,							__a		)

										# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
										# with the width and height being successively divided by 2.
										UpperCamelCase   =	2
										for i in range(len(__a		)		):
												self.assertListEqual(
												    list(hidden_states[i].shape[-2:]		)   ,							[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]   ,							)
												divisor *= 2

										self.assertEqual(self.model_tester.output_stride   ,							divisor // 2		)

								UpperCamelCase   ,				UpperCamelCase   =	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
										UpperCamelCase   =	True
										check_hidden_states_output(__a   ,							__a   ,							__a		)

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										UpperCamelCase   =	True

										check_hidden_states_output(__a   ,							__a   ,							__a		)


						def     snake_case_   (self		) ->   Optional[Any]:
								UpperCamelCase   =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__a		)


						def     snake_case_   (self		) ->   Dict:
								UpperCamelCase   =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*__a		)




						@slow
						def     snake_case_   (self		) ->   int:
								for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										UpperCamelCase   =	MobileViTModel.from_pretrained(__a		)
										self.assertIsNotNone(__a		)



def       a__					(					):




		"""simple docstring"""


		UpperCamelCase   =	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
		return image






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


						@cached_property
						def     snake_case_   (self		) ->   Tuple:
								return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"		) if is_vision_available() else None


						@slow
						def     snake_case_   (self		) ->   Dict:
								UpperCamelCase   =	MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"		).to(__a		)

								UpperCamelCase   =	self.default_image_processor
								UpperCamelCase   =	prepare_img()
								UpperCamelCase   =	image_processor(images=__a   ,							return_tensors="pt"		).to(__a		)

								# forward pass
								with torch.no_grad():
										UpperCamelCase   =	model(**__a		)

								# verify the logits
								UpperCamelCase   =	torch.Size((1, 10_00)		)
								self.assertEqual(outputs.logits.shape   ,							__a		)

								UpperCamelCase   =	torch.tensor([-1.9364, -1.2327, -0.4653]		).to(__a		)

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


						@slow
						def     snake_case_   (self		) ->   Optional[int]:
								UpperCamelCase   =	MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"		)
								UpperCamelCase   =	model.to(__a		)

								UpperCamelCase   =	MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"		)

								UpperCamelCase   =	prepare_img()
								UpperCamelCase   =	image_processor(images=__a   ,							return_tensors="pt"		).to(__a		)

								# forward pass
								with torch.no_grad():
										UpperCamelCase   =	model(**__a		)
								UpperCamelCase   =	outputs.logits

								# verify the logits
								UpperCamelCase   =	torch.Size((1, 21, 32, 32)		)
								self.assertEqual(logits.shape   ,							__a		)

								UpperCamelCase   =	torch.tensor(
								    [
								        [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
								        [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
								        [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
								    ]   ,							device=__a   ,							)

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




						@slow
						def     snake_case_   (self		) ->   int:
								UpperCamelCase   =	MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"		)
								UpperCamelCase   =	model.to(__a		)

								UpperCamelCase   =	MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"		)

								UpperCamelCase   =	prepare_img()
								UpperCamelCase   =	image_processor(images=__a   ,							return_tensors="pt"		).to(__a		)

								# forward pass
								with torch.no_grad():
										UpperCamelCase   =	model(**__a		)

								UpperCamelCase   =	outputs.logits.detach().cpu()

								UpperCamelCase   =	image_processor.post_process_semantic_segmentation(outputs=__a   ,							target_sizes=[(50, 60)]		)
								UpperCamelCase   =	torch.Size((50, 60)		)
								self.assertEqual(segmentation[0].shape   ,							__a		)

								UpperCamelCase   =	image_processor.post_process_semantic_segmentation(outputs=__a		)
								UpperCamelCase   =	torch.Size((32, 32)		)
								self.assertEqual(segmentation[0].shape   ,							__a		)













"""simple docstring"""





import os

from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home


lowerCAmelCase__     			=			HUGGINGFACE_HUB_CACHE


lowerCAmelCase__     			=			'''config.json'''
lowerCAmelCase__     			=			'''diffusion_pytorch_model.bin'''
lowerCAmelCase__     			=			'''diffusion_flax_model.msgpack'''
lowerCAmelCase__     			=			'''model.onnx'''
lowerCAmelCase__     			=			'''diffusion_pytorch_model.safetensors'''
lowerCAmelCase__     			=			'''weights.pb'''
lowerCAmelCase__     			=			'''https://huggingface.co'''
lowerCAmelCase__     			=			default_cache_path
lowerCAmelCase__     			=			'''diffusers_modules'''
lowerCAmelCase__     			=			os.getenv('''HF_MODULES_CACHE''', os.path.join(hf_cache_home, '''modules'''))
lowerCAmelCase__     			=			['''fp16''', '''non-ema''']
lowerCAmelCase__     			=			'''.self_attn'''






