"""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 	UpperCamelCase    (					lowercase		):



				def       _lowercase  (self       :   List[Any])					->			Optional[int]:
					__snake_case    :							str   	=				self.config_class(**self.inputs_dict)
					self.parent.assertTrue(hasattr(UpperCamelCase__			,						'width_multiplier'))







class 	UpperCamelCase    :



				def __init__(self       :   Any			,						_A       :   Dict			,						_A       :   Optional[int]=13			,						_A       :   Any=64			,						_A       :   str=2			,						_A       :   Union[str, Any]=3			,						_A       :   Any="swish"			,						_A       :   Optional[Any]=3			,						_A       :   Union[str, Any]=32			,						_A       :   Any=0.1			,						_A       :   Union[str, Any]=0.02			,						_A       :   Any=True			,						_A       :   Union[str, Any]=True			,						_A       :   Optional[int]=10			,						_A       :   List[str]=None			,						_A       :   Any=0.25			,						_A       :   Any=0.0			,						_A       :   str=0.0			,						)					->			List[str]:
					__snake_case    :							List[Any]   	=				parent
					__snake_case    :							Dict   	=				batch_size
					__snake_case    :							str   	=				image_size
					__snake_case    :							List[str]   	=				patch_size
					__snake_case    :							Optional[int]   	=				num_channels
					__snake_case    :							Any   	=				make_divisible(5_12 * width_multiplier			,						divisor=8)
					__snake_case    :							List[Any]   	=				hidden_act
					__snake_case    :							Optional[Any]   	=				conv_kernel_size
					__snake_case    :							int   	=				output_stride
					__snake_case    :							Optional[Any]   	=				classifier_dropout_prob
					__snake_case    :							Optional[int]   	=				use_labels
					__snake_case    :							int   	=				is_training
					__snake_case    :							Any   	=				num_labels
					__snake_case    :							Any   	=				initializer_range
					__snake_case    :							int   	=				scope
					__snake_case    :							Optional[Any]   	=				width_multiplier
					__snake_case    :							Union[str, Any]   	=				ffn_dropout
					__snake_case    :							Any   	=				attn_dropout



				def       _lowercase  (self       :   Optional[Any])					->			Tuple:
					__snake_case    :							str   	=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

					__snake_case    :							Tuple   	=				self.get_config()

					return config, pixel_values, labels, pixel_labels



				def       _lowercase  (self       :   List[Any])					->			List[str]:
					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       _lowercase  (self       :   Dict			,						_A       :   Any			,						_A       :   List[Any]			,						_A       :   Union[str, Any]			,						_A       :   Any)					->			Any:
					__snake_case    :							str   	=				MobileViTVaModel(config=UpperCamelCase__)
					model.to(UpperCamelCase__)
					model.eval()
					__snake_case    :							int   	=				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       _lowercase  (self       :   Optional[int]			,						_A       :   List[Any]			,						_A       :   List[Any]			,						_A       :   Union[str, Any]			,						_A       :   str)					->			Any:
					__snake_case    :							Any   	=				self.num_labels
					__snake_case    :							Tuple   	=				MobileViTVaForImageClassification(UpperCamelCase__)
					model.to(UpperCamelCase__)
					model.eval()
					__snake_case    :							str   	=				model(UpperCamelCase__			,						labels=UpperCamelCase__)
					self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels))



				def       _lowercase  (self       :   Tuple			,						_A       :   Dict			,						_A       :   str			,						_A       :   List[Any]			,						_A       :   Union[str, Any])					->			Union[str, Any]:
					__snake_case    :							List[Any]   	=				self.num_labels
					__snake_case    :							Optional[Any]   	=				MobileViTVaForSemanticSegmentation(UpperCamelCase__)
					model.to(UpperCamelCase__)
					model.eval()
					__snake_case    :							Any   	=				model(UpperCamelCase__)
					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    :							str   	=				model(UpperCamelCase__			,						labels=UpperCamelCase__)
					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       _lowercase  (self       :   Optional[int])					->			List[str]:
					__snake_case    :							Optional[Any]   	=				self.prepare_config_and_inputs()
					__snake_case	,       __snake_case	,       __snake_case	,       __snake_case    :							Union[str, Any]   	=				config_and_inputs
					__snake_case    :							Any   	=				{'pixel_values': pixel_values}
					return config, inputs_dict







@require_torch
class 	UpperCamelCase    (					lowercase   ,			lowercase   ,			unittest.TestCase		):
				UpperCAmelCase       :   Dict					=	(
				    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)

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

				UpperCAmelCase       :   List[str]					=	False
				UpperCAmelCase       :   str					=	False
				UpperCAmelCase       :   Optional[int]					=	False
				UpperCAmelCase       :   List[str]					=	False



				def       _lowercase  (self       :   Any)					->			Any:
					__snake_case    :							Tuple   	=				MobileViTVaModelTester(self)
					__snake_case    :							Optional[int]   	=				MobileViTVaConfigTester(self			,						config_class=UpperCamelCase__			,						has_text_modality=UpperCamelCase__)



				def       _lowercase  (self       :   Any)					->			str:
					self.config_tester.run_common_tests()



				@unittest.skip(reason='MobileViTV2 does not use inputs_embeds')
				def       _lowercase  (self       :   List[str])					->			List[str]:
					pass



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



				@unittest.skip(reason='MobileViTV2 does not output attentions')
				def       _lowercase  (self       :   Optional[int])					->			List[str]:
					pass



				@require_torch_multi_gpu
				@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.')
				def       _lowercase  (self       :   int)					->			str:
					pass



				@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
				def       _lowercase  (self       :   Optional[int])					->			Tuple:
					pass



				def       _lowercase  (self       :   List[Any])					->			Optional[Any]:
					__snake_case	,       __snake_case    :							Tuple   	=				self.model_tester.prepare_config_and_inputs_for_common()

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

						__snake_case    :							Dict   	=				['pixel_values']
						self.assertListEqual(arg_names[:1]			,						UpperCamelCase__)



				def       _lowercase  (self       :   Union[str, Any])					->			str:
					__snake_case    :							Any   	=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*UpperCamelCase__)



				def       _lowercase  (self       :   List[str])					->			Optional[Any]:





					def check_hidden_states_output(_A       :   List[str]			,						_A       :   Dict			,						_A       :   Union[str, Any]):
						__snake_case    :							List[Any]   	=				model_class(UpperCamelCase__)
						model.to(UpperCamelCase__)
						model.eval()

						with torch.no_grad():
							__snake_case    :							int   	=				model(**self._prepare_for_class(UpperCamelCase__			,						UpperCamelCase__))

						__snake_case    :							Optional[Any]   	=				outputs.hidden_states

						__snake_case    :							Optional[int]   	=				5
						self.assertEqual(len(UpperCamelCase__)			,						UpperCamelCase__)

						# 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    :							Dict   	=				2
						for i in range(len(UpperCamelCase__)):
							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[int]   	=				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						__snake_case    :							str   	=				True
						check_hidden_states_output(UpperCamelCase__			,						UpperCamelCase__			,						UpperCamelCase__)

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						__snake_case    :							int   	=				True

						check_hidden_states_output(UpperCamelCase__			,						UpperCamelCase__			,						UpperCamelCase__)



				def       _lowercase  (self       :   Optional[int])					->			str:
					__snake_case    :							List[Any]   	=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__)



				def       _lowercase  (self       :   Any)					->			Union[str, Any]:
					__snake_case    :							Tuple   	=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__)






				@slow
				def       _lowercase  (self       :   str)					->			Optional[int]:





					for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__snake_case    :							List[str]   	=				MobileViTVaModel.from_pretrained(UpperCamelCase__)
						self.assertIsNotNone(UpperCamelCase__)







def 						__UpperCAmelCase       (					)							->    Optional[Any]:

	'''simple docstring'''





	__snake_case    :							Dict   	=				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
	return image

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



				@cached_property
				def       _lowercase  (self       :   List[Any])					->			Union[str, Any]:
					return (
					    MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256')
					    if is_vision_available()
					    else None
					)



				@slow
				def       _lowercase  (self       :   Tuple)					->			Optional[int]:
					__snake_case    :							str   	=				MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256').to(
					    UpperCamelCase__)

					__snake_case    :							Tuple   	=				self.default_image_processor
					__snake_case    :							Dict   	=				prepare_img()
					__snake_case    :							Union[str, Any]   	=				image_processor(images=UpperCamelCase__			,						return_tensors='pt').to(UpperCamelCase__)

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

					# verify the logits
					__snake_case    :							Union[str, Any]   	=				torch.Size((1, 10_00))
					self.assertEqual(outputs.logits.shape			,						UpperCamelCase__)

					__snake_case    :							Union[str, Any]   	=				torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01]).to(UpperCamelCase__)

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



				@slow
				def       _lowercase  (self       :   Tuple)					->			Dict:
					__snake_case    :							int   	=				MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')
					__snake_case    :							int   	=				model.to(UpperCamelCase__)

					__snake_case    :							Tuple   	=				MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')

					__snake_case    :							Tuple   	=				prepare_img()
					__snake_case    :							Optional[int]   	=				image_processor(images=UpperCamelCase__			,						return_tensors='pt').to(UpperCamelCase__)

					# forward pass
					with torch.no_grad():
						__snake_case    :							Any   	=				model(**UpperCamelCase__)
					__snake_case    :							Any   	=				outputs.logits

					# verify the logits
					__snake_case    :							Dict   	=				torch.Size((1, 21, 32, 32))
					self.assertEqual(logits.shape			,						UpperCamelCase__)

					__snake_case    :							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=UpperCamelCase__			,						)

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






				@slow
				def       _lowercase  (self       :   Tuple)					->			int:
					__snake_case    :							Optional[int]   	=				MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')
					__snake_case    :							Tuple   	=				model.to(UpperCamelCase__)

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

					__snake_case    :							Optional[int]   	=				prepare_img()
					__snake_case    :							str   	=				image_processor(images=UpperCamelCase__			,						return_tensors='pt').to(UpperCamelCase__)

					# forward pass
					with torch.no_grad():
						__snake_case    :							Dict   	=				model(**UpperCamelCase__)

					__snake_case    :							Optional[Any]   	=				outputs.logits.detach().cpu()

					__snake_case    :							Any   	=				image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__			,						target_sizes=[(50, 60)])
					__snake_case    :							Union[str, Any]   	=				torch.Size((50, 60))
					self.assertEqual(segmentation[0].shape			,						UpperCamelCase__)

					__snake_case    :							int   	=				image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__)
					__snake_case    :							int   	=				torch.Size((32, 32))
					self.assertEqual(segmentation[0].shape			,						UpperCamelCase__)






"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available


_a  :  Any=				{"configuration_speech_encoder_decoder": ["SpeechEncoderDecoderConfig"]}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	_a  :  Union[str, Any]=				["SpeechEncoderDecoderModel"]

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	_a  :  Tuple=				["FlaxSpeechEncoderDecoderModel"]

if TYPE_CHECKING:
	from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel

	try:
		if not is_flax_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel

else:
	import sys

	_a  :  str=				_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





