





from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
					from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor


class 					__a      :

							def __init__(							self							:     Tuple       ,     __magic_name__							:     str       ,     __magic_name__							:     List[str]=3       ,     __magic_name__							:     Optional[Any]=32       ,     __magic_name__							:     Optional[Any]=3       ,     __magic_name__							:     str=10       ,     __magic_name__							:     Optional[int]=[10, 20, 30, 40]       ,     __magic_name__							:     Optional[Any]=[1, 1, 2, 1]       ,     __magic_name__							:     List[str]=True       ,     __magic_name__							:     Optional[int]=True       ,     __magic_name__							:     Any="relu"       ,     __magic_name__							:     Any=3       ,     __magic_name__							:     List[str]=None       ,     )					->       Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[Any]     						=  parent
													UpperCAmelCase_			:      Any     						=  batch_size
													UpperCAmelCase_			:      Optional[int]     						=  image_size
													UpperCAmelCase_			:      Union[str, Any]     						=  num_channels
													UpperCAmelCase_			:      Tuple     						=  embeddings_size
													UpperCAmelCase_			:      Optional[Any]     						=  hidden_sizes
													UpperCAmelCase_			:      Union[str, Any]     						=  depths
													UpperCAmelCase_			:      Optional[Any]     						=  is_training
													UpperCAmelCase_			:      Optional[int]     						=  use_labels
													UpperCAmelCase_			:      Tuple     						=  hidden_act
													UpperCAmelCase_			:      Any     						=  num_labels
													UpperCAmelCase_			:      Dict     						=  scope
													UpperCAmelCase_			:      Union[str, Any]     						=  len(__A   )

							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       str:







													"""simple docstring"""
													UpperCAmelCase_			:      List[str]     						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

													UpperCAmelCase_			:      int     						=  self.get_config()

													return config, pixel_values, labels

							def     UpperCAmelCase__	(							self							:     List[str]   )					->       int:







													"""simple docstring"""
													return ResNetConfig(
													    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       ,     image_size=self.image_size       ,     )

							def     UpperCAmelCase__	(							self							:     Optional[Any]       ,     __magic_name__							:     Union[str, Any]       ,     __magic_name__							:     Union[str, Any]       ,     __magic_name__							:     Any   )					->       Tuple:







													"""simple docstring"""
													UpperCAmelCase_			:      int     						=  TFResNetModel(config=__A   )
													UpperCAmelCase_			:      str     						=  model(__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     UpperCAmelCase__	(							self							:     Optional[Any]       ,     __magic_name__							:     Union[str, Any]       ,     __magic_name__							:     Any       ,     __magic_name__							:     Any   )					->       Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[Any]     						=  self.num_labels
													UpperCAmelCase_			:      str     						=  TFResNetForImageClassification(__A   )
													UpperCAmelCase_			:      str     						=  model(__A       ,     labels=__A   )
													self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)   )



							def     UpperCAmelCase__	(							self							:     Optional[Any]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[int]     						=  self.prepare_config_and_inputs()
													UpperCAmelCase_						,       UpperCAmelCase_						,       UpperCAmelCase_			:      int     						=  config_and_inputs
													UpperCAmelCase_			:      Union[str, Any]     						=  {'''pixel_values''': pixel_values}
													return config, inputs_dict





@require_tf
class 					__a      (__lowercase       ,		__lowercase       ,		unittest.TestCase     ):
							__a					:   Optional[int]									=       (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
							__a					:   List[Any]									=       (
							    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
							    if is_tf_available()
							    else {}
							)

							__a					:   List[str]									=       False
							__a					:   Optional[Any]									=       False
							__a					:   List[str]									=       False
							__a					:   Union[str, Any]									=       False
							__a					:   List[str]									=       False

							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  TFResNetModelTester(self   )
													UpperCAmelCase_			:      Dict     						=  ConfigTester(self       ,     config_class=__A       ,     has_text_modality=__A   )

							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       str:







													"""simple docstring"""
													self.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()

							def     UpperCAmelCase__	(							self							:     str   )					->       Optional[Any]:







													"""simple docstring"""
													return

							@unittest.skip(reason='''ResNet does not use inputs_embeds'''   )
							def     UpperCAmelCase__	(							self							:     Any   )					->       Union[str, Any]:







													"""simple docstring"""
													pass

							@unittest.skip(reason='''ResNet does not support input and output embeddings'''   )
							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       str:







													"""simple docstring"""
													pass

							def     UpperCAmelCase__	(							self							:     int   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_						,       UpperCAmelCase_			:      int     						=  self.model_tester.prepare_config_and_inputs_for_common()

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

																			UpperCAmelCase_			:      Any     						=  ['''pixel_values''']
																			self.assertListEqual(arg_names[:1]       ,     __A   )

							def     UpperCAmelCase__	(							self							:     Dict   )					->       Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[str]     						=  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__A   )

							def     UpperCAmelCase__	(							self							:     List[str]   )					->       Union[str, Any]:







													"""simple docstring"""
													def check_hidden_states_output(__magic_name__							:     str       ,     __magic_name__							:     Dict       ,     __magic_name__							:     Union[str, Any]   ):
																			UpperCAmelCase_			:      List[Any]     						=  model_class(__A   )
																			UpperCAmelCase_			:      str     						=  model(**self._prepare_for_class(__A       ,     __A   )   )

																			UpperCAmelCase_			:      Any     						=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																			UpperCAmelCase_			:      Union[str, Any]     						=  self.model_tester.num_stages
																			self.assertEqual(len(__A   )       ,     expected_num_stages + 1   )

																			# ResNet'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 // 4, self.model_tester.image_size // 4]       ,     )

													UpperCAmelCase_						,       UpperCAmelCase_			:      Optional[int]     						=  self.model_tester.prepare_config_and_inputs_for_common()
													UpperCAmelCase_			:      Union[str, Any]     						=  ['''basic''', '''bottleneck''']
													for model_class in self.all_model_classes:
																			for layer_type in layers_type:
																									UpperCAmelCase_			:      Union[str, Any]     						=  layer_type
																									UpperCAmelCase_			:      Optional[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     UpperCAmelCase__	(							self							:     List[str]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      int     						=  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*__A   )



							@slow
							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       str:







													"""simple docstring"""
													for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			UpperCAmelCase_			:      Union[str, Any]     						=  TFResNetModel.from_pretrained(__A   )
																			self.assertIsNotNone(__A   )





def        lowerCamelCase_      (  ) ->	Dict:
						UpperCAmelCase_			:      List[Any]     						=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
						return image


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

							@cached_property
							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       Dict:







													"""simple docstring"""
													return (
													    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
													    if is_vision_available()
													    else None
													)



							@slow
							def     UpperCAmelCase__	(							self							:     Optional[int]   )					->       Optional[int]:







													"""simple docstring"""
													UpperCAmelCase_			:      Any     						=  TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

													UpperCAmelCase_			:      Any     						=  self.default_image_processor
													UpperCAmelCase_			:      Dict     						=  prepare_img()
													UpperCAmelCase_			:      Tuple     						=  image_processor(images=__A       ,     return_tensors='''tf'''   )

													# forward pass
													UpperCAmelCase_			:      Optional[int]     						=  model(**__A   )

													# verify the logits
													UpperCAmelCase_			:      int     						=  tf.TensorShape((1, 10_00)   )
													self.assertEqual(outputs.logits.shape       ,     __A   )

													UpperCAmelCase_			:      int     						=  tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]   )

													self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()       ,     __A       ,     atol=1E-4   )   )












'''simple docstring'''







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


snake_case_     :       List[str]						=  False


class 					__a      (unittest.TestCase     ):
							pass





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

							def     UpperCAmelCase__	(							self							:     int   )					->       str:







													"""simple docstring"""
													# clean up the VRAM after each test
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()

							def     UpperCAmelCase__	(							self							:     List[str]   )					->       List[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Tuple     						=  VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''       ,     torch_dtype=torch.floataa   )
													pipe.to(__magic_name__   )
													pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      List[Any]     						=  load_image(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''   )

													UpperCAmelCase_			:      Optional[int]     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      Union[str, Any]     						=  pipe.dual_guided(
													    prompt='''first prompt'''       ,     image=__magic_name__       ,     text_to_image_strength=0.7_5       ,     generator=__magic_name__       ,     guidance_scale=7.5       ,     num_inference_steps=2       ,     output_type='''numpy'''       ,     ).images

													with tempfile.TemporaryDirectory() as tmpdirname:
																			pipe.save_pretrained(__magic_name__   )
																			UpperCAmelCase_			:      Optional[int]     						=  VersatileDiffusionPipeline.from_pretrained(__magic_name__       ,     torch_dtype=torch.floataa   )
													pipe.to(__magic_name__   )
													pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Any     						=  generator.manual_seed(0   )
													UpperCAmelCase_			:      Dict     						=  pipe.dual_guided(
													    prompt='''first prompt'''       ,     image=__magic_name__       ,     text_to_image_strength=0.7_5       ,     generator=__magic_name__       ,     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     UpperCAmelCase__	(							self							:     str   )					->       Optional[int]:







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''       ,     torch_dtype=torch.floataa   )
													pipe.to(__magic_name__   )
													pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Union[str, Any]     						=  '''cyberpunk 2077'''
													UpperCAmelCase_			:      Union[str, Any]     						=  load_image(
													    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''   )
													UpperCAmelCase_			:      Tuple     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[Any]     						=  pipe.dual_guided(
													    prompt=__magic_name__       ,     image=__magic_name__       ,     text_to_image_strength=0.7_5       ,     generator=__magic_name__       ,     guidance_scale=7.5       ,     num_inference_steps=50       ,     output_type='''numpy'''       ,     ).images

													UpperCAmelCase_			:      List[str]     						=  image[0, 2_53:2_56, 2_53:2_56, -1]

													assert image.shape == (1, 5_12, 5_12, 3)
													UpperCAmelCase_			:      Union[str, Any]     						=  np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1]   )

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

													UpperCAmelCase_			:      Tuple     						=  '''A painting of a squirrel eating a burger '''
													UpperCAmelCase_			:      Optional[int]     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      List[Any]     						=  pipe.text_to_image(
													    prompt=__magic_name__       ,     generator=__magic_name__       ,     guidance_scale=7.5       ,     num_inference_steps=50       ,     output_type='''numpy'''   ).images

													UpperCAmelCase_			:      Tuple     						=  image[0, 2_53:2_56, 2_53:2_56, -1]

													assert image.shape == (1, 5_12, 5_12, 3)
													UpperCAmelCase_			:      Any     						=  np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8]   )

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

													UpperCAmelCase_			:      Tuple     						=  pipe.image_variation(__magic_name__       ,     generator=__magic_name__       ,     output_type='''numpy'''   ).images

													UpperCAmelCase_			:      Optional[Any]     						=  image[0, 2_53:2_56, 2_53:2_56, -1]

													assert image.shape == (1, 5_12, 5_12, 3)
													UpperCAmelCase_			:      List[str]     						=  np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6]   )

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





