






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      ( A__			):

				"""simple docstring"""




				def        lowercase__     (  self		:					Optional[int]						):

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



class    _UpperCAmelCase      :

				"""simple docstring"""




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

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




				def        lowercase__     (  self		:					str						):

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

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

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




				def        lowercase__     (  self		:					Optional[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        lowercase__     (  self		:					Union[str, Any],						lowerCamelCase		:					List[Any],						lowerCamelCase		:					Tuple,						lowerCamelCase		:					Any						):

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

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




				def        lowercase__     (  self		:					List[Any]						):

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



@require_tf
class    _UpperCAmelCase      ( A__	,A__	,unittest.TestCase			):

				"""simple docstring"""




				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        lowercase__     (  self		:					str						):

								'''simple docstring'''
								lowercase__     				=    TFCvtModelTester(self						)
								lowercase__     				=    TFCvtConfigTester(self,						config_class=lowerCamelCase,						has_text_modality=lowerCamelCase,						hidden_size=37						)




				def        lowercase__     (  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        lowercase__     (  self		:					List[Any]						):

								'''simple docstring'''
								pass




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

								'''simple docstring'''
								pass




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

								'''simple docstring'''
								lowercase__     				=    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        lowercase__     (  self		:					Any						):

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

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

												lowercase__     				=    ['''pixel_values''']
												self.assertListEqual(arg_names[:1],						lowerCamelCase						)




				def        lowercase__     (  self		:					List[str]						):

								'''simple docstring'''
								def check_hidden_states_output(lowerCamelCase		:					List[Any],						lowerCamelCase		:					int,						lowerCamelCase		:					int						):
												lowercase__     				=    model_class(lowerCamelCase						)

												lowercase__     				=    model(**self._prepare_for_class(lowerCamelCase,						lowerCamelCase						)						)
												lowercase__     				=    outputs.hidden_states

												lowercase__     				=    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,
												    ],						)

								lowercase__				,		lowercase__     				=    self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												lowercase__     				=    True
												check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase						)

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

												check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase						)




				def        lowercase__     (  self		:					List[str]						):

								'''simple docstring'''
								lowercase__     				=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase						)




				def        lowercase__     (  self		:					int						):

								'''simple docstring'''
								lowercase__     				=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase						)




				@slow
				def        lowercase__     (  self		:					Any						):

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






def 						a    (		):






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




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

				"""simple docstring"""




				@cached_property
				def        lowercase__     (  self		:					Union[str, Any]						):

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




				@slow
				def        lowercase__     (  self		:					Any						):

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

								lowercase__     				=    self.default_image_processor
								lowercase__     				=    prepare_img()
								lowercase__     				=    image_processor(images=lowerCamelCase,						return_tensors='''tf'''						)

								# forward pass
								lowercase__     				=    model(**lowerCamelCase						)

								# verify the logits
								lowercase__     				=    tf.TensorShape((1, 1_000)						)
								self.assertEqual(outputs.logits.shape,						lowerCamelCase						)

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












from __future__ import annotations

from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class    _UpperCAmelCase      :

				"""simple docstring"""




				lowercase__       							= 42
				lowercase__       							= 42



class    _UpperCAmelCase      :

				"""simple docstring"""




				def __init__(  self		:					str,						lowerCamelCase		:					int						):

								'''simple docstring'''
								lowercase__     				=    [[] for _ in range(lowerCamelCase						)]
								lowercase__     				=    size




				def __getitem__(  self		:					Optional[Any],						lowerCamelCase		:					int						):

								'''simple docstring'''
								return iter(self._graph[vertex]						)




				@property
				def        lowercase__     (  self		:					str						):

								'''simple docstring'''
								return self._size




				def        lowercase__     (  self		:					Union[str, Any],						lowerCamelCase		:					int,						lowerCamelCase		:					int,						lowerCamelCase		:					int						):

								'''simple docstring'''
								if weight not in (0, 1):
												raise ValueError('''Edge weight must be either 0 or 1.'''						)

								if to_vertex < 0 or to_vertex >= self.size:
												raise ValueError('''Vertex indexes must be in [0; size).'''						)

								self._graph[from_vertex].append(Edge(lowerCamelCase,						lowerCamelCase						)						)




				def        lowercase__     (  self		:					Optional[int],						lowerCamelCase		:					int,						lowerCamelCase		:					int						):

								'''simple docstring'''
								lowercase__     				=    deque([start_vertex]						)
								lowercase__     				=    [None] * self.size
								lowercase__     				=    0

								while queue:
												lowercase__     				=    queue.popleft()
												lowercase__     				=    distances[current_vertex]
												if current_distance is None:
																continue

												for edge in self[current_vertex]:
																lowercase__     				=    current_distance + edge.weight
																lowercase__     				=    distances[edge.destination_vertex]
																if (
																    isinstance(lowerCamelCase,						lowerCamelCase						)
																    and new_distance >= dest_vertex_distance
																):
																				continue
																lowercase__     				=    new_distance
																if edge.weight == 0:
																				queue.appendleft(edge.destination_vertex						)
																else:
																				queue.append(edge.destination_vertex						)

								if distances[finish_vertex] is None:
												raise ValueError('''No path from start_vertex to finish_vertex.'''						)

								return distances[finish_vertex]


if __name__ == "__main__":
							import doctest

							doctest.testmod()




