



'''simple docstring'''






from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import numpy as np
						import tensorflow as tf

						from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
						from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import MobileViTImageProcessor

class     SCREAMING_SNAKE_CASE(							A__      ):







	"""simple docstring"""






	def 					A     (						self      :					List[str]		)      ->		List[str]:
								UpperCAmelCase			:	Union[str, Any]										=		self.config_class(**self.inputs_dict		)
								self.parent.assertTrue(hasattr(__snake_case		,      '''hidden_sizes'''		)		)
								self.parent.assertTrue(hasattr(__snake_case		,      '''neck_hidden_sizes'''		)		)
								self.parent.assertTrue(hasattr(__snake_case		,      '''num_attention_heads'''		)		)

class     SCREAMING_SNAKE_CASE:







	"""simple docstring"""






	def __init__(						self      :					Dict		,      __snake_case      :					Optional[Any]		,      __snake_case      :					Union[str, Any]=13		,      __snake_case      :					List[str]=32		,      __snake_case      :					Optional[int]=2		,      __snake_case      :					List[str]=3		,      __snake_case      :					Any=640		,      __snake_case      :					Optional[Any]=4		,      __snake_case      :					List[str]="silu"		,      __snake_case      :					Tuple=3		,      __snake_case      :					Union[str, Any]=32		,      __snake_case      :					Optional[Any]=0.1		,      __snake_case      :					str=0.1		,      __snake_case      :					Any=0.1		,      __snake_case      :					Union[str, Any]=0.02		,      __snake_case      :					Optional[Any]=True		,      __snake_case      :					Dict=True		,      __snake_case      :					Optional[Any]=10		,      __snake_case      :					int=None		,      )      ->		Tuple:
								UpperCAmelCase			:	Any										=		parent
								UpperCAmelCase			:	Optional[Any]										=		batch_size
								UpperCAmelCase			:	Union[str, Any]										=		image_size
								UpperCAmelCase			:	Dict										=		patch_size
								UpperCAmelCase			:	Union[str, Any]										=		num_channels
								UpperCAmelCase			:	Tuple										=		last_hidden_size
								UpperCAmelCase			:	Tuple										=		num_attention_heads
								UpperCAmelCase			:	List[Any]										=		hidden_act
								UpperCAmelCase			:	List[str]										=		conv_kernel_size
								UpperCAmelCase			:	List[Any]										=		output_stride
								UpperCAmelCase			:	Dict										=		hidden_dropout_prob
								UpperCAmelCase			:	Optional[Any]										=		attention_probs_dropout_prob
								UpperCAmelCase			:	int										=		classifier_dropout_prob
								UpperCAmelCase			:	Any										=		use_labels
								UpperCAmelCase			:	Any										=		is_training
								UpperCAmelCase			:	int										=		num_labels
								UpperCAmelCase			:	Tuple										=		initializer_range
								UpperCAmelCase			:	Union[str, Any]										=		scope







	def 					A     (						self      :					List[str]		)      ->		Optional[int]:
								UpperCAmelCase			:	Dict										=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

								UpperCAmelCase			:	Union[str, Any]										=		self.get_config()

								return config, pixel_values, labels, pixel_labels







	def 					A     (						self      :					int		)      ->		Optional[int]:
								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 					A     (						self      :					Dict		,      __snake_case      :					List[str]		,      __snake_case      :					Union[str, Any]		,      __snake_case      :					Optional[Any]		,      __snake_case      :					Optional[int]		)      ->		Optional[Any]:
								UpperCAmelCase			:	Dict										=		TFMobileViTModel(config=__snake_case		)
								UpperCAmelCase			:	Optional[Any]										=		model(__snake_case		,      training=__snake_case		)
								UpperCAmelCase			:	Dict										=		self.image_size // self.output_stride
								self.parent.assertEqual(
								    result.last_hidden_state.shape		,      (self.batch_size, self.last_hidden_size, expected_height, expected_width)		)







	def 					A     (						self      :					Optional[Any]		,      __snake_case      :					Any		,      __snake_case      :					int		,      __snake_case      :					Any		,      __snake_case      :					Any		)      ->		List[str]:
								UpperCAmelCase			:	Optional[int]										=		self.num_labels
								UpperCAmelCase			:	List[Any]										=		TFMobileViTForImageClassification(__snake_case		)
								UpperCAmelCase			:	Tuple										=		model(__snake_case		,      labels=__snake_case		,      training=__snake_case		)
								self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)		)







	def 					A     (						self      :					Tuple		,      __snake_case      :					Optional[int]		,      __snake_case      :					Tuple		,      __snake_case      :					str		,      __snake_case      :					List[str]		)      ->		Tuple:
								UpperCAmelCase			:	List[Any]										=		self.num_labels
								UpperCAmelCase			:	List[str]										=		TFMobileViTForSemanticSegmentation(__snake_case		)
								UpperCAmelCase			:	int										=		self.image_size // self.output_stride

								UpperCAmelCase			:	Union[str, Any]										=		model(__snake_case		,      training=__snake_case		)
								self.parent.assertEqual(
								    result.logits.shape		,      (self.batch_size, self.num_labels, expected_height, expected_width)		)

								UpperCAmelCase			:	List[Any]										=		model(__snake_case		,      labels=__snake_case		,      training=__snake_case		)
								self.parent.assertEqual(
								    result.logits.shape		,      (self.batch_size, self.num_labels, expected_height, expected_width)		)







	def 					A     (						self      :					int		)      ->		str:
								UpperCAmelCase			:	Optional[Any]										=		self.prepare_config_and_inputs()
								UpperCAmelCase							,		UpperCAmelCase							,		UpperCAmelCase							,		UpperCAmelCase			:	Tuple										=		config_and_inputs
								UpperCAmelCase			:	int										=		{'''pixel_values''': pixel_values}
								return config, inputs_dict

@require_tf
class     SCREAMING_SNAKE_CASE(							A__							,		A__							,		unittest.TestCase      ):







	"""simple docstring"""






	lowerCamelCase__      			=	(
	    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
	    if is_tf_available()
	    else ()
	)
	lowerCamelCase__      			=	(
	    {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
	    if is_tf_available()
	    else {}
	)

	lowerCamelCase__      			=	False
	lowerCamelCase__      			=	False
	lowerCamelCase__      			=	False
	lowerCamelCase__      			=	False
	lowerCamelCase__      			=	False







	def 					A     (						self      :					int		)      ->		Optional[int]:
								UpperCAmelCase			:	Optional[Any]										=		TFMobileViTModelTester(self		)
								UpperCAmelCase			:	Union[str, Any]										=		TFMobileViTConfigTester(self		,      config_class=__snake_case		,      has_text_modality=__snake_case		)







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







	@unittest.skip(reason='''MobileViT does not use inputs_embeds'''		)
	def 					A     (						self      :					Dict		)      ->		Dict:
								pass







	@unittest.skip(reason='''MobileViT does not support input and output embeddings'''		)
	def 					A     (						self      :					int		)      ->		Optional[int]:
								pass







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







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

								for model_class in self.all_model_classes:
															UpperCAmelCase			:	Union[str, Any]										=		model_class(__snake_case		)
															UpperCAmelCase			:	Tuple										=		inspect.signature(model.call		)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															UpperCAmelCase			:	int										=		[*signature.parameters.keys()]

															UpperCAmelCase			:	List[Any]										=		['''pixel_values''']
															self.assertListEqual(arg_names[:1]		,      __snake_case		)







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







	def 					A     (						self      :					int		)      ->		Any:
								def check_hidden_states_output(__snake_case      :					List[Any]		,      __snake_case      :					Optional[Any]		,      __snake_case      :					Optional[Any]		):
															UpperCAmelCase			:	List[str]										=		model_class(__snake_case		)

															UpperCAmelCase			:	Union[str, Any]										=		model(**self._prepare_for_class(__snake_case		,      __snake_case		)		)

															UpperCAmelCase			:	str										=		outputs.hidden_states

															UpperCAmelCase			:	str										=		5
															self.assertEqual(len(__snake_case		)		,      __snake_case		)

															# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
															# with the width and height being successively divided by 2.
															UpperCAmelCase			:	Dict										=		2
															for i in range(len(__snake_case		)		):
																						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			:	Optional[Any]										=		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase			:	Dict										=		True
															check_hidden_states_output(__snake_case		,      __snake_case		,      __snake_case		)

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

															check_hidden_states_output(__snake_case		,      __snake_case		,      __snake_case		)







	def 					A     (						self      :					Optional[Any]		)      ->		Dict:
								UpperCAmelCase			:	str										=		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__snake_case		)







	def 					A     (						self      :					Any		)      ->		Any:
								UpperCAmelCase			:	str										=		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*__snake_case		)







	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''		)		) == 0		,      reason='''TF does not support backprop for grouped convolutions on CPU.'''		,      )
	def 					A     (						self      :					Tuple		)      ->		Optional[int]:
								super().test_dataset_conversion()







	def 					A     (						self      :					Tuple		,      __snake_case      :					Any		,      __snake_case      :					Union[str, Any]		,      __snake_case      :					Optional[int]=2E-1		,      __snake_case      :					int=2E-1		)      ->		Any:
								self.assertTrue(np.allclose(__snake_case		,      __snake_case		,      atol=__snake_case		,      rtol=__snake_case		)		)







	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''		)		) == 0		,      reason='''TF does not support backprop for grouped convolutions on CPU.'''		,      )
	@slow
	def 					A     (						self      :					Optional[int]		)      ->		List[str]:
								UpperCAmelCase							,		UpperCAmelCase			:	Optional[Any]										=		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
															if model_class.__name__ != "TFMobileViTModel":
																						UpperCAmelCase			:	Optional[Any]										=		model_class(__snake_case		)
																						if getattr(__snake_case		,      '''hf_compute_loss'''		,      __snake_case		):
																													super().test_keras_fit()







	def 					A     (						self      :					Union[str, Any]		)      ->		Dict:
								UpperCAmelCase							,		UpperCAmelCase			:	Any										=		self.model_tester.prepare_config_and_inputs_for_common()
								for model_class in self.all_model_classes:
															# set an ignore index to correctly test the masked loss used in
															# `TFMobileViTForSemanticSegmentation`.
															if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
																						UpperCAmelCase			:	List[Any]										=		5

															UpperCAmelCase			:	Optional[Any]										=		model_class(__snake_case		)
															if getattr(__snake_case		,      '''hf_compute_loss'''		,      __snake_case		):
																						# The number of elements in the loss should be the same as the number of elements in the label
																						UpperCAmelCase			:	Union[str, Any]										=		self._prepare_for_class(inputs_dict.copy()		,      __snake_case		,      return_labels=__snake_case		)
																						UpperCAmelCase			:	Dict										=		prepared_for_class[
																						    sorted(prepared_for_class.keys() - inputs_dict.keys()		,      reverse=__snake_case		)[0]
																						]
																						UpperCAmelCase			:	List[Any]										=		added_label.shape.as_list()[:1]

																						# Test that model correctly compute the loss with kwargs
																						UpperCAmelCase			:	Dict										=		self._prepare_for_class(inputs_dict.copy()		,      __snake_case		,      return_labels=__snake_case		)
																						UpperCAmelCase			:	Any										=		{'''input_ids''', '''pixel_values''', '''input_features'''}
																						UpperCAmelCase			:	int										=		possible_input_names.intersection(set(__snake_case		)		).pop()
																						UpperCAmelCase			:	int										=		prepared_for_class.pop(__snake_case		)

																						UpperCAmelCase			:	List[str]										=		model(__snake_case		,      **__snake_case		)[0]
																						self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)

																						# Test that model correctly compute the loss when we mask some positions
																						UpperCAmelCase			:	Union[str, Any]										=		self._prepare_for_class(inputs_dict.copy()		,      __snake_case		,      return_labels=__snake_case		)
																						UpperCAmelCase			:	int										=		{'''input_ids''', '''pixel_values''', '''input_features'''}
																						UpperCAmelCase			:	Optional[Any]										=		possible_input_names.intersection(set(__snake_case		)		).pop()
																						UpperCAmelCase			:	Any										=		prepared_for_class.pop(__snake_case		)
																						if "labels" in prepared_for_class:
																													UpperCAmelCase			:	int										=		prepared_for_class['''labels'''].numpy()
																													if len(labels.shape		) > 1 and labels.shape[1] != 1:
																																				# labels[0] = -100
																																				UpperCAmelCase			:	List[str]										=		tf.convert_to_tensor(__snake_case		)
																																				UpperCAmelCase			:	Optional[int]										=		model(__snake_case		,      **__snake_case		)[0]
																																				self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)
																																				self.assertTrue(not np.any(np.isnan(loss.numpy()		)		)		)

                # Test that model correctly compute the loss with a dict
																						UpperCAmelCase			:	Union[str, Any]										=		self._prepare_for_class(inputs_dict.copy()		,      __snake_case		,      return_labels=__snake_case		)
																						UpperCAmelCase			:	List[str]										=		model(__snake_case		)[0]
																						self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)

																						# Test that model correctly compute the loss with a tuple
																						UpperCAmelCase			:	Union[str, Any]										=		self._prepare_for_class(inputs_dict.copy()		,      __snake_case		,      return_labels=__snake_case		)

																						# Get keys that were added with the _prepare_for_class function
																						UpperCAmelCase			:	Union[str, Any]										=		prepared_for_class.keys() - inputs_dict.keys()
																						UpperCAmelCase			:	Dict										=		inspect.signature(model.call		).parameters
																						UpperCAmelCase			:	Tuple										=		list(signature.keys()		)

																						# Create a dictionary holding the location of the tensors in the tuple
																						UpperCAmelCase			:	Any										=		{0: input_name}
																						for label_key in label_keys:
																													UpperCAmelCase			:	Any										=		signature_names.index(__snake_case		)
																													UpperCAmelCase			:	str										=		label_key
																						UpperCAmelCase			:	Union[str, Any]										=		sorted(tuple_index_mapping.items()		)
																						# Initialize a list with their default values, update the values and convert to a tuple
																						UpperCAmelCase			:	Tuple										=		[]

																						for name in signature_names:
																													if name != "kwargs":
																																				list_input.append(signature[name].default		)

																						for index, value in sorted_tuple_index_mapping:
																													UpperCAmelCase			:	Dict										=		prepared_for_class[value]

																						UpperCAmelCase			:	Optional[int]										=		tuple(__snake_case		)

																						# Send to model
																						UpperCAmelCase			:	int										=		model(tuple_input[:-1]		)[0]

																						self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)







	@slow
	def 					A     (						self      :					str		)      ->		List[str]:
								for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase			:	Union[str, Any]										=		TFMobileViTModel.from_pretrained(__snake_case		)
															self.assertIsNotNone(__snake_case		)


def 			snake_case_					( )				->       int:
							UpperCAmelCase			:	int										=		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
							return image




@require_tf
class     SCREAMING_SNAKE_CASE(							unittest.TestCase      ):







	"""simple docstring"""






	@slow
	def 					A     (						self      :					Any		)      ->		Dict:
								UpperCAmelCase			:	Dict										=		TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''		)

								UpperCAmelCase			:	Union[str, Any]										=		MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''		)
								UpperCAmelCase			:	Union[str, Any]										=		prepare_img()
								UpperCAmelCase			:	Dict										=		image_processor(images=__snake_case		,      return_tensors='''tf'''		)

								# forward pass
								UpperCAmelCase			:	List[str]										=		model(**__snake_case		,      training=__snake_case		)

								# verify the logits
								UpperCAmelCase			:	int										=		tf.TensorShape((1, 1000)		)
								self.assertEqual(outputs.logits.shape		,      __snake_case		)

								UpperCAmelCase			:	Union[str, Any]										=		tf.constant([-1.93_64, -1.23_27, -0.46_53]		)

								tf.debugging.assert_near(outputs.logits[0, :3]		,      __snake_case		,      atol=1E-4		,      rtol=1E-04		)







	@slow
	def 					A     (						self      :					Optional[int]		)      ->		Union[str, Any]:
								# `from_pt` will be removed
								UpperCAmelCase			:	int										=		TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''		)

								UpperCAmelCase			:	Tuple										=		MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''		)

								UpperCAmelCase			:	str										=		prepare_img()
								UpperCAmelCase			:	int										=		image_processor(images=__snake_case		,      return_tensors='''tf'''		)

								# forward pass
								UpperCAmelCase			:	int										=		model(inputs.pixel_values		,      training=__snake_case		)
								UpperCAmelCase			:	Optional[int]										=		outputs.logits

								# verify the logits
								UpperCAmelCase			:	Dict										=		tf.TensorShape((1, 21, 32, 32)		)
								self.assertEqual(logits.shape		,      __snake_case		)

								UpperCAmelCase			:	List[Any]										=		tf.constant(
								    [
								        [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
								        [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
								        [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
								    ]		)

								tf.debugging.assert_near(logits[0, :3, :3, :3]		,      __snake_case		,      rtol=1E-4		,      atol=1E-4		)










'''simple docstring'''






from typing import TYPE_CHECKING

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


UpperCamelCase__:       Tuple							     =      {
    "configuration_splinter": ["SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SplinterConfig"],
    "tokenization_splinter": ["SplinterTokenizer"],
}

try:
						if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCamelCase__:       Optional[Any]							     =      ["SplinterTokenizerFast"]

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCamelCase__:       Any							     =      [
						    "SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST",
						    "SplinterForQuestionAnswering",
						    "SplinterForPreTraining",
						    "SplinterLayer",
						    "SplinterModel",
						    "SplinterPreTrainedModel",
						]


if TYPE_CHECKING:
						from .configuration_splinter import SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP, SplinterConfig
						from .tokenization_splinter import SplinterTokenizer

						try:
												if not is_tokenizers_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_splinter_fast import SplinterTokenizerFast

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_splinter import (
												    SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST,
												    SplinterForPreTraining,
												    SplinterForQuestionAnswering,
												    SplinterLayer,
												    SplinterModel,
												    SplinterPreTrainedModel,
												)


else:
						import sys

						UpperCamelCase__:       Dict							     =      _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





