


"""simple docstring"""



from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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 tensorflow as tf

		from transformers import TFCvtForImageClassification, TFCvtModel
		from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor







class    __a						( __snake_case							):







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			self.config_class(**self.inputs_dict   )
					self.parent.assertTrue(hasattr(UpperCAmelCase      ,	'''embed_dim'''   )   )
					self.parent.assertTrue(hasattr(UpperCAmelCase      ,	'''num_heads'''   )   )







class    __a						:







				def __init__( self      ,	UpperCAmelCase      ,	UpperCAmelCase=13      ,	UpperCAmelCase=64      ,	UpperCAmelCase=3      ,	UpperCAmelCase=[16, 48, 96]      ,	UpperCAmelCase=[1, 3, 6]      ,	UpperCAmelCase=[1, 2, 10]      ,	UpperCAmelCase=[7, 3, 3]      ,	UpperCAmelCase=[4, 2, 2]      ,	UpperCAmelCase=[2, 1, 1]      ,	UpperCAmelCase=[2, 2, 2]      ,	UpperCAmelCase=[False, False, True]      ,	UpperCAmelCase=[0.0, 0.0, 0.0]      ,	UpperCAmelCase=0.0_2      ,	UpperCAmelCase=1E-1_2      ,	UpperCAmelCase=True      ,	UpperCAmelCase=True      ,	UpperCAmelCase=2      ,	):

					'''simple docstring'''






					lowerCAmelCase_      							=			parent
					lowerCAmelCase_      							=			batch_size
					lowerCAmelCase_      							=			image_size
					lowerCAmelCase_      							=			patch_sizes
					lowerCAmelCase_      							=			patch_stride
					lowerCAmelCase_      							=			patch_padding
					lowerCAmelCase_      							=			is_training
					lowerCAmelCase_      							=			use_labels
					lowerCAmelCase_      							=			num_labels
					lowerCAmelCase_      							=			num_channels
					lowerCAmelCase_      							=			embed_dim
					lowerCAmelCase_      							=			num_heads
					lowerCAmelCase_      							=			stride_kv
					lowerCAmelCase_      							=			depth
					lowerCAmelCase_      							=			cls_token
					lowerCAmelCase_      							=			attention_drop_rate
					lowerCAmelCase_      							=			initializer_range
					lowerCAmelCase_      							=			layer_norm_eps







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

					lowerCAmelCase_      							=			None
					if self.use_labels:
						# create a random int32 tensor of given shape
						lowerCAmelCase_      							=			ids_tensor([self.batch_size]      ,	self.num_labels   )

					lowerCAmelCase_      							=			self.get_config()
					return config, pixel_values, labels







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					return CvtConfig(
					    image_size=self.image_size      ,	num_labels=self.num_labels      ,	num_channels=self.num_channels      ,	embed_dim=self.embed_dim      ,	num_heads=self.num_heads      ,	patch_sizes=self.patch_sizes      ,	patch_padding=self.patch_padding      ,	patch_stride=self.patch_stride      ,	stride_kv=self.stride_kv      ,	depth=self.depth      ,	cls_token=self.cls_token      ,	attention_drop_rate=self.attention_drop_rate      ,	initializer_range=self.initializer_range      ,	)







				def      lowerCamelCase_     ( self      ,	UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			TFCvtModel(config=UpperCAmelCase   )
					lowerCAmelCase_      							=			model(UpperCAmelCase      ,	training=UpperCAmelCase   )
					lowerCAmelCase_      							=			(self.image_size, self.image_size)
					lowerCAmelCase_							,	lowerCAmelCase_      							=			image_size[0], image_size[1]
					for i in range(len(self.depth   )   ):
						lowerCAmelCase_      							=			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
						lowerCAmelCase_      							=			floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
					self.parent.assertEqual(result.last_hidden_state.shape      ,	(self.batch_size, self.embed_dim[-1], height, width)   )







				def      lowerCamelCase_     ( self      ,	UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			self.num_labels
					lowerCAmelCase_      							=			TFCvtForImageClassification(UpperCAmelCase   )
					lowerCAmelCase_      							=			model(UpperCAmelCase      ,	labels=UpperCAmelCase      ,	training=UpperCAmelCase   )
					self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.num_labels)   )







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			self.prepare_config_and_inputs()
					lowerCAmelCase_							,	lowerCAmelCase_							,	lowerCAmelCase_      							=			config_and_inputs
					lowerCAmelCase_      							=			{'''pixel_values''': pixel_values}
					return config, inputs_dict







@require_tf
class    __a						( __snake_case					,			__snake_case					,			unittest.TestCase							):
				lowerCamelCase     :       List[str]			       =(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
				lowerCamelCase     :       List[str]			       =(
				    {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
				    if is_tf_available()
				    else {}
				)
				lowerCamelCase     :       Tuple			       =False
				lowerCamelCase     :       Any			       =False
				lowerCamelCase     :       List[str]			       =False
				lowerCamelCase     :       str			       =False
				lowerCamelCase     :       Tuple			       =False







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			TFCvtModelTester(self   )
					lowerCAmelCase_      							=			TFCvtConfigTester(self      ,	config_class=UpperCAmelCase      ,	has_text_modality=UpperCAmelCase      ,	hidden_size=37   )







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					self.config_tester.create_and_test_config_common_properties()
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()







				@unittest.skip(reason='''Cvt does not output attentions'''   )
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					pass







				@unittest.skip(reason='''Cvt does not use inputs_embeds'''   )
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					pass







				@unittest.skip(reason='''Cvt does not support input and output embeddings'''   )
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					pass







				@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      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					super().test_dataset_conversion()







				@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      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					super().test_keras_fit()







				@unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'''   )
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			tf.keras.mixed_precision.Policy('''mixed_float16'''   )
					tf.keras.mixed_precision.set_global_policy(UpperCAmelCase   )
					super().test_keras_fit()
					tf.keras.mixed_precision.set_global_policy('''float32'''   )







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_							,	lowerCAmelCase_      							=			self.model_tester.prepare_config_and_inputs_for_common()

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

						lowerCAmelCase_      							=			['''pixel_values''']
						self.assertListEqual(arg_names[:1]      ,	UpperCAmelCase   )







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					def check_hidden_states_output(UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase   ):
						lowerCAmelCase_      							=			model_class(UpperCAmelCase   )

						lowerCAmelCase_      							=			model(**self._prepare_for_class(UpperCAmelCase      ,	UpperCAmelCase   )   )
						lowerCAmelCase_      							=			outputs.hidden_states

						lowerCAmelCase_      							=			len(self.model_tester.depth   )
						self.assertEqual(len(UpperCAmelCase   )      ,	UpperCAmelCase   )

						# verify the first hidden states (first block)
						self.assertListEqual(
						    list(hidden_states[0].shape[-3:]   )      ,	[
						        self.model_tester.embed_dim[0],
						        self.model_tester.image_size // 4,
						        self.model_tester.image_size // 4,
						    ]      ,	)

					lowerCAmelCase_							,	lowerCAmelCase_      							=			self.model_tester.prepare_config_and_inputs_for_common()

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

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

						check_hidden_states_output(UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase   )







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*UpperCAmelCase   )







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase   )







				@slow
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowerCAmelCase_      							=			TFCvtModel.from_pretrained(UpperCAmelCase   )
						self.assertIsNotNone(UpperCAmelCase   )




def      UpperCAmelCase     (       )						-> str:


	"""simple docstring"""




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







@require_tf
@require_vision
class    __a						( unittest.TestCase							):







				@cached_property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )







				@slow
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

					lowerCAmelCase_      							=			self.default_image_processor
					lowerCAmelCase_      							=			prepare_img()
					lowerCAmelCase_      							=			image_processor(images=UpperCAmelCase      ,	return_tensors='''tf'''   )

					# forward pass
					lowerCAmelCase_      							=			model(**UpperCAmelCase   )

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

					lowerCAmelCase_      							=			tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]   )
					self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,	UpperCAmelCase      ,	atol=1E-4   )   )



"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowercase_							=							logging.get_logger(__name__)

lowercase_							=							{
    'google/mobilenet_v2_1.4_224': 'https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json',
    'google/mobilenet_v2_1.0_224': 'https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json',
    'google/mobilenet_v2_0.75_160': 'https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json',
    'google/mobilenet_v2_0.35_96': 'https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json',
    # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2
}







class    __a						( __snake_case							):
				lowerCamelCase     :       List[Any]			       ='mobilenet_v2'







				def __init__( self      ,	UpperCAmelCase=3      ,	UpperCAmelCase=224      ,	UpperCAmelCase=1.0      ,	UpperCAmelCase=8      ,	UpperCAmelCase=8      ,	UpperCAmelCase=6      ,	UpperCAmelCase=32      ,	UpperCAmelCase=True      ,	UpperCAmelCase=True      ,	UpperCAmelCase="relu6"      ,	UpperCAmelCase=True      ,	UpperCAmelCase=0.8      ,	UpperCAmelCase=0.0_2      ,	UpperCAmelCase=0.0_0_1      ,	UpperCAmelCase=255      ,	**UpperCAmelCase      ,	):

					'''simple docstring'''






					super().__init__(**UpperCAmelCase   )

					if depth_multiplier <= 0:
						raise ValueError('''depth_multiplier must be greater than zero.'''   )

					lowerCAmelCase_      							=			num_channels
					lowerCAmelCase_      							=			image_size
					lowerCAmelCase_      							=			depth_multiplier
					lowerCAmelCase_      							=			depth_divisible_by
					lowerCAmelCase_      							=			min_depth
					lowerCAmelCase_      							=			expand_ratio
					lowerCAmelCase_      							=			output_stride
					lowerCAmelCase_      							=			first_layer_is_expansion
					lowerCAmelCase_      							=			finegrained_output
					lowerCAmelCase_      							=			hidden_act
					lowerCAmelCase_      							=			tf_padding
					lowerCAmelCase_      							=			classifier_dropout_prob
					lowerCAmelCase_      							=			initializer_range
					lowerCAmelCase_      							=			layer_norm_eps
					lowerCAmelCase_      							=			semantic_loss_ignore_index







class    __a						( __snake_case							):
				lowerCamelCase     :       Optional[int]			       =version.parse('1.11'							)







				@property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					return OrderedDict([('''pixel_values''', {0: '''batch'''})]   )







				@property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					if self.task == "image-classification":
						return OrderedDict([('''logits''', {0: '''batch'''})]   )
					else:
						return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]   )







				@property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					return 1E-4