



'''simple docstring'''




from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class     UpperCamelCase_				:





	def __init__(						self	,	A	,	A=3	,	A=32	,	A=3	,	A=10	,	A=[10, 20, 30, 40]	,	A=[1, 1, 2, 1]	,	A=True	,	A=True	,	A="relu"	,	A=3	,	A=None	,	)    ->    Dict:
								UpperCAmelCase  :	int							  =	parent
								UpperCAmelCase  :	Dict							  =	batch_size
								UpperCAmelCase  :	Optional[int]							  =	image_size
								UpperCAmelCase  :	Optional[Any]							  =	num_channels
								UpperCAmelCase  :	str							  =	embeddings_size
								UpperCAmelCase  :	List[Any]							  =	hidden_sizes
								UpperCAmelCase  :	Dict							  =	depths
								UpperCAmelCase  :	Optional[int]							  =	is_training
								UpperCAmelCase  :	Dict							  =	use_labels
								UpperCAmelCase  :	str							  =	hidden_act
								UpperCAmelCase  :	List[str]							  =	num_labels
								UpperCAmelCase  :	int							  =	scope
								UpperCAmelCase  :	Optional[int]							  =	len(A					)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  :	Tuple							  =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

								UpperCAmelCase  :	Optional[Any]							  =	None
								if self.use_labels:
															UpperCAmelCase  :	Optional[Any]							  =	ids_tensor([self.batch_size]	,	self.num_labels					)

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





	def 				_lowercase(						self					)    ->    Any:
								return RegNetConfig(
								    num_channels=self.num_channels	,	embeddings_size=self.embeddings_size	,	hidden_sizes=self.hidden_sizes	,	depths=self.depths	,	hidden_act=self.hidden_act	,	num_labels=self.num_labels	,	)





	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Optional[int]:
								UpperCAmelCase  :	int							  =	TFRegNetModel(config=A					)
								UpperCAmelCase  :	int							  =	model(A	,	training=A					)
								# expected last hidden states: B, C, H // 32, W // 32
								self.parent.assertEqual(
								    result.last_hidden_state.shape	,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)	,	)





	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Union[str, Any]:
								UpperCAmelCase  :	List[str]							  =	self.num_labels
								UpperCAmelCase  :	List[str]							  =	TFRegNetForImageClassification(A					)
								UpperCAmelCase  :	Tuple							  =	model(A	,	labels=A	,	training=A					)
								self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels)					)






	def 				_lowercase(						self					)    ->    List[Any]:
								UpperCAmelCase  :	Optional[int]							  =	self.prepare_config_and_inputs()
								UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	Optional[int]							  =	config_and_inputs
								UpperCAmelCase  :	Optional[Any]							  =	{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_tf
class     UpperCamelCase_				(							__magic_name__   ,  __magic_name__   ,  unittest.TestCase    ):
	lowercase    =				(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
	lowercase    =				(
	    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	lowercase    =				False
	lowercase    =				False
	lowercase    =				False
	lowercase    =				False
	lowercase    =				False





	def 				_lowercase(						self					)    ->    Optional[int]:
								UpperCAmelCase  :	Union[str, Any]							  =	TFRegNetModelTester(self					)
								UpperCAmelCase  :	str							  =	ConfigTester(self	,	config_class=A	,	has_text_modality=A					)





	def 				_lowercase(						self					)    ->    Any:
								return





	@unittest.skip(reason="""RegNet does not use inputs_embeds"""					)
	def 				_lowercase(						self					)    ->    List[Any]:
								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."""	,	)
	@slow
	def 				_lowercase(						self					)    ->    Optional[int]:
								super().test_keras_fit()





	@unittest.skip(reason="""RegNet does not support input and output embeddings"""					)
	def 				_lowercase(						self					)    ->    Optional[Any]:
								pass





	def 				_lowercase(						self					)    ->    Any:
								UpperCAmelCase  ,  UpperCAmelCase  :	Tuple							  =	self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCAmelCase  :	List[str]							  =	["""pixel_values"""]
															self.assertListEqual(arg_names[:1]	,	A					)





	def 				_lowercase(						self					)    ->    List[Any]:
								UpperCAmelCase  :	Union[str, Any]							  =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A					)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								def check_hidden_states_output(A	,	A	,	A					):
															UpperCAmelCase  :	Any							  =	model_class(A					)
															UpperCAmelCase  :	int							  =	model(**self._prepare_for_class(A	,	A					)	,	training=A					)

															UpperCAmelCase  :	List[Any]							  =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															UpperCAmelCase  :	Tuple							  =	self.model_tester.num_stages
															self.assertEqual(len(A					)	,	expected_num_stages + 1					)

															# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]					)	,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2]	,	)

								UpperCAmelCase  ,  UpperCAmelCase  :	Optional[int]							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	int							  =	["""basic""", """bottleneck"""]
								for model_class in self.all_model_classes:
															for layer_type in layers_type:
																						UpperCAmelCase  :	Union[str, Any]							  =	layer_type
																						UpperCAmelCase  :	List[Any]							  =	True
																						check_hidden_states_output(A	,	A	,	A					)

																						# check that output_hidden_states also work using config
																						del inputs_dict["output_hidden_states"]
																						UpperCAmelCase  :	List[Any]							  =	True

																						check_hidden_states_output(A	,	A	,	A					)





	def 				_lowercase(						self					)    ->    Dict:
								UpperCAmelCase  ,  UpperCAmelCase  :	List[Any]							  =	self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(A	,	A	,	A	,	A={}					):
															UpperCAmelCase  :	List[str]							  =	model(A	,	return_dict=A	,	**A					)
															UpperCAmelCase  :	Any							  =	model(A	,	return_dict=A	,	**A					).to_tuple()

															def recursive_check(A	,	A					):
																						if isinstance(A	,	(List, Tuple)					):
																													for tuple_iterable_value, dict_iterable_value in zip(A	,	A					):
																																				recursive_check(A	,	A					)
																						elif tuple_object is None:
																													return
																						else:
																													self.assertTrue(
																													    all(tf.equal(A	,	A					)					)	,	msg=(
																													        """Tuple and dict output are not equal. Difference:"""
																													        f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object					)					)}'''
																													    )	,	)

																						recursive_check(A	,	A					)

								for model_class in self.all_model_classes:
															UpperCAmelCase  :	Union[str, Any]							  =	model_class(A					)

															UpperCAmelCase  :	str							  =	self._prepare_for_class(A	,	A					)
															UpperCAmelCase  :	List[str]							  =	self._prepare_for_class(A	,	A					)
															check_equivalence(A	,	A	,	A					)

															UpperCAmelCase  :	List[str]							  =	self._prepare_for_class(A	,	A	,	return_labels=A					)
															UpperCAmelCase  :	Any							  =	self._prepare_for_class(A	,	A	,	return_labels=A					)
															check_equivalence(A	,	A	,	A					)

															UpperCAmelCase  :	int							  =	self._prepare_for_class(A	,	A					)
															UpperCAmelCase  :	Tuple							  =	self._prepare_for_class(A	,	A					)
															check_equivalence(A	,	A	,	A	,	{"""output_hidden_states""": True}					)

															UpperCAmelCase  :	str							  =	self._prepare_for_class(A	,	A	,	return_labels=A					)
															UpperCAmelCase  :	Optional[int]							  =	self._prepare_for_class(A	,	A	,	return_labels=A					)
															check_equivalence(A	,	A	,	A	,	{"""output_hidden_states""": True}					)





	def 				_lowercase(						self					)    ->    List[str]:
								UpperCAmelCase  :	Optional[int]							  =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*A					)






	@slow
	def 				_lowercase(						self					)    ->    Union[str, Any]:
								for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase  :	Dict							  =	TFRegNetModel.from_pretrained(A					)
															self.assertIsNotNone(A					)




def    __lowerCamelCase						(      )   ->    Optional[int]:
							UpperCAmelCase  :	int							  =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
							return image


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





	@cached_property
	def 				_lowercase(						self					)    ->    Optional[int]:
								return (
								    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
								    if is_vision_available()
								    else None
								)






	@slow
	def 				_lowercase(						self					)    ->    Optional[int]:
								UpperCAmelCase  :	Optional[Any]							  =	TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

								UpperCAmelCase  :	Union[str, Any]							  =	self.default_image_processor
								UpperCAmelCase  :	str							  =	prepare_img()
								UpperCAmelCase  :	str							  =	image_processor(images=A	,	return_tensors="""tf"""					)

								# forward pass
								UpperCAmelCase  :	int							  =	model(**A	,	training=A					)

								# verify the logits
								UpperCAmelCase  :	Optional[int]							  =	tf.TensorShape((1, 1000)					)
								self.assertEqual(outputs.logits.shape	,	A					)

								UpperCAmelCase  :	Union[str, Any]							  =	tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]					)

								tf.debugging.assert_near(outputs.logits[0, :3]	,	A	,	atol=1e-4					)






'''simple docstring'''




import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


a     :    Tuple      						=					False

class     UpperCamelCase_				(							unittest.TestCase    ):
	pass




@slow
@require_torch_gpu
class     UpperCamelCase_				(							unittest.TestCase    ):





	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  :	Any							  =	VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion"""					)
								pipe.to(A					)
								pipe.set_progress_bar_config(disable=A					)

								UpperCAmelCase  :	List[str]							  =	load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""					)
								UpperCAmelCase  :	List[Any]							  =	torch.manual_seed(0					)
								UpperCAmelCase  :	List[str]							  =	pipe(
								    image=A	,	generator=A	,	guidance_scale=7.5	,	num_inference_steps=50	,	output_type="""numpy"""	,	).images

								UpperCAmelCase  :	Tuple							  =	image[0, 253:256, 253:256, -1]

								assert image.shape == (1, 512, 512, 3)
								UpperCAmelCase  :	List[str]							  =	np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5]					)

								assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2

