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




		"""simple docstring"""





		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.config_class(**self.inputs_dict)
				self.parent.assertTrue(hasattr(lowercase_							,  """embed_dim"""))
				self.parent.assertTrue(hasattr(lowercase_							,  """num_heads"""))



class 						SCREAMING_SNAKE_CASE_ :




		"""simple docstring"""





		def __init__(     self							,  lowerCAmelCase__							,  lowerCAmelCase__=1_3							,  lowerCAmelCase__=6_4							,  lowerCAmelCase__=3							,  lowerCAmelCase__=[1_6, 4_8, 9_6]							,  lowerCAmelCase__=[1, 3, 6]							,  lowerCAmelCase__=[1, 2, 1_0]							,  lowerCAmelCase__=[7, 3, 3]							,  lowerCAmelCase__=[4, 2, 2]							,  lowerCAmelCase__=[2, 1, 1]							,  lowerCAmelCase__=[2, 2, 2]							,  lowerCAmelCase__=[False, False, True]							,  lowerCAmelCase__=[0.0, 0.0, 0.0]							,  lowerCAmelCase__=0.02							,  lowerCAmelCase__=1E-12							,  lowerCAmelCase__=True							,  lowerCAmelCase__=True							,  lowerCAmelCase__=2							,  ):
				__SCREAMING_SNAKE_CASE            = parent
				__SCREAMING_SNAKE_CASE            = batch_size
				__SCREAMING_SNAKE_CASE            = image_size
				__SCREAMING_SNAKE_CASE            = patch_sizes
				__SCREAMING_SNAKE_CASE            = patch_stride
				__SCREAMING_SNAKE_CASE            = patch_padding
				__SCREAMING_SNAKE_CASE            = is_training
				__SCREAMING_SNAKE_CASE            = use_labels
				__SCREAMING_SNAKE_CASE            = num_labels
				__SCREAMING_SNAKE_CASE            = num_channels
				__SCREAMING_SNAKE_CASE            = embed_dim
				__SCREAMING_SNAKE_CASE            = num_heads
				__SCREAMING_SNAKE_CASE            = stride_kv
				__SCREAMING_SNAKE_CASE            = depth
				__SCREAMING_SNAKE_CASE            = cls_token
				__SCREAMING_SNAKE_CASE            = attention_drop_rate
				__SCREAMING_SNAKE_CASE            = initializer_range
				__SCREAMING_SNAKE_CASE            = layer_norm_eps




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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




		def 	snake_case_     (     self):
				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 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = TFCvtModel(config=lowercase_)
				__SCREAMING_SNAKE_CASE            = model(lowercase_							,  training=lowercase_)
				__SCREAMING_SNAKE_CASE            = (self.image_size, self.image_size)
				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = image_size[0], image_size[1]
				for i in range(len(self.depth)):
						__SCREAMING_SNAKE_CASE            = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
						__SCREAMING_SNAKE_CASE            = 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 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.num_labels
				__SCREAMING_SNAKE_CASE            = TFCvtForImageClassification(lowercase_)
				__SCREAMING_SNAKE_CASE            = model(lowercase_							,  labels=lowercase_							,  training=lowercase_)
				self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_labels))




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.prepare_config_and_inputs()
				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = config_and_inputs
				__SCREAMING_SNAKE_CASE            = {"""pixel_values""": pixel_values}
				return config, inputs_dict



@require_tf
class 						SCREAMING_SNAKE_CASE_ (						UpperCamelCase__     ,				UpperCamelCase__     ,				unittest.TestCase ):




		"""simple docstring"""





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




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = TFCvtModelTester(self)
				__SCREAMING_SNAKE_CASE            = TFCvtConfigTester(self							,  config_class=lowercase_							,  has_text_modality=lowercase_							,  hidden_size=3_7)




		def 	snake_case_     (     self):
				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 	snake_case_     (     self):
				pass




		@unittest.skip(reason="""Cvt does not use inputs_embeds""")
		def 	snake_case_     (     self):
				pass




		@unittest.skip(reason="""Cvt does not support input and output embeddings""")
		def 	snake_case_     (     self):
				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 	snake_case_     (     self):
				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 	snake_case_     (     self):
				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 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = tf.keras.mixed_precision.Policy("""mixed_float16""")
				tf.keras.mixed_precision.set_global_policy(lowercase_)
				super().test_keras_fit()
				tf.keras.mixed_precision.set_global_policy("""float32""")




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs_for_common()

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

						__SCREAMING_SNAKE_CASE            = ["""pixel_values"""]
						self.assertListEqual(arg_names[:1]							,  lowercase_)




		def 	snake_case_     (     self):
				def check_hidden_states_output(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
						__SCREAMING_SNAKE_CASE            = model_class(lowercase_)

						__SCREAMING_SNAKE_CASE            = model(**self._prepare_for_class(lowercase_							,  lowercase_))
						__SCREAMING_SNAKE_CASE            = outputs.hidden_states

						__SCREAMING_SNAKE_CASE            = len(self.model_tester.depth)
						self.assertEqual(len(lowercase_)							,  lowercase_)

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

				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						__SCREAMING_SNAKE_CASE            = True
						check_hidden_states_output(lowercase_							,  lowercase_							,  lowercase_)

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

						check_hidden_states_output(lowercase_							,  lowercase_							,  lowercase_)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowercase_)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*lowercase_)




		@slow
		def 	snake_case_     (     self):
				for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__SCREAMING_SNAKE_CASE            = TFCvtModel.from_pretrained(lowercase_)
						self.assertIsNotNone(lowercase_)



def 						_lowerCAmelCase				(				):
		__SCREAMING_SNAKE_CASE            = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				)
		return image
@require_tf
@require_vision
class 						SCREAMING_SNAKE_CASE_ (						unittest.TestCase ):




		"""simple docstring"""





		@cached_property
		def 	snake_case_     (     self):
				return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])




		@slow
		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

				__SCREAMING_SNAKE_CASE            = self.default_image_processor
				__SCREAMING_SNAKE_CASE            = prepare_img()
				__SCREAMING_SNAKE_CASE            = image_processor(images=lowercase_							,  return_tensors="""tf""")

				# forward pass
				__SCREAMING_SNAKE_CASE            = model(**lowercase_)

				# verify the logits
				__SCREAMING_SNAKE_CASE            = tf.TensorShape((1, 1_0_0_0))
				self.assertEqual(outputs.logits.shape							,  lowercase_)

				__SCREAMING_SNAKE_CASE            = tf.constant([0.92_85, 0.90_15, -0.31_50])
				self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()							,  lowercase_							,  atol=1E-4))











'''simple docstring'''

# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.multicontrolnet import MultiControlNetModel  # noqa: F401
from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline  # noqa: F401


deprecate(
    "stable diffusion controlnet",
    "0.22.0",
    "Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.",
    standard_warn=False,
    stacklevel=3,
)



