





'''simple docstring'''






import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
		from transformers.models.mobilevitva.modeling_mobilevitva import (
		    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
		    make_divisible,
		)


if is_vision_available():
		from PIL import Image

		from transformers import MobileViTImageProcessor







class 			lowerCamelCase					(						_SCREAMING_SNAKE_CASE  ):


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		self.config_class(**self.inputs_dict       )
											self.parent.assertTrue(hasattr(A_       ,     'width_multiplier'       )       )







class 			lowerCamelCase					:


					def __init__(					self	:  List[Any]       ,     __snake_case	:  Any       ,     __snake_case	:  str=13       ,     __snake_case	:  List[str]=64       ,     __snake_case	:  List[str]=2       ,     __snake_case	:  Tuple=3       ,     __snake_case	:  Any="swish"       ,     __snake_case	:  List[str]=3       ,     __snake_case	:  Dict=32       ,     __snake_case	:  str=0.1       ,     __snake_case	:  List[str]=0.02       ,     __snake_case	:  List[str]=True       ,     __snake_case	:  Dict=True       ,     __snake_case	:  Optional[int]=10       ,     __snake_case	:  Union[str, Any]=None       ,     __snake_case	:  List[str]=0.25       ,     __snake_case	:  List[Any]=0.0       ,     __snake_case	:  Union[str, Any]=0.0       ,     ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		parent
											_snake_case:   List[str]  					=		batch_size
											_snake_case:   Dict  					=		image_size
											_snake_case:   List[str]  					=		patch_size
											_snake_case:   List[Any]  					=		num_channels
											_snake_case:   Any  					=		make_divisible(5_12 * width_multiplier       ,     divisor=8       )
											_snake_case:   Union[str, Any]  					=		hidden_act
											_snake_case:   List[Any]  					=		conv_kernel_size
											_snake_case:   Any  					=		output_stride
											_snake_case:   int  					=		classifier_dropout_prob
											_snake_case:   Tuple  					=		use_labels
											_snake_case:   Optional[Any]  					=		is_training
											_snake_case:   List[str]  					=		num_labels
											_snake_case:   Optional[int]  					=		initializer_range
											_snake_case:   int  					=		scope
											_snake_case:   Tuple  					=		width_multiplier
											_snake_case:   Any  					=		ffn_dropout
											_snake_case:   Optional[Any]  					=		attn_dropout


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

											_snake_case:   List[Any]  					=		None
											_snake_case:   Optional[int]  					=		None
											if self.use_labels:
																	_snake_case:   str  					=		ids_tensor([self.batch_size]       ,     self.num_labels       )
																	_snake_case:   Any  					=		ids_tensor([self.batch_size, self.image_size, self.image_size]       ,     self.num_labels       )

											_snake_case:   List[str]  					=		self.get_config()

											return config, pixel_values, labels, pixel_labels


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											return MobileViTVaConfig(
											    image_size=self.image_size       ,     patch_size=self.patch_size       ,     num_channels=self.num_channels       ,     hidden_act=self.hidden_act       ,     conv_kernel_size=self.conv_kernel_size       ,     output_stride=self.output_stride       ,     classifier_dropout_prob=self.classifier_dropout_prob       ,     initializer_range=self.initializer_range       ,     width_multiplier=self.width_multiplier       ,     ffn_dropout=self.ffn_dropout_prob       ,     attn_dropout=self.attn_dropout_prob       ,     )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  str       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   Any  					=		MobileViTVaModel(config=A_       )
											model.to(A_       )
											model.eval()
											_snake_case:   Any  					=		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    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Tuple       ,     __snake_case	:  Any       ,     __snake_case	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case:   int  					=		self.num_labels
											_snake_case:   Tuple  					=		MobileViTVaForImageClassification(A_       )
											model.to(A_       )
											model.eval()
											_snake_case:   Union[str, Any]  					=		model(A_       ,     labels=A_       )
											self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ,     __snake_case	:  Dict       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Dict       ,     __snake_case	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		self.num_labels
											_snake_case:   Optional[Any]  					=		MobileViTVaForSemanticSegmentation(A_       )
											model.to(A_       )
											model.eval()
											_snake_case:   Any  					=		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,
											    )       ,     )
											_snake_case:   int  					=		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    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   Tuple  					=		self.prepare_config_and_inputs()
											_snake_case					,						_snake_case					,						_snake_case					,						_snake_case:   Tuple  					=		config_and_inputs
											_snake_case:   List[str]  					=		{'pixel_values': pixel_values}
											return config, inputs_dict







@require_torch
class 			lowerCamelCase					(						_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							unittest.TestCase  ):
					_SCREAMING_SNAKE_CASE							   =    (
					    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)

					_SCREAMING_SNAKE_CASE							   =    (
					    {
					        "feature-extraction": MobileViTVaModel,
					        "image-classification": MobileViTVaForImageClassification,
					        "image-segmentation": MobileViTVaForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		MobileViTVaModelTester(self       )
											_snake_case:   Any  					=		MobileViTVaConfigTester(self       ,     config_class=A_       ,     has_text_modality=A_       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					@unittest.skip(reason='MobileViTV2 does not use inputs_embeds'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											pass


					@unittest.skip(reason='MobileViTV2 does not support input and output embeddings'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											pass


					@unittest.skip(reason='MobileViTV2 does not output attentions'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											pass


					@require_torch_multi_gpu
					@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											pass


					@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   Tuple  					=		self.model_tester.prepare_config_and_inputs_for_common()

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

																	_snake_case:   Optional[int]  					=		['pixel_values']
																	self.assertListEqual(arg_names[:1]       ,     A_       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*A_       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											def check_hidden_states_output(__snake_case	:  Optional[Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Optional[int]       ):
																	_snake_case:   str  					=		model_class(A_       )
																	model.to(A_       )
																	model.eval()

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

																	_snake_case:   str  					=		outputs.hidden_states

																	_snake_case:   List[str]  					=		5
																	self.assertEqual(len(A_       )       ,     A_       )

																	# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
																	# with the width and height being successively divided by 2.
																	_snake_case:   List[str]  					=		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       )

											_snake_case					,						_snake_case:   Optional[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	_snake_case:   Optional[Any]  					=		True
																	check_hidden_states_output(A_       ,     A_       ,     A_       )

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

																	check_hidden_states_output(A_       ,     A_       ,     A_       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*A_       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case:   Any  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*A_       )




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_snake_case:   Tuple  					=		MobileViTVaModel.from_pretrained(A_       )
																	self.assertIsNotNone(A_       )





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







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


					@cached_property
					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											return (
											    MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'       )
											    if is_vision_available()
											    else None
											)


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'       ).to(
											    A_       )

											_snake_case:   Tuple  					=		self.default_image_processor
											_snake_case:   Optional[Any]  					=		prepare_img()
											_snake_case:   Dict  					=		image_processor(images=A_       ,     return_tensors='pt'       ).to(A_       )

											# forward pass
											with torch.no_grad():
																	_snake_case:   List[Any]  					=		model(**A_       )

											# verify the logits
											_snake_case:   Dict  					=		torch.Size((1, 10_00)       )
											self.assertEqual(outputs.logits.shape       ,     A_       )

											_snake_case:   List[str]  					=		torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01]       ).to(A_       )

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


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   int  					=		MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )
											_snake_case:   Union[str, Any]  					=		model.to(A_       )

											_snake_case:   List[str]  					=		MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )

											_snake_case:   List[str]  					=		prepare_img()
											_snake_case:   int  					=		image_processor(images=A_       ,     return_tensors='pt'       ).to(A_       )

											# forward pass
											with torch.no_grad():
																	_snake_case:   Dict  					=		model(**A_       )
											_snake_case:   List[Any]  					=		outputs.logits

											# verify the logits
											_snake_case:   Union[str, Any]  					=		torch.Size((1, 21, 32, 32)       )
											self.assertEqual(logits.shape       ,     A_       )

											_snake_case:   List[str]  					=		torch.tensor(
											    [
											        [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
											        [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
											        [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
											    ]       ,     device=A_       ,     )

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




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )
											_snake_case:   str  					=		model.to(A_       )

											_snake_case:   Optional[Any]  					=		MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )

											_snake_case:   Tuple  					=		prepare_img()
											_snake_case:   List[Any]  					=		image_processor(images=A_       ,     return_tensors='pt'       ).to(A_       )

											# forward pass
											with torch.no_grad():
																	_snake_case:   List[Any]  					=		model(**A_       )

											_snake_case:   Any  					=		outputs.logits.detach().cpu()

											_snake_case:   Optional[int]  					=		image_processor.post_process_semantic_segmentation(outputs=A_       ,     target_sizes=[(50, 60)]       )
											_snake_case:   Tuple  					=		torch.Size((50, 60)       )
											self.assertEqual(segmentation[0].shape       ,     A_       )

											_snake_case:   Tuple  					=		image_processor.post_process_semantic_segmentation(outputs=A_       )
											_snake_case:   Optional[int]  					=		torch.Size((32, 32)       )
											self.assertEqual(segmentation[0].shape       ,     A_       )












'''simple docstring'''






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin







class 			lowerCamelCase					(						__UpperCAmelCase  ):
					_SCREAMING_SNAKE_CASE							   =    "Speech2TextFeatureExtractor"
					_SCREAMING_SNAKE_CASE							   =    "Speech2TextTokenizer"


					def __init__(					self	:  List[str]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  List[str]       ):





											'''simple docstring'''





											super().__init__(__snake_case       ,     __snake_case       )
											_snake_case:   Optional[int]  					=		self.feature_extractor
											_snake_case:   Dict  					=		False


					def __call__(					self	:  Optional[int]       ,     *__snake_case	:  Optional[Any]       ,     **__snake_case	:  Union[str, Any]       ):





											'''simple docstring'''





											if self._in_target_context_manager:
																	return self.current_processor(*__snake_case       ,     **__snake_case       )

											if "raw_speech" in kwargs:
																	warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'       )
																	_snake_case:   int  					=		kwargs.pop('raw_speech'       )
											else:
																	_snake_case:   Tuple  					=		kwargs.pop('audio'       ,     __snake_case       )
											_snake_case:   Optional[Any]  					=		kwargs.pop('sampling_rate'       ,     __snake_case       )
											_snake_case:   Optional[Any]  					=		kwargs.pop('text'       ,     __snake_case       )
											if len(__snake_case       ) > 0:
																	_snake_case:   Optional[Any]  					=		args[0]
																	_snake_case:   Union[str, Any]  					=		args[1:]

											if audio is None and text is None:
																	raise ValueError('You need to specify either an `audio` or `text` input to process.'       )

											if audio is not None:
																	_snake_case:   List[Any]  					=		self.feature_extractor(__snake_case       ,     *__snake_case       ,     sampling_rate=__snake_case       ,     **__snake_case       )
											if text is not None:
																	_snake_case:   Tuple  					=		self.tokenizer(__snake_case       ,     **__snake_case       )

											if text is None:
																	return inputs
											elif audio is None:
																	return encodings
											else:
																	_snake_case:   List[Any]  					=		encodings['input_ids']
																	return inputs


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     *__snake_case	:  Optional[int]       ,     **__snake_case	:  str       ):





											'''simple docstring'''





											return self.tokenizer.batch_decode(*__snake_case       ,     **__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     *__snake_case	:  List[str]       ,     **__snake_case	:  Tuple       ):





											'''simple docstring'''





											return self.tokenizer.decode(*__snake_case       ,     **__snake_case       )




					@contextmanager
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											warnings.warn(
											    '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '
											    'labels by using the argument `text` of the regular `__call__` method (either in the same call as '
											    'your audio inputs, or in a separate call.'       )
											_snake_case:   Any  					=		True
											_snake_case:   str  					=		self.tokenizer
											yield
											_snake_case:   Union[str, Any]  					=		self.feature_extractor
											_snake_case:   Tuple  					=		False





