

"""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      __UpperCamelCase					(  snake_case_		):


		def    SCREAMING_SNAKE_CASE__  (self					:						Union[str, Any]):
							A     =   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      __UpperCamelCase					:


		def __init__(self					:						Any	,	__SCREAMING_SNAKE_CASE					:						str	,	__SCREAMING_SNAKE_CASE					:						Optional[int]=1_3	,	__SCREAMING_SNAKE_CASE					:						Optional[int]=3_2	,	__SCREAMING_SNAKE_CASE					:						Optional[Any]=2	,	__SCREAMING_SNAKE_CASE					:						Union[str, Any]=3	,	__SCREAMING_SNAKE_CASE					:						Dict=6_4_0	,	__SCREAMING_SNAKE_CASE					:						int=4	,	__SCREAMING_SNAKE_CASE					:						Dict="silu"	,	__SCREAMING_SNAKE_CASE					:						str=3	,	__SCREAMING_SNAKE_CASE					:						Tuple=3_2	,	__SCREAMING_SNAKE_CASE					:						List[Any]=0.1	,	__SCREAMING_SNAKE_CASE					:						Optional[Any]=0.1	,	__SCREAMING_SNAKE_CASE					:						Tuple=0.1	,	__SCREAMING_SNAKE_CASE					:						Tuple=0.0_2	,	__SCREAMING_SNAKE_CASE					:						List[Any]=True	,	__SCREAMING_SNAKE_CASE					:						Union[str, Any]=True	,	__SCREAMING_SNAKE_CASE					:						int=1_0	,	__SCREAMING_SNAKE_CASE					:						List[Any]=None	,	):
							A     =   parent
							A     =   batch_size
							A     =   image_size
							A     =   patch_size
							A     =   num_channels
							A     =   last_hidden_size
							A     =   num_attention_heads
							A     =   hidden_act
							A     =   conv_kernel_size
							A     =   output_stride
							A     =   hidden_dropout_prob
							A     =   attention_probs_dropout_prob
							A     =   classifier_dropout_prob
							A     =   use_labels
							A     =   is_training
							A     =   num_labels
							A     =   initializer_range
							A     =   scope


		def    SCREAMING_SNAKE_CASE__  (self					:						List[Any]):
							A     =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

							A     =   self.get_config()

							return config, pixel_values, labels, pixel_labels


		def    SCREAMING_SNAKE_CASE__  (self					:						Optional[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    SCREAMING_SNAKE_CASE__  (self					:						int	,	__SCREAMING_SNAKE_CASE					:						List[Any]	,	__SCREAMING_SNAKE_CASE					:						Optional[int]	,	__SCREAMING_SNAKE_CASE					:						Any	,	__SCREAMING_SNAKE_CASE					:						Optional[int]):
							A     =   TFMobileViTModel(config=_A)
							A     =   model(_A	,	training=_A)
							A     =   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    SCREAMING_SNAKE_CASE__  (self					:						List[str]	,	__SCREAMING_SNAKE_CASE					:						int	,	__SCREAMING_SNAKE_CASE					:						int	,	__SCREAMING_SNAKE_CASE					:						int	,	__SCREAMING_SNAKE_CASE					:						int):
							A     =   self.num_labels
							A     =   TFMobileViTForImageClassification(_A)
							A     =   model(_A	,	labels=_A	,	training=_A)
							self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels))


		def    SCREAMING_SNAKE_CASE__  (self					:						Tuple	,	__SCREAMING_SNAKE_CASE					:						int	,	__SCREAMING_SNAKE_CASE					:						Dict	,	__SCREAMING_SNAKE_CASE					:						Optional[int]	,	__SCREAMING_SNAKE_CASE					:						List[str]):
							A     =   self.num_labels
							A     =   TFMobileViTForSemanticSegmentation(_A)
							A     =   self.image_size // self.output_stride

							A     =   model(_A	,	training=_A)
							self.parent.assertEqual(
							    result.logits.shape	,	(self.batch_size, self.num_labels, expected_height, expected_width))

							A     =   model(_A	,	labels=_A	,	training=_A)
							self.parent.assertEqual(
							    result.logits.shape	,	(self.batch_size, self.num_labels, expected_height, expected_width))


		def    SCREAMING_SNAKE_CASE__  (self					:						Optional[Any]):
							A     =   self.prepare_config_and_inputs()
							A     =   config_and_inputs
							A     =   {'pixel_values': pixel_values}
							return config, inputs_dict





@require_tf
class      __UpperCamelCase					(  snake_case_	,						snake_case_	,						unittest.TestCase		):
		SCREAMING_SNAKE_CASE														=       (
		    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
		    if is_tf_available()
		    else ()
		)
		SCREAMING_SNAKE_CASE														=       (
		    {"feature-extraction": TFMobileViTModel, "image-classification": TFMobileViTForImageClassification}
		    if is_tf_available()
		    else {}
		)

		SCREAMING_SNAKE_CASE														=       False
		SCREAMING_SNAKE_CASE														=       False
		SCREAMING_SNAKE_CASE														=       False
		SCREAMING_SNAKE_CASE														=       False
		SCREAMING_SNAKE_CASE														=       False


		def    SCREAMING_SNAKE_CASE__  (self					:						int):
							A     =   TFMobileViTModelTester(self)
							A     =   TFMobileViTConfigTester(self	,	config_class=_A	,	has_text_modality=_A)


		def    SCREAMING_SNAKE_CASE__  (self					:						Union[str, Any]):
							self.config_tester.run_common_tests()


		@unittest.skip(reason="MobileViT does not use inputs_embeds")
		def    SCREAMING_SNAKE_CASE__  (self					:						Tuple):
							pass


		@unittest.skip(reason="MobileViT does not support input and output embeddings")
		def    SCREAMING_SNAKE_CASE__  (self					:						Union[str, Any]):
							pass


		@unittest.skip(reason="MobileViT does not output attentions")
		def    SCREAMING_SNAKE_CASE__  (self					:						Tuple):
							pass


		def    SCREAMING_SNAKE_CASE__  (self					:						List[Any]):
							A     =   self.model_tester.prepare_config_and_inputs_for_common()

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

												A     =   ['pixel_values']
												self.assertListEqual(arg_names[:1]	,	_A)


		def    SCREAMING_SNAKE_CASE__  (self					:						List[Any]):
							A     =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A)


		def    SCREAMING_SNAKE_CASE__  (self					:						Optional[int]):


							def check_hidden_states_output(__SCREAMING_SNAKE_CASE					:						Optional[int]	,	__SCREAMING_SNAKE_CASE					:						int	,	__SCREAMING_SNAKE_CASE					:						Dict):
												A     =   model_class(_A)

												A     =   model(**self._prepare_for_class(_A	,	_A))

												A     =   outputs.hidden_states

												A     =   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.
												A     =   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)

							A     =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												A     =   True
												check_hidden_states_output(_A	,	_A	,	_A)

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

												check_hidden_states_output(_A	,	_A	,	_A)


		def    SCREAMING_SNAKE_CASE__  (self					:						Optional[Any]):
							A     =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A)


		def    SCREAMING_SNAKE_CASE__  (self					:						str):
							A     =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*_A)


		@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    SCREAMING_SNAKE_CASE__  (self					:						str):
							super().test_dataset_conversion()


		def    SCREAMING_SNAKE_CASE__  (self					:						str	,	__SCREAMING_SNAKE_CASE					:						List[str]	,	__SCREAMING_SNAKE_CASE					:						Any	,	__SCREAMING_SNAKE_CASE					:						Tuple=2E-1	,	__SCREAMING_SNAKE_CASE					:						Union[str, Any]=2E-1):
							self.assertTrue(np.allclose(_A	,	_A	,	atol=_A	,	rtol=_A))


		@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    SCREAMING_SNAKE_CASE__  (self					:						List[str]):
							A     =   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":
																	A     =   model_class(_A)
																	if getattr(_A	,	"hf_compute_loss"	,	_A):
																						super().test_keras_fit()


		def    SCREAMING_SNAKE_CASE__  (self					:						int):
							A     =   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":
																	A     =   5

												A     =   model_class(_A)
												if getattr(_A	,	"hf_compute_loss"	,	_A):
																	# The number of elements in the loss should be the same as the number of elements in the label
																	A     =   self._prepare_for_class(inputs_dict.copy()	,	_A	,	return_labels=_A)
																	A     =   prepared_for_class[
																	    sorted(prepared_for_class.keys() - inputs_dict.keys()	,	reverse=_A)[0]
																	]
																	A     =   added_label.shape.as_list()[:1]

																	# Test that model correctly compute the loss with kwargs
																	A     =   self._prepare_for_class(inputs_dict.copy()	,	_A	,	return_labels=_A)
																	A     =   {'input_ids', 'pixel_values', 'input_features'}
																	A     =   possible_input_names.intersection(set(_A)).pop()
																	A     =   prepared_for_class.pop(_A)

																	A     =   model(_A	,	**_A)[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
																	A     =   self._prepare_for_class(inputs_dict.copy()	,	_A	,	return_labels=_A)
																	A     =   {'input_ids', 'pixel_values', 'input_features'}
																	A     =   possible_input_names.intersection(set(_A)).pop()
																	A     =   prepared_for_class.pop(_A)
																	if "labels" in prepared_for_class:
																						A     =   prepared_for_class['labels'].numpy()
																						if len(labels.shape) > 1 and labels.shape[1] != 1:
																											# labels[0] = -100
																											A     =   tf.convert_to_tensor(_A)
																											A     =   model(_A	,	**_A)[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
																	A     =   self._prepare_for_class(inputs_dict.copy()	,	_A	,	return_labels=_A)
																	A     =   model(_A)[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
																	A     =   self._prepare_for_class(inputs_dict.copy()	,	_A	,	return_labels=_A)

																	# Get keys that were added with the _prepare_for_class function
																	A     =   prepared_for_class.keys() - inputs_dict.keys()
																	A     =   inspect.signature(model.call).parameters
																	A     =   list(signature.keys())

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

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

																	for index, value in sorted_tuple_index_mapping:
																						A     =   prepared_for_class[value]

																	A     =   tuple(_A)

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

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


		@slow
		def    SCREAMING_SNAKE_CASE__  (self					:						Tuple):


							for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												A     =   TFMobileViTModel.from_pretrained(_A)
												self.assertIsNotNone(_A)

def   __SCREAMING_SNAKE_CASE		(		):
					"""simple docstring"""
					A     =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
					return image





@require_tf
class      __UpperCamelCase					(  unittest.TestCase		):


		@slow
		def    SCREAMING_SNAKE_CASE__  (self					:						Optional[Any]):
							A     =   TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small")

							A     =   MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small")
							A     =   prepare_img()
							A     =   image_processor(images=_A	,	return_tensors="tf")

							# forward pass
							A     =   model(**_A	,	training=_A)

							# verify the logits
							A     =   tf.TensorShape((1, 1_0_0_0))
							self.assertEqual(outputs.logits.shape	,	_A)

							A     =   tf.constant([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3])

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


		@slow
		def    SCREAMING_SNAKE_CASE__  (self					:						List[Any]):
							A     =   TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

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

							A     =   prepare_img()
							A     =   image_processor(images=_A	,	return_tensors="tf")

							# forward pass
							A     =   model(inputs.pixel_values	,	training=_A)
							A     =   outputs.logits

							# verify the logits
							A     =   tf.TensorShape((1, 2_1, 3_2, 3_2))
							self.assertEqual(logits.shape	,	_A)

							A     =   tf.constant(
							    [
							        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
							        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
							        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
							    ])

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












import os
import shutil
import unittest
from unittest.mock import patch

from transformers.testing_utils import CaptureStd, is_pt_tf_cross_test, require_torch
class SCREAMING_SNAKE_CASE_    (       unittest.TestCase       ):






						@patch('sys.argv'		, ['fakeprogrampath', 'env']						)
						def UpperCAmelCase_					(   self   :   Tuple						)				->     Dict:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							with CaptureStd() as cs:
								transformers.commands.transformers_cli.main()
							self.assertIn('Python version'		, cs.out						)
							self.assertIn('Platform'		, cs.out						)
							self.assertIn('Using distributed or parallel set-up in script?'		, cs.out						)






						@is_pt_tf_cross_test
						@patch(
						    'sys.argv'		, ['fakeprogrampath', 'pt-to-tf', '--model-name', 'hf-internal-testing/tiny-random-gptj', '--no-pr']						)
						def UpperCAmelCase_					(   self   :   Union[str, Any]						)				->     Optional[Any]:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							shutil.rmtree('/tmp/hf-internal-testing/tiny-random-gptj'		, ignore_errors=_A						)  # cleans potential past runs
							transformers.commands.transformers_cli.main()

							# The original repo has no TF weights -- if they exist, they were created by the CLI
							self.assertTrue(os.path.exists('/tmp/hf-internal-testing/tiny-random-gptj/tf_model.h5'						)						)






						@require_torch
						@patch('sys.argv'		, ['fakeprogrampath', 'download', 'hf-internal-testing/tiny-random-gptj', '--cache-dir', '/tmp']						)
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     str:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							# # remove any previously downloaded model to start clean
							shutil.rmtree('/tmp/models--hf-internal-testing--tiny-random-gptj'		, ignore_errors=_A						)

							# run the command
							transformers.commands.transformers_cli.main()

							# check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--tiny-random-gptj
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--tiny-random-gptj/blobs'						)						)
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--tiny-random-gptj/refs'						)						)
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--tiny-random-gptj/snapshots'						)						)






						@require_torch
						@patch(
						    'sys.argv'		, [
						        'fakeprogrampath',
						        'download',
						        'hf-internal-testing/test_dynamic_model_with_tokenizer',
						        '--trust-remote-code',
						        '--cache-dir',
						        '/tmp',
						    ]		, )
						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     str:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							# # remove any previously downloaded model to start clean
							shutil.rmtree('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer'		, ignore_errors=_A						)

							# run the command
							transformers.commands.transformers_cli.main()

							# check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/blobs'						)						)
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/refs'						)						)
							self.assertTrue(
							    os.path.exists('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/snapshots'						)						)

