



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







		'''simple docstring'''





		def    UpperCAmelCase       (      self		:    Dict		)   ->						Tuple:






				"""simple docstring"""



				lowercase__  :       Any												=     self.config_class(**self.inputs_dict		)
				self.parent.assertTrue(hasattr(snake_case__     ,'''embed_dim'''		)		)
				self.parent.assertTrue(hasattr(snake_case__     ,'''num_heads'''		)		)





class 			__A			:







		'''simple docstring'''





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






				"""simple docstring"""



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







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






				"""simple docstring"""



				lowercase__  :       Union[str, Any]												=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

				lowercase__  :       List[str]												=     self.get_config()
				return config, pixel_values, labels







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






				"""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		:    Any     ,_snake_case		:    List[str]     ,_snake_case		:    Tuple     ,_snake_case		:    Any		)   ->						Dict:






				"""simple docstring"""



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






				"""simple docstring"""



				lowercase__  :       Optional[int]												=     self.num_labels
				lowercase__  :       List[Any]												=     TFCvtForImageClassification(snake_case__		)
				lowercase__  :       int												=     model(snake_case__     ,labels=snake_case__     ,training=snake_case__		)
				self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.num_labels)		)







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






				"""simple docstring"""



				lowercase__  :       Dict												=     self.prepare_config_and_inputs()
				lowercase__  :       int												=     config_and_inputs
				lowercase__  :       Tuple												=     {"pixel_values": pixel_values}
				return config, inputs_dict





@require_tf
class 			__A			(      A_	,A_	,unittest.TestCase       ):







		'''simple docstring'''





		lowerCAmelCase     :   str        =							(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
		lowerCAmelCase     :   str        =							(
		    {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
		    if is_tf_available()
		    else {}
		)
		lowerCAmelCase     :   Tuple        =							False
		lowerCAmelCase     :   int        =							False
		lowerCAmelCase     :   Optional[Any]        =							False
		lowerCAmelCase     :   List[Any]        =							False
		lowerCAmelCase     :   Optional[int]        =							False







		def    UpperCAmelCase       (      self		:    Dict		)   ->						int:






				"""simple docstring"""



				lowercase__  :       List[str]												=     TFCvtModelTester(self		)
				lowercase__  :       List[Any]												=     TFCvtConfigTester(self     ,config_class=snake_case__     ,has_text_modality=snake_case__     ,hidden_size=37		)







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






				"""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		:    List[Any]		)   ->						Tuple:






				"""simple docstring"""



				pass







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






				"""simple docstring"""



				pass







		@unittest.skip(reason='''Cvt does not support input and output embeddings'''		)
		def    UpperCAmelCase       (      self		:    Any		)   ->						Optional[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		:    Union[str, Any]		)   ->						List[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		:    Optional[Any]		)   ->						Any:






				"""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		:    Optional[Any]		)   ->						List[str]:






				"""simple docstring"""



				lowercase__  :       Tuple												=     tf.keras.mixed_precision.Policy('''mixed_float16'''		)
				tf.keras.mixed_precision.set_global_policy(snake_case__		)
				super().test_keras_fit()
				tf.keras.mixed_precision.set_global_policy('''float32'''		)







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






				"""simple docstring"""



				lowercase__  :       Dict												=     self.model_tester.prepare_config_and_inputs_for_common()

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

						lowercase__  :       Union[str, Any]												=     ["pixel_values"]
						self.assertListEqual(arg_names[:1]     ,snake_case__		)







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






				"""simple docstring"""



				def check_hidden_states_output(_snake_case		:    Union[str, Any]     ,_snake_case		:    Union[str, Any]     ,_snake_case		:    Tuple		):
						lowercase__  :       Dict												=     model_class(snake_case__		)

						lowercase__  :       Union[str, Any]												=     model(**self._prepare_for_class(snake_case__     ,snake_case__		)		)
						lowercase__  :       Optional[Any]												=     outputs.hidden_states

						lowercase__  :       Optional[int]												=     len(self.model_tester.depth		)
						self.assertEqual(len(snake_case__		)     ,snake_case__		)

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

				lowercase__  :       Optional[int]												=     self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowercase__  :       int												=     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"]
						lowercase__  :       Tuple												=     True

						check_hidden_states_output(snake_case__     ,snake_case__     ,snake_case__		)







		def    UpperCAmelCase       (      self		:    Tuple		)   ->						int:






				"""simple docstring"""



				lowercase__  :       Dict												=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*snake_case__		)







		def    UpperCAmelCase       (      self		:    int		)   ->						int:






				"""simple docstring"""



				lowercase__  :       Tuple												=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*snake_case__		)







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






				"""simple docstring"""



				for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowercase__  :       Optional[int]												=     TFCvtModel.from_pretrained(snake_case__		)
						self.assertIsNotNone(snake_case__		)





def 	__UpperCAmelCase (       )				-> Any:
		lowercase__  :       Any												=     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
		return image





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







		'''simple docstring'''





		@cached_property
		def    UpperCAmelCase       (      self		:    List[Any]		)   ->						Optional[int]:






				"""simple docstring"""



				return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)







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






				"""simple docstring"""



				lowercase__  :       Any												=     TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

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

				# forward pass
				lowercase__  :       Tuple												=     model(**snake_case__		)

				# verify the logits
				lowercase__  :       Optional[Any]												=     tf.TensorShape((1, 1_000)		)
				self.assertEqual(outputs.logits.shape     ,snake_case__		)

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


'''simple docstring'''





import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate







def snake_case_     (					lowercase__		):
  return x + 2






class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def 							UpperCamelCase  (					self		:  Optional[int] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							"x = 3"
   UpperCAmelCase__      :					List[str]				       =							{}
   UpperCAmelCase__      :					Tuple				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3} )

   UpperCAmelCase__      :					Any				       =							"x = y"
   UpperCAmelCase__      :					List[str]				       =							{"y": 5}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 5, "y": 5} )







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



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"y = add_two(x)"
   UpperCAmelCase__      :					Tuple				       =							{"x": 3}
   UpperCAmelCase__      :					Union[str, Any]				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )

   # Won't work without the tool
   with CaptureStdout() as out:
     UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result is None
   assert "tried to execute add_two" in out.out







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							"x = 3"
   UpperCAmelCase__      :					List[Any]				       =							{}
   UpperCAmelCase__      :					Tuple				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3} )







 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"test_dict = {'x': x, 'y': add_two(x)}"
   UpperCAmelCase__      :					List[Any]				       =							{"x": 3}
   UpperCAmelCase__      :					int				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_dict": {"x": 3, "y": 5}} )







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"x = 3\ny = 5"
   UpperCAmelCase__      :					Dict				       =							{}
   UpperCAmelCase__      :					Union[str, Any]				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )







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



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							"text = f'This is x: {x}.'"
   UpperCAmelCase__      :					Dict				       =							{"x": 3}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == "This is x: 3."
   self.assertDictEqual(snake_case__			,				{"x": 3, "text": "This is x: 3."} )







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							"if x <= 3:\n    y = 2\nelse:\n    y = 5"
   UpperCAmelCase__      :					Dict				       =							{"x": 3}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 2
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 2} )

   UpperCAmelCase__      :					Optional[Any]				       =							{"x": 8}
   UpperCAmelCase__      :					str				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 8, "y": 5} )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							"test_list = [x, add_two(x)]"
   UpperCAmelCase__      :					Any				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   self.assertListEqual(snake_case__			,				[3, 5] )
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_list": [3, 5]} )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							"y = x"
   UpperCAmelCase__      :					str				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 3} )







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							"test_list = [x, add_two(x)]\ntest_list[1]"
   UpperCAmelCase__      :					List[Any]				       =							{"x": 3}
   UpperCAmelCase__      :					List[Any]				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_list": [3, 5]} )

   UpperCAmelCase__      :					Union[str, Any]				       =							"test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
   UpperCAmelCase__      :					str				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_dict": {"x": 3, "y": 5}} )







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



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							"x = 0\nfor i in range(3):\n    x = i"
   UpperCAmelCase__      :					List[Any]				       =							{}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"range": range}			,				state=snake_case__ )
   assert result == 2
   self.assertDictEqual(snake_case__			,				{"x": 2, "i": 2} )



