



'''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 							lowercase__     (							lowercase       ):





	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       self.config_class(**self.inputs_dict			)
							self.parent.assertTrue(hasattr(lowerCamelCase__			,'embed_dim'			)			)
							self.parent.assertTrue(hasattr(lowerCamelCase__			,'num_heads'			)			)






class 							lowercase__     :





	def __init__(			self :    Any			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Optional[Any]=13			,lowerCamelCase__ :    Tuple=64			,lowerCamelCase__ :    Union[str, Any]=3			,lowerCamelCase__ :    Dict=[16, 48, 96]			,lowerCamelCase__ :    List[Any]=[1, 3, 6]			,lowerCamelCase__ :    Any=[1, 2, 10]			,lowerCamelCase__ :    Union[str, Any]=[7, 3, 3]			,lowerCamelCase__ :    Any=[4, 2, 2]			,lowerCamelCase__ :    Dict=[2, 1, 1]			,lowerCamelCase__ :    Tuple=[2, 2, 2]			,lowerCamelCase__ :    Optional[int]=[False, False, True]			,lowerCamelCase__ :    List[str]=[0.0, 0.0, 0.0]			,lowerCamelCase__ :    int=0.0_2			,lowerCamelCase__ :    Optional[Any]=1E-12			,lowerCamelCase__ :    Union[str, Any]=True			,lowerCamelCase__ :    Any=True			,lowerCamelCase__ :    str=2			,):







							'''simple docstring'''
							_UpperCamelCase :		str			    =       parent
							_UpperCamelCase :		List[str]			    =       batch_size
							_UpperCamelCase :		Any			    =       image_size
							_UpperCamelCase :		Tuple			    =       patch_sizes
							_UpperCamelCase :		Union[str, Any]			    =       patch_stride
							_UpperCamelCase :		Optional[Any]			    =       patch_padding
							_UpperCamelCase :		Optional[Any]			    =       is_training
							_UpperCamelCase :		Optional[Any]			    =       use_labels
							_UpperCamelCase :		List[Any]			    =       num_labels
							_UpperCamelCase :		Tuple			    =       num_channels
							_UpperCamelCase :		List[Any]			    =       embed_dim
							_UpperCamelCase :		List[str]			    =       num_heads
							_UpperCamelCase :		Union[str, Any]			    =       stride_kv
							_UpperCamelCase :		Tuple			    =       depth
							_UpperCamelCase :		str			    =       cls_token
							_UpperCamelCase :		str			    =       attention_drop_rate
							_UpperCamelCase :		Union[str, Any]			    =       initializer_range
							_UpperCamelCase :		int			    =       layer_norm_eps





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

							_UpperCamelCase :		Optional[Any]			    =       self.get_config()
							return config, pixel_values, labels





	def      UpperCamelCase_  (			self :    Dict			):







							'''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      UpperCamelCase_  (			self :    Dict			,lowerCamelCase__ :    int			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       TFCvtModel(config=lowerCamelCase__			)
							_UpperCamelCase :		Optional[int]			    =       model(lowerCamelCase__			,training=lowerCamelCase__			)
							_UpperCamelCase :		List[Any]			    =       (self.image_size, self.image_size)
							_UpperCamelCase    ,      _UpperCamelCase :		List[str]			    =       image_size[0], image_size[1]
							for i in range(len(self.depth			)			):
													_UpperCamelCase :		Optional[int]			    =       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1			)
													_UpperCamelCase :		Any			    =       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      UpperCamelCase_  (			self :    Tuple			,lowerCamelCase__ :    List[Any]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    int			):







							'''simple docstring'''
							_UpperCamelCase :		str			    =       self.num_labels
							_UpperCamelCase :		Optional[Any]			    =       TFCvtForImageClassification(lowerCamelCase__			)
							_UpperCamelCase :		List[Any]			    =       model(lowerCamelCase__			,labels=lowerCamelCase__			,training=lowerCamelCase__			)
							self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)			)





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       self.prepare_config_and_inputs()
							_UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase :		str			    =       config_and_inputs
							_UpperCamelCase :		Optional[int]			    =       {'pixel_values': pixel_values}
							return config, inputs_dict






@require_tf
class 							lowercase__     (							lowercase						, lowercase						, unittest.TestCase       ):
	lowercase__      =      (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
	lowercase__      =      (
	    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
	    if is_tf_available()
	    else {}
	)
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       TFCvtModelTester(self			)
							_UpperCamelCase :		Dict			    =       TFCvtConfigTester(self			,config_class=lowerCamelCase__			,has_text_modality=lowerCamelCase__			,hidden_size=37			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''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      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							pass





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







							'''simple docstring'''
							pass





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







							'''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      UpperCamelCase_  (			self :    Any			):







							'''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      UpperCamelCase_  (			self :    int			):







							'''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      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       tf.keras.mixed_precision.Policy('mixed_float16'			)
							tf.keras.mixed_precision.set_global_policy(lowerCamelCase__			)
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy('float32'			)





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		Union[str, Any]			    =       self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCamelCase :		int			    =       ['pixel_values']
													self.assertListEqual(arg_names[:1]			,lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__ :    int			,lowerCamelCase__ :    Union[str, Any]			,lowerCamelCase__ :    Dict			):
													_UpperCamelCase :		List[Any]			    =       model_class(lowerCamelCase__			)

													_UpperCamelCase :		int			    =       model(**self._prepare_for_class(lowerCamelCase__			,lowerCamelCase__			)			)
													_UpperCamelCase :		Dict			    =       outputs.hidden_states

													_UpperCamelCase :		List[str]			    =       len(self.model_tester.depth			)
													self.assertEqual(len(lowerCamelCase__			)			,lowerCamelCase__			)

													# 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,
													    ]			,)

							_UpperCamelCase    ,      _UpperCamelCase :		List[str]			    =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase :		Any			    =       True
													check_hidden_states_output(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			)

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

													check_hidden_states_output(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__			)





	@slow
	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase :		Optional[int]			    =       TFCvtModel.from_pretrained(lowerCamelCase__			)
													self.assertIsNotNone(lowerCamelCase__			)






def A__   (					):
						_UpperCamelCase :		List[Any]			    =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						return image






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





	@cached_property
	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)





	@slow
	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		Tuple			    =       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)

							_UpperCamelCase :		List[str]			    =       self.default_image_processor
							_UpperCamelCase :		Optional[int]			    =       prepare_img()
							_UpperCamelCase :		Any			    =       image_processor(images=lowerCamelCase__			,return_tensors='tf'			)

							# forward pass
							_UpperCamelCase :		List[str]			    =       model(**lowerCamelCase__			)

							# verify the logits
							_UpperCamelCase :		Optional[Any]			    =       tf.TensorShape((1, 1000)			)
							self.assertEqual(outputs.logits.shape			,lowerCamelCase__			)

							_UpperCamelCase :		Optional[int]			    =       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()			,lowerCamelCase__			,atol=1E-4			)			)







'''simple docstring'''
from typing import TYPE_CHECKING

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


snake_case_			:     Any  	=  {
    'configuration_mvp': ['MVP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MvpConfig', 'MvpOnnxConfig'],
    'tokenization_mvp': ['MvpTokenizer'],
}

try:
					if not is_tokenizers_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					snake_case_			:     Dict  	=  ['MvpTokenizerFast']

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					snake_case_			:     List[Any]  	=  [
					    'MVP_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'MvpForCausalLM',
					    'MvpForConditionalGeneration',
					    'MvpForQuestionAnswering',
					    'MvpForSequenceClassification',
					    'MvpModel',
					    'MvpPreTrainedModel',
					]

if TYPE_CHECKING:
					from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
					from .tokenization_mvp import MvpTokenizer

					try:
										if not is_tokenizers_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_mvp_fast import MvpTokenizerFast

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_mvp import (
										    MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    MvpForCausalLM,
										    MvpForConditionalGeneration,
										    MvpForQuestionAnswering,
										    MvpForSequenceClassification,
										    MvpModel,
										    MvpPreTrainedModel,
										)

else:
					import sys

					snake_case_			:     Optional[Any]  	=  _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


