






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




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dict=	self.config_class(**self.inputs_dict      )
												self.parent.assertTrue(hasattr(snake_case__	,  "embed_dim"      )      )
												self.parent.assertTrue(hasattr(snake_case__	,  "num_heads"      )      )


class    __UpperCAmelCase:




						"""simple docstring"""




						def __init__(       self	,  snake_case__	,  snake_case__=13	,  snake_case__=64	,  snake_case__=3	,  snake_case__=[16, 48, 96]	,  snake_case__=[1, 3, 6]	,  snake_case__=[1, 2, 10]	,  snake_case__=[7, 3, 3]	,  snake_case__=[4, 2, 2]	,  snake_case__=[2, 1, 1]	,  snake_case__=[2, 2, 2]	,  snake_case__=[False, False, True]	,  snake_case__=[0.0, 0.0, 0.0]	,  snake_case__=0.02	,  snake_case__=1e-12	,  snake_case__=True	,  snake_case__=True	,  snake_case__=2	,  ):
												'''simple docstring'''
												lowercase__    :				int=	parent
												lowercase__    :				Dict=	batch_size
												lowercase__    :				Any=	image_size
												lowercase__    :				Dict=	patch_sizes
												lowercase__    :				Tuple=	patch_stride
												lowercase__    :				List[str]=	patch_padding
												lowercase__    :				Any=	is_training
												lowercase__    :				Any=	use_labels
												lowercase__    :				Optional[Any]=	num_labels
												lowercase__    :				Any=	num_channels
												lowercase__    :				int=	embed_dim
												lowercase__    :				Union[str, Any]=	num_heads
												lowercase__    :				str=	stride_kv
												lowercase__    :				Dict=	depth
												lowercase__    :				Dict=	cls_token
												lowercase__    :				str=	attention_drop_rate
												lowercase__    :				str=	initializer_range
												lowercase__    :				List[Any]=	layer_norm_eps




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Tuple=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

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




						def 		UpperCAmelCase_	(       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 		UpperCAmelCase_	(       self	,  snake_case__	,  snake_case__	,  snake_case__      ):
												'''simple docstring'''
												lowercase__    :				str=	TFCvtModel(config=snake_case__      )
												lowercase__    :				str=	model(snake_case__	,  training=snake_case__      )
												lowercase__    :				List[Any]=	(self.image_size, self.image_size)
												lowercase__,     lowercase__    :				str=	image_size[0], image_size[1]
												for i in range(len(self.depth      )      ):
																		lowercase__    :				Any=	floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1      )
																		lowercase__    :				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	,  snake_case__	,  snake_case__	,  snake_case__      ):
												'''simple docstring'''
												lowercase__    :				int=	self.num_labels
												lowercase__    :				List[Any]=	TFCvtForImageClassification(snake_case__      )
												lowercase__    :				List[str]=	model(snake_case__	,  labels=snake_case__	,  training=snake_case__      )
												self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.num_labels)      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				List[Any]=	self.prepare_config_and_inputs()
												lowercase__,     lowercase__,     lowercase__    :				Any=	config_and_inputs
												lowercase__    :				Dict=	{"pixel_values": pixel_values}
												return config, inputs_dict


@require_tf
class    __UpperCAmelCase(       SCREAMING_SNAKE_CASE__  ,  SCREAMING_SNAKE_CASE__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase    	= (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
						__lowerCamelCase    	= (
						    {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
						    if is_tf_available()
						    else {}
						)
						__lowerCamelCase    	= False
						__lowerCamelCase    	= False
						__lowerCamelCase    	= False
						__lowerCamelCase    	= False
						__lowerCamelCase    	= False




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Union[str, Any]=	TFCvtModelTester(self      )
												lowercase__    :				str=	TFCvtConfigTester(self	,  config_class=snake_case__	,  has_text_modality=snake_case__	,  hidden_size=37      )




						def 		UpperCAmelCase_	(       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 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												pass




						@unittest.skip(reason="Cvt does not use inputs_embeds"      )
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												pass




						@unittest.skip(reason="Cvt does not support input and output embeddings"      )
						def 		UpperCAmelCase_	(       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 		UpperCAmelCase_	(       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 		UpperCAmelCase_	(       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 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dict=	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      ):
												'''simple docstring'''
												lowercase__,     lowercase__    :				Union[str, Any]=	self.model_tester.prepare_config_and_inputs_for_common()

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

																		lowercase__    :				Optional[int]=	["pixel_values"]
																		self.assertListEqual(arg_names[:1]	,  snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												def check_hidden_states_output(snake_case__	,  snake_case__	,  snake_case__      ):
																		lowercase__    :				Any=	model_class(snake_case__      )

																		lowercase__    :				Union[str, Any]=	model(**self._prepare_for_class(snake_case__	,  snake_case__      )      )
																		lowercase__    :				Tuple=	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__,     lowercase__    :				int=	self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		lowercase__    :				Tuple=	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__    :				Any=	True

																		check_hidden_states_output(snake_case__	,  snake_case__	,  snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dict=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				List[str]=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*snake_case__      )




						@slow
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		lowercase__    :				Optional[Any]=	TFCvtModel.from_pretrained(snake_case__      )
																		self.assertIsNotNone(snake_case__      )





def 						lowercase__()    ->Dict:




						"""simple docstring"""



						lowercase__    :				Dict=	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
						return image







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




						"""simple docstring"""




						@cached_property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )




						@slow
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Optional[int]=	TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

												lowercase__    :				int=	self.default_image_processor
												lowercase__    :				Tuple=	prepare_img()
												lowercase__    :				Dict=	image_processor(images=snake_case__	,  return_tensors="tf"      )

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

												# verify the logits
												lowercase__    :				Tuple=	tf.TensorShape((1, 1000)      )
												self.assertEqual(outputs.logits.shape	,  snake_case__      )

												lowercase__    :				Optional[int]=	tf.constant([0.92_85, 0.90_15, -0.31_50]      )
												self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()	,  snake_case__	,  atol=1e-4      )      )














"""simple docstring"""







from __future__ import annotations





def 						lowercase__(A						)    ->int:




						"""simple docstring"""



						for i in range(1 ,		len(matrix[0]						)						):
												matrix[0][i] += matrix[0][i - 1]

						# preprocessing the first column
						for i in range(1 ,		len(A						)						):
												matrix[i][0] += matrix[i - 1][0]

						# updating the path cost for current position
						for i in range(1 ,		len(A						)						):
												for j in range(1 ,		len(matrix[0]						)						):
																		matrix[i][j] += min(matrix[i - 1][j] ,		matrix[i][j - 1]						)

						return matrix[-1][-1]


if __name__ == "__main__":
			import doctest

			doctest.testmod()






