



'''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_ (							__magic_name__			):





	def  _lowercase(  self    )			->			str:
								UpperCAmelCase     :		Any							     =		self.config_class(**self.inputs_dict    )
								self.parent.assertTrue(hasattr(A		,		"""width_multiplier"""    )    )




class 			UpperCamelCase_ :





	def __init__(  self		,		A		,		A=13		,		A=64		,		A=2		,		A=3		,		A="swish"		,		A=3		,		A=32		,		A=0.1		,		A=0.0_2		,		A=True		,		A=True		,		A=10		,		A=None		,		A=0.2_5		,		A=0.0		,		A=0.0		,		)			->			Tuple:
								UpperCAmelCase     :		Optional[int]							     =		parent
								UpperCAmelCase     :		Any							     =		batch_size
								UpperCAmelCase     :		Tuple							     =		image_size
								UpperCAmelCase     :		Any							     =		patch_size
								UpperCAmelCase     :		Optional[Any]							     =		num_channels
								UpperCAmelCase     :		List[str]							     =		make_divisible(512 * width_multiplier		,		divisor=8    )
								UpperCAmelCase     :		List[str]							     =		hidden_act
								UpperCAmelCase     :		Optional[int]							     =		conv_kernel_size
								UpperCAmelCase     :		str							     =		output_stride
								UpperCAmelCase     :		Optional[Any]							     =		classifier_dropout_prob
								UpperCAmelCase     :		Any							     =		use_labels
								UpperCAmelCase     :		List[Any]							     =		is_training
								UpperCAmelCase     :		Optional[Any]							     =		num_labels
								UpperCAmelCase     :		Dict							     =		initializer_range
								UpperCAmelCase     :		List[str]							     =		scope
								UpperCAmelCase     :		Optional[Any]							     =		width_multiplier
								UpperCAmelCase     :		Any							     =		ffn_dropout
								UpperCAmelCase     :		List[Any]							     =		attn_dropout





	def  _lowercase(  self    )			->			str:
								UpperCAmelCase     :		List[str]							     =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

								UpperCAmelCase     :		int							     =		self.get_config()

								return config, pixel_values, labels, pixel_labels





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





	def  _lowercase(  self		,		A		,		A		,		A		,		A    )			->			int:
								UpperCAmelCase     :		List[str]							     =		self.num_labels
								UpperCAmelCase     :		List[Any]							     =		MobileViTVaForSemanticSegmentation(A    )
								model.to(A    )
								model.eval()
								UpperCAmelCase     :		Dict							     =		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     :		Dict							     =		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  _lowercase(  self    )			->			Any:
								UpperCAmelCase     :		Tuple							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     :		Tuple							     =		config_and_inputs
								UpperCAmelCase     :		Tuple							     =		{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_torch
class 			UpperCamelCase_ (							__magic_name__      ,     __magic_name__      ,     unittest.TestCase			):
	lowercase          = (
	    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
	    if is_torch_available()
	    else ()
	)

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

	lowercase          = False
	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		Optional[int]							     =		MobileViTVaModelTester(self    )
								UpperCAmelCase     :		str							     =		MobileViTVaConfigTester(self		,		config_class=A		,		has_text_modality=A    )





	def  _lowercase(  self    )			->			List[str]:
								self.config_tester.run_common_tests()





	@unittest.skip(reason="""MobileViTV2 does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Dict:
								pass





	@unittest.skip(reason="""MobileViTV2 does not support input and output embeddings"""    )
	def  _lowercase(  self    )			->			str:
								pass





	@unittest.skip(reason="""MobileViTV2 does not output attentions"""    )
	def  _lowercase(  self    )			->			int:
								pass





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





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





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     ,     UpperCAmelCase     :		Tuple							     =		self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCAmelCase     :		List[str]							     =		["""pixel_values"""]
															self.assertListEqual(arg_names[:1]		,		A    )





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Any							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A    )





	def  _lowercase(  self    )			->			Optional[int]:
								def check_hidden_states_output(A		,		A		,		A    ):
															UpperCAmelCase     :		str							     =		model_class(A    )
															model.to(A    )
															model.eval()

															with torch.no_grad():
																						UpperCAmelCase     :		List[Any]							     =		model(**self._prepare_for_class(A		,		A    )    )

															UpperCAmelCase     :		List[str]							     =		outputs.hidden_states

															UpperCAmelCase     :		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.
															UpperCAmelCase     :		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    )

								UpperCAmelCase     ,     UpperCAmelCase     :		int							     =		self.model_tester.prepare_config_and_inputs_for_common()

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

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

															check_hidden_states_output(A		,		A		,		A    )





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		List[str]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*A    )





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Dict							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*A    )






	@slow
	def  _lowercase(  self    )			->			int:
								for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase     :		Tuple							     =		MobileViTVaModel.from_pretrained(A    )
															self.assertIsNotNone(A    )




def       __lowerCamelCase  (					)      ->			List[str]:
							UpperCAmelCase     :		Optional[int]							     =		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[str]:
								return (
								    MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""    )
								    if is_vision_available()
								    else None
								)





	@slow
	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Optional[Any]							     =		MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""    ).to(
								    A    )

								UpperCAmelCase     :		Optional[Any]							     =		self.default_image_processor
								UpperCAmelCase     :		int							     =		prepare_img()
								UpperCAmelCase     :		Dict							     =		image_processor(images=A		,		return_tensors="""pt"""    ).to(A    )

								# forward pass
								with torch.no_grad():
															UpperCAmelCase     :		Union[str, Any]							     =		model(**A    )

								# verify the logits
								UpperCAmelCase     :		Optional[Any]							     =		torch.Size((1, 1000)    )
								self.assertEqual(outputs.logits.shape		,		A    )

								UpperCAmelCase     :		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  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		Optional[Any]							     =		MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )
								UpperCAmelCase     :		Union[str, Any]							     =		model.to(A    )

								UpperCAmelCase     :		Any							     =		MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )

								UpperCAmelCase     :		Tuple							     =		prepare_img()
								UpperCAmelCase     :		str							     =		image_processor(images=A		,		return_tensors="""pt"""    ).to(A    )

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

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

								UpperCAmelCase     :		Union[str, Any]							     =		torch.tensor(
								    [
								        [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
								        [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
								        [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
								    ]		,		device=A		,		)

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






	@slow
	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		Any							     =		MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )
								UpperCAmelCase     :		Dict							     =		model.to(A    )

								UpperCAmelCase     :		Tuple							     =		MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )

								UpperCAmelCase     :		Tuple							     =		prepare_img()
								UpperCAmelCase     :		Optional[Any]							     =		image_processor(images=A		,		return_tensors="""pt"""    ).to(A    )

								# forward pass
								with torch.no_grad():
															UpperCAmelCase     :		Optional[Any]							     =		model(**A    )

								UpperCAmelCase     :		Optional[int]							     =		outputs.logits.detach().cpu()

								UpperCAmelCase     :		Tuple							     =		image_processor.post_process_semantic_segmentation(outputs=A		,		target_sizes=[(50, 60)]    )
								UpperCAmelCase     :		Optional[Any]							     =		torch.Size((50, 60)    )
								self.assertEqual(segmentation[0].shape		,		A    )

								UpperCAmelCase     :		int							     =		image_processor.post_process_semantic_segmentation(outputs=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		torch.Size((32, 32)    )
								self.assertEqual(segmentation[0].shape		,		A    )






'''simple docstring'''




from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
							import tensorflow as tf

							from transformers import TFBlipTextModel
							from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST

class 			UpperCamelCase_ :





	def __init__(  self		,		A		,		A=12		,		A=7		,		A=True		,		A=True		,		A=True		,		A=99		,		A=32		,		A=32		,		A=2		,		A=4		,		A=37		,		A=0.1		,		A=0.1		,		A=512		,		A=0.0_2		,		A=0		,		A=None		,		)			->			Any:
								UpperCAmelCase     :		Optional[Any]							     =		parent
								UpperCAmelCase     :		str							     =		batch_size
								UpperCAmelCase     :		Union[str, Any]							     =		seq_length
								UpperCAmelCase     :		Optional[Any]							     =		is_training
								UpperCAmelCase     :		int							     =		use_input_mask
								UpperCAmelCase     :		List[Any]							     =		use_labels
								UpperCAmelCase     :		Dict							     =		vocab_size
								UpperCAmelCase     :		str							     =		hidden_size
								UpperCAmelCase     :		List[Any]							     =		projection_dim
								UpperCAmelCase     :		Tuple							     =		num_hidden_layers
								UpperCAmelCase     :		Dict							     =		num_attention_heads
								UpperCAmelCase     :		Optional[Any]							     =		intermediate_size
								UpperCAmelCase     :		Any							     =		dropout
								UpperCAmelCase     :		List[Any]							     =		attention_dropout
								UpperCAmelCase     :		Optional[Any]							     =		max_position_embeddings
								UpperCAmelCase     :		Tuple							     =		initializer_range
								UpperCAmelCase     :		Optional[Any]							     =		scope
								UpperCAmelCase     :		Union[str, Any]							     =		bos_token_id





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		Optional[int]							     =		ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size    )

								UpperCAmelCase     :		Union[str, Any]							     =		None
								if self.use_input_mask:
															UpperCAmelCase     :		str							     =		random_attention_mask([self.batch_size, self.seq_length]    )

								if input_mask is not None:
															UpperCAmelCase     :		Tuple							     =		input_mask.numpy()
															UpperCAmelCase     ,     UpperCAmelCase     :		int							     =		input_mask.shape
															UpperCAmelCase     :		Optional[int]							     =		np.random.randint(1		,		seq_length - 1		,		size=(batch_size,)    )
															for batch_idx, start_index in enumerate(A    ):
																						UpperCAmelCase     :		Tuple							     =		1
																						UpperCAmelCase     :		Optional[Any]							     =		0

								UpperCAmelCase     :		int							     =		self.get_config()

								return config, input_ids, tf.convert_to_tensor(A    )





	def  _lowercase(  self    )			->			int:
								return BlipTextConfig(
								    vocab_size=self.vocab_size		,		hidden_size=self.hidden_size		,		projection_dim=self.projection_dim		,		num_hidden_layers=self.num_hidden_layers		,		num_attention_heads=self.num_attention_heads		,		intermediate_size=self.intermediate_size		,		dropout=self.dropout		,		attention_dropout=self.attention_dropout		,		max_position_embeddings=self.max_position_embeddings		,		initializer_range=self.initializer_range		,		bos_token_id=self.bos_token_id		,		)





	def  _lowercase(  self		,		A		,		A		,		A    )			->			Union[str, Any]:
								UpperCAmelCase     :		int							     =		TFBlipTextModel(config=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		model(A		,		attention_mask=A		,		training=A    )
								UpperCAmelCase     :		int							     =		model(A		,		training=A    )
								self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size)    )
								self.parent.assertEqual(result.pooler_output.shape		,		(self.batch_size, self.hidden_size)    )






	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Dict							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     :		Any							     =		config_and_inputs
								UpperCAmelCase     :		Optional[Any]							     =		{"""input_ids""": input_ids, """attention_mask""": input_mask}
								return config, inputs_dict




@require_tf
class 			UpperCamelCase_ (							__magic_name__      ,     unittest.TestCase			):
	lowercase          = (TFBlipTextModel,) if is_tf_available() else ()
	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Union[str, Any]							     =		BlipTextModelTester(self    )
								UpperCAmelCase     :		List[str]							     =		ConfigTester(self		,		config_class=A		,		hidden_size=37    )





	def  _lowercase(  self    )			->			Tuple:
								self.config_tester.run_common_tests()





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		List[Any]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A    )





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





	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""Blip does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Union[str, Any]:
								pass





	@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""    )
	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""    )
	def  _lowercase(  self    )			->			Dict:
								pass





	@slow
	def  _lowercase(  self    )			->			Dict:
								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase     :		Any							     =		TFBlipTextModel.from_pretrained(A    )
															self.assertIsNotNone(A    )






	def  _lowercase(  self		,		A=True    )			->			str:
								super().test_pt_tf_model_equivalence(allow_missing_keys=A    )

