





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 							__SCREAMING_SNAKE_CASE       :






							def __init__(    self	,			__lowerCAmelCase	,			__lowerCAmelCase=3	,			__lowerCAmelCase=32	,			__lowerCAmelCase=3	,			__lowerCAmelCase=10	,			__lowerCAmelCase=[10, 20, 30, 40]	,			__lowerCAmelCase=[1, 1, 2, 1]	,			__lowerCAmelCase=True	,			__lowerCAmelCase=True	,			__lowerCAmelCase="relu"	,			__lowerCAmelCase=3	,			__lowerCAmelCase=None	,			):
														UpperCamelCase__					  =      parent
														UpperCamelCase__					  =      batch_size
														UpperCamelCase__					  =      image_size
														UpperCamelCase__					  =      num_channels
														UpperCamelCase__					  =      embeddings_size
														UpperCamelCase__					  =      hidden_sizes
														UpperCamelCase__					  =      depths
														UpperCamelCase__					  =      is_training
														UpperCamelCase__					  =      use_labels
														UpperCamelCase__					  =      hidden_act
														UpperCamelCase__					  =      num_labels
														UpperCamelCase__					  =      scope
														UpperCamelCase__					  =      len(__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

														UpperCamelCase__					  =      None
														if self.use_labels:
																					UpperCamelCase__					  =      ids_tensor([self.batch_size]	,			self.num_labels	)

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






							def 					_lowerCamelCase		(    self	):
														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 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	):
														UpperCamelCase__					  =      TFRegNetModel(config=__lowerCAmelCase	)
														UpperCamelCase__					  =      model(__lowerCAmelCase	,			training=__lowerCAmelCase	)
														# 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 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	):
														UpperCamelCase__					  =      self.num_labels
														UpperCamelCase__					  =      TFRegNetForImageClassification(__lowerCAmelCase	)
														UpperCamelCase__					  =      model(__lowerCAmelCase	,			labels=__lowerCAmelCase	,			training=__lowerCAmelCase	)
														self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)	)







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






@require_tf
class 							__SCREAMING_SNAKE_CASE       (  _a ,		_a ,		unittest.TestCase							):
							snake_case  :   str      =							(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
							snake_case  :   Any      =							(
							    {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
							    if is_tf_available()
							    else {}
							)

							snake_case  :   Any      =							False
							snake_case  :   List[str]      =							False
							snake_case  :   List[str]      =							False
							snake_case  :   str      =							False
							snake_case  :   Tuple      =							False






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      TFRegNetModelTester(self	)
														UpperCamelCase__					  =      ConfigTester(self	,			config_class=__lowerCAmelCase	,			has_text_modality=__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														return






							@unittest.skip(reason="""RegNet does not use inputs_embeds"""	)
							def 					_lowerCamelCase		(    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."""	,			)
							@slow
							def 					_lowerCamelCase		(    self	):
														super().test_keras_fit()






							@unittest.skip(reason="""RegNet does not support input and output embeddings"""	)
							def 					_lowerCamelCase		(    self	):
														pass






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__  ,  UpperCamelCase__					  =      self.model_tester.prepare_config_and_inputs_for_common()

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

																					UpperCamelCase__					  =      ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]	,			__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														def check_hidden_states_output(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	):
																					UpperCamelCase__					  =      model_class(__lowerCAmelCase	)
																					UpperCamelCase__					  =      model(**self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	)	,			training=__lowerCAmelCase	)

																					UpperCamelCase__					  =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																					UpperCamelCase__					  =      self.model_tester.num_stages
																					self.assertEqual(len(__lowerCAmelCase	)	,			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__					  =      self.model_tester.prepare_config_and_inputs_for_common()
														UpperCamelCase__					  =      ["""basic""", """bottleneck"""]
														for model_class in self.all_model_classes:
																					for layer_type in layers_type:
																												UpperCamelCase__					  =      layer_type
																												UpperCamelCase__					  =      True
																												check_hidden_states_output(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	)

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

																												check_hidden_states_output(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__  ,  UpperCamelCase__					  =      self.model_tester.prepare_config_and_inputs_for_common()

														def check_equivalence(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase={}	):
																					UpperCamelCase__					  =      model(__lowerCAmelCase	,			return_dict=__lowerCAmelCase	,			**__lowerCAmelCase	)
																					UpperCamelCase__					  =      model(__lowerCAmelCase	,			return_dict=__lowerCAmelCase	,			**__lowerCAmelCase	).to_tuple()

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

																												recursive_check(__lowerCAmelCase	,			__lowerCAmelCase	)

														for model_class in self.all_model_classes:
																					UpperCamelCase__					  =      model_class(__lowerCAmelCase	)

																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	)
																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	)
																					check_equivalence(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	)

																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	,			return_labels=__lowerCAmelCase	)
																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	,			return_labels=__lowerCAmelCase	)
																					check_equivalence(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	)

																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	)
																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	)
																					check_equivalence(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	,			{"""output_hidden_states""": True}	)

																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	,			return_labels=__lowerCAmelCase	)
																					UpperCamelCase__					  =      self._prepare_for_class(__lowerCAmelCase	,			__lowerCAmelCase	,			return_labels=__lowerCAmelCase	)
																					check_equivalence(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	,			{"""output_hidden_states""": True}	)






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase	)







							@slow
							def 					_lowerCamelCase		(    self	):
														for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					UpperCamelCase__					  =      TFRegNetModel.from_pretrained(__lowerCAmelCase	)
																					self.assertIsNotNone(__lowerCAmelCase	)






def      _UpperCamelCase  ():






							"""simple docstring"""





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

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






							@cached_property
							def 					_lowerCamelCase		(    self	):
														return (
														    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
														    if is_vision_available()
														    else None
														)







							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

														UpperCamelCase__					  =      self.default_image_processor
														UpperCamelCase__					  =      prepare_img()
														UpperCamelCase__					  =      image_processor(images=__lowerCAmelCase	,			return_tensors="""tf"""	)

														# forward pass
														UpperCamelCase__					  =      model(**__lowerCAmelCase	,			training=__lowerCAmelCase	)

														# verify the logits
														UpperCamelCase__					  =      tf.TensorShape((1, 1000)	)
														self.assertEqual(outputs.logits.shape	,			__lowerCAmelCase	)

														UpperCamelCase__					  =      tf.constant([-0.4180, -1.5051, -3.4836]	)

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











import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


UpperCamelCase__           =			False

class 							__SCREAMING_SNAKE_CASE       (  unittest.TestCase							):
							pass






@nightly
@require_torch_gpu
class 							__SCREAMING_SNAKE_CASE       (  unittest.TestCase							):






							def 					_lowerCamelCase		(    self	):
														# clean up the VRAM after each test
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      VersatileDiffusionTextToImagePipeline.from_pretrained("""shi-labs/versatile-diffusion"""	)
														# remove text_unet
														pipe.remove_unused_weights()
														pipe.to(__lowerCAmelCase	)
														pipe.set_progress_bar_config(disable=__lowerCAmelCase	)

														UpperCamelCase__					  =      """A painting of a squirrel eating a burger """
														UpperCamelCase__					  =      torch.manual_seed(0	)
														UpperCamelCase__					  =      pipe(
														    prompt=__lowerCAmelCase	,			generator=__lowerCAmelCase	,			guidance_scale=7.5	,			num_inference_steps=2	,			output_type="""numpy"""	).images

														with tempfile.TemporaryDirectory() as tmpdirname:
																					pipe.save_pretrained(__lowerCAmelCase	)
																					UpperCamelCase__					  =      VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCAmelCase	)
														pipe.to(__lowerCAmelCase	)
														pipe.set_progress_bar_config(disable=__lowerCAmelCase	)

														UpperCamelCase__					  =      generator.manual_seed(0	)
														UpperCamelCase__					  =      pipe(
														    prompt=__lowerCAmelCase	,			generator=__lowerCAmelCase	,			guidance_scale=7.5	,			num_inference_steps=2	,			output_type="""numpy"""	).images

														assert np.abs(image - new_image	).sum() < 1E-5, "Models don't have the same forward pass"







							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      VersatileDiffusionTextToImagePipeline.from_pretrained(
														    """shi-labs/versatile-diffusion"""	,			torch_dtype=torch.floataa	)
														pipe.to(__lowerCAmelCase	)
														pipe.set_progress_bar_config(disable=__lowerCAmelCase	)

														UpperCamelCase__					  =      """A painting of a squirrel eating a burger """
														UpperCamelCase__					  =      torch.manual_seed(0	)
														UpperCamelCase__					  =      pipe(
														    prompt=__lowerCAmelCase	,			generator=__lowerCAmelCase	,			guidance_scale=7.5	,			num_inference_steps=50	,			output_type="""numpy"""	).images

														UpperCamelCase__					  =      image[0, 253:256, 253:256, -1]

														assert image.shape == (1, 512, 512, 3)
														UpperCamelCase__					  =      np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]	)

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




