
"""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    _UpperCAmelCase(   lowerCamelCase     ):



		def 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  self.config_class(**self.inputs_dict)
							self.parent.assertTrue(hasattr(__a    ,		'''embed_dim'''))
							self.parent.assertTrue(hasattr(__a    ,		'''num_heads'''))






class    _UpperCAmelCase:



		def __init__( self    ,		__a    ,		__a=13    ,		__a=64    ,		__a=3    ,		__a=[16, 48, 96]    ,		__a=[1, 3, 6]    ,		__a=[1, 2, 10]    ,		__a=[7, 3, 3]    ,		__a=[4, 2, 2]    ,		__a=[2, 1, 1]    ,		__a=[2, 2, 2]    ,		__a=[False, False, True]    ,		__a=[0.0, 0.0, 0.0]    ,		__a=0.02    ,		__a=1e-12    ,		__a=True    ,		__a=True    ,		__a=2    ,		)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  parent
							_UpperCamelCase										=  batch_size
							_UpperCamelCase										=  image_size
							_UpperCamelCase										=  patch_sizes
							_UpperCamelCase										=  patch_stride
							_UpperCamelCase										=  patch_padding
							_UpperCamelCase										=  is_training
							_UpperCamelCase										=  use_labels
							_UpperCamelCase										=  num_labels
							_UpperCamelCase										=  num_channels
							_UpperCamelCase										=  embed_dim
							_UpperCamelCase										=  num_heads
							_UpperCamelCase										=  stride_kv
							_UpperCamelCase										=  depth
							_UpperCamelCase										=  cls_token
							_UpperCamelCase										=  attention_drop_rate
							_UpperCamelCase										=  initializer_range
							_UpperCamelCase										=  layer_norm_eps



		def 						UpperCAmelCase							( self)	->	Union[str, Any]:






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

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

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



		def 						UpperCAmelCase							( self)	->	int:






							'''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    ,		__a    ,		__a    ,		__a)	->	List[Any]:






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






							'''simple docstring'''
							_UpperCamelCase										=  self.num_labels
							_UpperCamelCase										=  TFCvtForImageClassification(__a)
							_UpperCamelCase										=  model(__a    ,		labels=__a    ,		training=__a)
							self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.num_labels))




		def 						UpperCAmelCase							( self)	->	Any:






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






@require_tf
class    _UpperCAmelCase(   lowerCamelCase				,					lowerCamelCase				,					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)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  TFCvtModelTester(self)
							_UpperCamelCase										=  TFCvtConfigTester(self    ,		config_class=__a    ,		has_text_modality=__a    ,		hidden_size=37)



		def 						UpperCAmelCase							( self)	->	Union[str, 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)	->	Union[str, Any]:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''Cvt does not use inputs_embeds''')
		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							pass



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






							'''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)	->	Tuple:






							'''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)	->	List[str]:






							'''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)	->	Dict:






							'''simple docstring'''
							_UpperCamelCase										=  tf.keras.mixed_precision.Policy('''mixed_float16''')
							tf.keras.mixed_precision.set_global_policy(__a)
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy('''float32''')



		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							_UpperCamelCase			,  _UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()

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

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



		def 						UpperCAmelCase							( self)	->	Optional[int]:






							'''simple docstring'''
							def check_hidden_states_output(__a    ,		__a    ,		__a):
												_UpperCamelCase										=  model_class(__a)

												_UpperCamelCase										=  model(**self._prepare_for_class(__a    ,		__a))
												_UpperCamelCase										=  outputs.hidden_states

												_UpperCamelCase										=  len(self.model_tester.depth)
												self.assertEqual(len(__a)    ,		__a)

												# 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										=  self.model_tester.prepare_config_and_inputs_for_common()

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

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

												check_hidden_states_output(__a    ,		__a    ,		__a)



		def 						UpperCAmelCase							( self)	->	Optional[int]:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__a)



		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__a)




		@slow
		def 						UpperCAmelCase							( self)	->	Tuple:






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





def 				lowerCamelCase__		(      )							->		Tuple:


					"""simple docstring"""





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






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



		@cached_property
		def 						UpperCAmelCase							( self)	->	Tuple:






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




		@slow
		def 						UpperCAmelCase							( self)	->	Dict:






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

							_UpperCamelCase										=  self.default_image_processor
							_UpperCamelCase										=  prepare_img()
							_UpperCamelCase										=  image_processor(images=__a    ,		return_tensors='''tf''')

							# forward pass
							_UpperCamelCase										=  model(**__a)

							# verify the logits
							_UpperCamelCase										=  tf.TensorShape((1, 10_00))
							self.assertEqual(outputs.logits.shape    ,		__a)

							_UpperCamelCase										=  tf.constant([0.9285, 0.9015, -0.3150])
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,		__a    ,		atol=1e-4))








"""simple docstring"""





import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402


_a														=		get_tests_dir("""fixtures/dummy-config.json""")






class    _UpperCAmelCase(   unittest.TestCase     ):



		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							_UpperCamelCase										=  0



		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							self.assertIsNotNone(transformers.models.auto.__spec__)
							self.assertIsNotNone(importlib.util.find_spec('''transformers.models.auto'''))



		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							_UpperCamelCase										=  AutoConfig.from_pretrained('''bert-base-uncased''')
							self.assertIsInstance(__a    ,		__a)



		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  AutoConfig.from_pretrained(__a)
							self.assertIsInstance(__a    ,		__a)



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  AutoConfig.from_pretrained(__a)
							self.assertIsInstance(__a    ,		__a)



		def 						UpperCAmelCase							( self)	->	Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase										=  AutoConfig.for_model('''roberta''')
							self.assertIsInstance(__a    ,		__a)



		def 						UpperCAmelCase							( self)	->	Dict:






							'''simple docstring'''
							with tempfile.TemporaryDirectory() as tmp_dir:
												# This model name contains bert and roberta, but roberta ends up being picked.
												_UpperCamelCase										=  os.path.join(__a    ,		'''fake-roberta''')
												os.makedirs(__a    ,		exist_ok=__a)
												with open(os.path.join(__a    ,		'''config.json''')    ,		'''w''') as f:
																	f.write(json.dumps({}))
												_UpperCamelCase										=  AutoConfig.from_pretrained(__a)
												self.assertEqual(type(__a)    ,		__a)



		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							try:
												AutoConfig.register('''custom'''    ,		__a)
												# Wrong model type will raise an error
												with self.assertRaises(__a):
																	AutoConfig.register('''model'''    ,		__a)
												# Trying to register something existing in the Transformers library will raise an error
												with self.assertRaises(__a):
																	AutoConfig.register('''bert'''    ,		__a)

												# Now that the config is registered, it can be used as any other config with the auto-API
												_UpperCamelCase										=  CustomConfig()
												with tempfile.TemporaryDirectory() as tmp_dir:
																	config.save_pretrained(__a)
																	_UpperCamelCase										=  AutoConfig.from_pretrained(__a)
																	self.assertIsInstance(__a    ,		__a)

							finally:
												if "custom" in CONFIG_MAPPING._extra_content:
																	del CONFIG_MAPPING._extra_content["custom"]



		def 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							with self.assertRaisesRegex(
							    __a    ,		'''bert-base is not a local folder and is not a valid model identifier'''):
												_UpperCamelCase										=  AutoConfig.from_pretrained('''bert-base''')



		def 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							with self.assertRaisesRegex(
							    __a    ,		R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
												_UpperCamelCase										=  AutoConfig.from_pretrained(__a    ,		revision='''aaaaaa''')



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							with self.assertRaisesRegex(
							    __a    ,		'''hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'''    ,		):
												_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/no-config-test-repo''')



		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							# If remote code is not set, we will time out when asking whether to load the model.
							with self.assertRaises(__a):
												_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''')
							# If remote code is disabled, we can't load this config.
							with self.assertRaises(__a):
												_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''    ,		trust_remote_code=__a)

							_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''    ,		trust_remote_code=__a)
							self.assertEqual(config.__class__.__name__    ,		'''NewModelConfig''')

							# Test config can be reloaded.
							with tempfile.TemporaryDirectory() as tmp_dir:
												config.save_pretrained(__a)
												_UpperCamelCase										=  AutoConfig.from_pretrained(__a    ,		trust_remote_code=__a)
							self.assertEqual(reloaded_config.__class__.__name__    ,		'''NewModelConfig''')




		def 						UpperCAmelCase							( self)	->	Any:






							'''simple docstring'''






							class    _UpperCAmelCase(   lowerCamelCase     ):
									lowercase__      =				'new-model'

							try:
												AutoConfig.register('''new-model'''    ,		__a)
												# If remote code is not set, the default is to use local
												_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''')
												self.assertEqual(config.__class__.__name__    ,		'''NewModelConfigLocal''')

												# If remote code is disabled, we load the local one.
												_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''    ,		trust_remote_code=__a)
												self.assertEqual(config.__class__.__name__    ,		'''NewModelConfigLocal''')

												# If remote is enabled, we load from the Hub
												_UpperCamelCase										=  AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''    ,		trust_remote_code=__a)
												self.assertEqual(config.__class__.__name__    ,		'''NewModelConfig''')

							finally:
												if "new-model" in CONFIG_MAPPING._extra_content:
																	del CONFIG_MAPPING._extra_content["new-model"]






