
import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionInstructPixaPixPipeline,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()





class       __A(				__lowerCamelCase     ,		__lowerCamelCase     ,		__lowerCamelCase     ,		unittest.TestCase       ):
					SCREAMING_SNAKE_CASE			    =    StableDiffusionInstructPixaPixPipeline
					SCREAMING_SNAKE_CASE			    =    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'}
					SCREAMING_SNAKE_CASE			    =    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
					SCREAMING_SNAKE_CASE			    =    IMAGE_TO_IMAGE_IMAGE_PARAMS
					SCREAMING_SNAKE_CASE			    =    IMAGE_TO_IMAGE_IMAGE_PARAMS

					def    lowercase__      (	self					:     int   ):
												torch.manual_seed(0   )
												lowerCamelCase_							  =					UNetaDConditionModel(
												    block_out_channels=(3_2, 6_4)   ,					layers_per_block=2   ,					sample_size=3_2   ,					in_channels=8   ,					out_channels=4   ,					down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")   ,					up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")   ,					cross_attention_dim=3_2   ,					)
												lowerCamelCase_							  =					PNDMScheduler(skip_prk_steps=UpperCamelCase_   )
												torch.manual_seed(0   )
												lowerCamelCase_							  =					AutoencoderKL(
												    block_out_channels=[3_2, 6_4]   ,					in_channels=3   ,					out_channels=3   ,					down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]   ,					up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]   ,					latent_channels=4   ,					)
												torch.manual_seed(0   )
												lowerCamelCase_							  =					CLIPTextConfig(
												    bos_token_id=0   ,					eos_token_id=2   ,					hidden_size=3_2   ,					intermediate_size=3_7   ,					layer_norm_eps=1E-05   ,					num_attention_heads=4   ,					num_hidden_layers=5   ,					pad_token_id=1   ,					vocab_size=1_0_0_0   ,					)
												lowerCamelCase_							  =					CLIPTextModel(UpperCamelCase_   )
												lowerCamelCase_							  =					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

												lowerCamelCase_							  =					{
												    """unet""": unet,
												    """scheduler""": scheduler,
												    """vae""": vae,
												    """text_encoder""": text_encoder,
												    """tokenizer""": tokenizer,
												    """safety_checker""": None,
												    """feature_extractor""": None,
												}
												return components

					def    lowercase__      (	self					:     List[Any]   ,					__UpperCamelCase					:     List[Any]   ,					__UpperCamelCase					:     List[str]=0   ):
												lowerCamelCase_							  =					floats_tensor((1, 3, 3_2, 3_2)   ,					rng=random.Random(UpperCamelCase_   )   ).to(UpperCamelCase_   )
												lowerCamelCase_							  =					image.cpu().permute(0   ,					2   ,					3   ,					1   )[0]
												lowerCamelCase_							  =					Image.fromarray(np.uinta(UpperCamelCase_   )   ).convert("""RGB"""   )
												if str(UpperCamelCase_   ).startswith("""mps"""   ):
																			lowerCamelCase_							  =					torch.manual_seed(UpperCamelCase_   )
												else:
																			lowerCamelCase_							  =					torch.Generator(device=UpperCamelCase_   ).manual_seed(UpperCamelCase_   )
												lowerCamelCase_							  =					{
												    """prompt""": """A painting of a squirrel eating a burger""",
												    """image""": image,
												    """generator""": generator,
												    """num_inference_steps""": 2,
												    """guidance_scale""": 6.0,
												    """image_guidance_scale""": 1,
												    """output_type""": """numpy""",
												}
												return inputs

					def    lowercase__      (	self					:     Optional[Any]   ):
												lowerCamelCase_							  =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
												lowerCamelCase_							  =					self.get_dummy_components()
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline(**UpperCamelCase_   )
												lowerCamelCase_							  =					sd_pipe.to(UpperCamelCase_   )
												sd_pipe.set_progress_bar_config(disable=UpperCamelCase_   )

												lowerCamelCase_							  =					self.get_dummy_inputs(UpperCamelCase_   )
												lowerCamelCase_							  =					sd_pipe(**UpperCamelCase_   ).images
												lowerCamelCase_							  =					image[0, -3:, -3:, -1]
												assert image.shape == (1, 3_2, 3_2, 3)
												lowerCamelCase_							  =					np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815]   )

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

					def    lowercase__      (	self					:     Union[str, Any]   ):
												lowerCamelCase_							  =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
												lowerCamelCase_							  =					self.get_dummy_components()
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline(**UpperCamelCase_   )
												lowerCamelCase_							  =					sd_pipe.to(UpperCamelCase_   )
												sd_pipe.set_progress_bar_config(disable=UpperCamelCase_   )

												lowerCamelCase_							  =					self.get_dummy_inputs(UpperCamelCase_   )
												lowerCamelCase_							  =					"""french fries"""
												lowerCamelCase_							  =					sd_pipe(**UpperCamelCase_   ,					negative_prompt=UpperCamelCase_   )
												lowerCamelCase_							  =					output.images
												lowerCamelCase_							  =					image[0, -3:, -3:, -1]

												assert image.shape == (1, 3_2, 3_2, 3)
												lowerCamelCase_							  =					np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831]   )

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

					def    lowercase__      (	self					:     Union[str, Any]   ):
												lowerCamelCase_							  =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
												lowerCamelCase_							  =					self.get_dummy_components()
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline(**UpperCamelCase_   )
												lowerCamelCase_							  =					sd_pipe.to(UpperCamelCase_   )
												sd_pipe.set_progress_bar_config(disable=UpperCamelCase_   )

												lowerCamelCase_							  =					self.get_dummy_inputs(UpperCamelCase_   )
												lowerCamelCase_							  =					[inputs["""prompt"""]] * 2

												lowerCamelCase_							  =					np.array(inputs["""image"""]   ).astype(np.floataa   ) / 255.0
												lowerCamelCase_							  =					torch.from_numpy(UpperCamelCase_   ).unsqueeze(0   ).to(UpperCamelCase_   )
												lowerCamelCase_							  =					image / 2 + 0.5
												lowerCamelCase_							  =					image.permute(0   ,					3   ,					1   ,					2   )
												lowerCamelCase_							  =					image.repeat(2   ,					1   ,					1   ,					1   )

												lowerCamelCase_							  =					sd_pipe(**UpperCamelCase_   ).images
												lowerCamelCase_							  =					image[-1, -3:, -3:, -1]

												assert image.shape == (2, 3_2, 3_2, 3)
												lowerCamelCase_							  =					np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579]   )

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

					def    lowercase__      (	self					:     Optional[Any]   ):
												lowerCamelCase_							  =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
												lowerCamelCase_							  =					self.get_dummy_components()
												lowerCamelCase_							  =					EulerAncestralDiscreteScheduler(
												    beta_start=0.00085   ,					beta_end=0.012   ,					beta_schedule="""scaled_linear"""   )
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline(**UpperCamelCase_   )
												lowerCamelCase_							  =					sd_pipe.to(UpperCamelCase_   )
												sd_pipe.set_progress_bar_config(disable=UpperCamelCase_   )

												lowerCamelCase_							  =					self.get_dummy_inputs(UpperCamelCase_   )
												lowerCamelCase_							  =					sd_pipe(**UpperCamelCase_   ).images
												lowerCamelCase_							  =					image[0, -3:, -3:, -1]

												lowerCamelCase_							  =					[round(UpperCamelCase_   ,					4   ) for x in image_slice.flatten().tolist()]
												print(""",""".join([str(UpperCamelCase_   ) for x in slice]   )   )

												assert image.shape == (1, 3_2, 3_2, 3)
												lowerCamelCase_							  =					np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986]   )

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

					def    lowercase__      (	self					:     Union[str, Any]   ):
												super().test_inference_batch_single_identical(expected_max_diff=3E-3   )



					def    lowercase__      (	self					:     Union[str, Any]   ):
												lowerCamelCase_							  =					self.get_dummy_components()
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline(**UpperCamelCase_   )
												lowerCamelCase_							  =					VaeImageProcessor(do_resize=UpperCamelCase_   ,					do_normalize=UpperCamelCase_   )
												lowerCamelCase_							  =					pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )

												lowerCamelCase_							  =					pipe(**self.get_dummy_inputs_by_type(UpperCamelCase_   ,					input_image_type="""pt"""   )   )[0]

												lowerCamelCase_							  =					components["""vae"""]
												lowerCamelCase_							  =					self.get_dummy_inputs_by_type(UpperCamelCase_   ,					input_image_type="""pt"""   )

												for image_param in self.image_latents_params:
																			if image_param in inputs.keys():
																										lowerCamelCase_							  =					vae.encode(inputs[image_param]   ).latent_dist.mode()

												lowerCamelCase_							  =					pipe(**UpperCamelCase_   )[0]

												lowerCamelCase_							  =					np.abs(out - out_latents_inputs   ).max()
												self.assertLess(UpperCamelCase_   ,					1E-4   ,					"""passing latents as image input generate different result from passing image"""   )





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

					def    lowercase__      (	self					:     Union[str, Any]   ):
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()

					def    lowercase__      (	self					:     List[Any]   ,					__UpperCamelCase					:     str=0   ):
												lowerCamelCase_							  =					torch.manual_seed(UpperCamelCase_   )
												lowerCamelCase_							  =					load_image(
												    """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg"""   )
												lowerCamelCase_							  =					{
												    """prompt""": """turn him into a cyborg""",
												    """image""": image,
												    """generator""": generator,
												    """num_inference_steps""": 3,
												    """guidance_scale""": 7.5,
												    """image_guidance_scale""": 1.0,
												    """output_type""": """numpy""",
												}
												return inputs

					def    lowercase__      (	self					:     str   ):
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline.from_pretrained(
												    """timbrooks/instruct-pix2pix"""   ,					safety_checker=UpperCamelCase_   )
												pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )
												pipe.enable_attention_slicing()

												lowerCamelCase_							  =					self.get_inputs()
												lowerCamelCase_							  =					pipe(**UpperCamelCase_   ).images
												lowerCamelCase_							  =					image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 5_1_2, 5_1_2, 3)
												lowerCamelCase_							  =					np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555]   )

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

					def    lowercase__      (	self					:     Optional[Any]   ):
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline.from_pretrained(
												    """timbrooks/instruct-pix2pix"""   ,					safety_checker=UpperCamelCase_   )
												lowerCamelCase_							  =					LMSDiscreteScheduler.from_config(pipe.scheduler.config   )
												pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )
												pipe.enable_attention_slicing()

												lowerCamelCase_							  =					self.get_inputs()
												lowerCamelCase_							  =					pipe(**UpperCamelCase_   ).images
												lowerCamelCase_							  =					image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 5_1_2, 5_1_2, 3)
												lowerCamelCase_							  =					np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301]   )

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

					def    lowercase__      (	self					:     Optional[Any]   ):
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline.from_pretrained(
												    """timbrooks/instruct-pix2pix"""   ,					safety_checker=UpperCamelCase_   )
												lowerCamelCase_							  =					DDIMScheduler.from_config(pipe.scheduler.config   )
												pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )
												pipe.enable_attention_slicing()

												lowerCamelCase_							  =					self.get_inputs()
												lowerCamelCase_							  =					pipe(**UpperCamelCase_   ).images
												lowerCamelCase_							  =					image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 5_1_2, 5_1_2, 3)
												lowerCamelCase_							  =					np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753]   )

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

					def    lowercase__      (	self					:     List[str]   ):
												lowerCamelCase_							  =					0

												def callback_fn(__UpperCamelCase					:     int   ,					__UpperCamelCase					:     int   ,					__UpperCamelCase					:     torch.FloatTensor   ) -> None:
																			lowerCamelCase_							  =					True
																			nonlocal number_of_steps
																			number_of_steps += 1
																			if step == 1:
																										lowerCamelCase_							  =					latents.detach().cpu().numpy()
																										assert latents.shape == (1, 4, 6_4, 6_4)
																										lowerCamelCase_							  =					latents[0, -3:, -3:, -1]
																										lowerCamelCase_							  =					np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983]   )

																										assert np.abs(latents_slice.flatten() - expected_slice   ).max() < 5E-2
																			elif step == 2:
																										lowerCamelCase_							  =					latents.detach().cpu().numpy()
																										assert latents.shape == (1, 4, 6_4, 6_4)
																										lowerCamelCase_							  =					latents[0, -3:, -3:, -1]
																										lowerCamelCase_							  =					np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115]   )

																										assert np.abs(latents_slice.flatten() - expected_slice   ).max() < 5E-2

												lowerCamelCase_							  =					False

												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline.from_pretrained(
												    """timbrooks/instruct-pix2pix"""   ,					safety_checker=UpperCamelCase_   ,					torch_dtype=torch.floataa   )
												lowerCamelCase_							  =					pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )
												pipe.enable_attention_slicing()

												lowerCamelCase_							  =					self.get_inputs()
												pipe(**UpperCamelCase_   ,					callback=UpperCamelCase_   ,					callback_steps=1   )
												assert callback_fn.has_been_called
												assert number_of_steps == 3

					def    lowercase__      (	self					:     List[Any]   ):
												torch.cuda.empty_cache()
												torch.cuda.reset_max_memory_allocated()
												torch.cuda.reset_peak_memory_stats()

												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline.from_pretrained(
												    """timbrooks/instruct-pix2pix"""   ,					safety_checker=UpperCamelCase_   ,					torch_dtype=torch.floataa   )
												lowerCamelCase_							  =					pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )
												pipe.enable_attention_slicing(1   )
												pipe.enable_sequential_cpu_offload()

												lowerCamelCase_							  =					self.get_inputs()
												lowerCamelCase_							  =					pipe(**UpperCamelCase_   )

												lowerCamelCase_							  =					torch.cuda.max_memory_allocated()
												# make sure that less than 2.2 GB is allocated
												assert mem_bytes < 2.2 * 1_0**9



					def    lowercase__      (	self					:     str   ):
												lowerCamelCase_							  =					self.get_inputs()
												# resize to resolution that is divisible by 8 but not 16 or 32
												lowerCamelCase_							  =					inputs["""image"""].resize((5_0_4, 5_0_4)   )

												lowerCamelCase_							  =					"""timbrooks/instruct-pix2pix"""
												lowerCamelCase_							  =					StableDiffusionInstructPixaPixPipeline.from_pretrained(
												    UpperCamelCase_   ,					safety_checker=UpperCamelCase_   ,					)
												pipe.to(UpperCamelCase_   )
												pipe.set_progress_bar_config(disable=UpperCamelCase_   )
												pipe.enable_attention_slicing()

												lowerCamelCase_							  =					pipe(**UpperCamelCase_   )
												lowerCamelCase_							  =					output.images[0]

												lowerCamelCase_							  =					image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

												assert image.shape == (5_0_4, 5_0_4, 3)
												lowerCamelCase_							  =					np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590]   )

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

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

					def __init__(	self					:     int   ,					__UpperCamelCase					:     Union[str, Any]   ,					__UpperCamelCase					:     Union[str, Any]=3   ,					__UpperCamelCase					:     int=3_2   ,					__UpperCamelCase					:     Any=3   ,					__UpperCamelCase					:     List[str]=1_0   ,					__UpperCamelCase					:     int=[1_0, 2_0, 3_0, 4_0]   ,					__UpperCamelCase					:     List[str]=[1, 1, 2, 1]   ,					__UpperCamelCase					:     str=True   ,					__UpperCamelCase					:     List[str]=True   ,					__UpperCamelCase					:     Dict="relu"   ,					__UpperCamelCase					:     int=3   ,					__UpperCamelCase					:     Dict=None   ,					):
												lowerCamelCase_							  =					parent
												lowerCamelCase_							  =					batch_size
												lowerCamelCase_							  =					image_size
												lowerCamelCase_							  =					num_channels
												lowerCamelCase_							  =					embeddings_size
												lowerCamelCase_							  =					hidden_sizes
												lowerCamelCase_							  =					depths
												lowerCamelCase_							  =					is_training
												lowerCamelCase_							  =					use_labels
												lowerCamelCase_							  =					hidden_act
												lowerCamelCase_							  =					num_labels
												lowerCamelCase_							  =					scope
												lowerCamelCase_							  =					len(__UpperCamelCase   )

					def    lowercase__      (	self					:     Any   ):
												lowerCamelCase_							  =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

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

					def    lowercase__      (	self					:     str   ):
												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					:     Optional[int]   ,					__UpperCamelCase					:     int   ,					__UpperCamelCase					:     Tuple   ,					__UpperCamelCase					:     Union[str, Any]   ):
												lowerCamelCase_							  =					TFRegNetModel(config=__UpperCamelCase   )
												lowerCamelCase_							  =					model(__UpperCamelCase   ,					training=__UpperCamelCase   )
												# 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 // 3_2, self.image_size // 3_2)   ,					)

					def    lowercase__      (	self					:     Union[str, Any]   ,					__UpperCamelCase					:     int   ,					__UpperCamelCase					:     List[Any]   ,					__UpperCamelCase					:     List[str]   ):
												lowerCamelCase_							  =					self.num_labels
												lowerCamelCase_							  =					TFRegNetForImageClassification(__UpperCamelCase   )
												lowerCamelCase_							  =					model(__UpperCamelCase   ,					labels=__UpperCamelCase   ,					training=__UpperCamelCase   )
												self.parent.assertEqual(result.logits.shape   ,					(self.batch_size, self.num_labels)   )



					def    lowercase__      (	self					:     int   ):
												lowerCamelCase_							  =					self.prepare_config_and_inputs()
												lowerCamelCase_  ,   lowerCamelCase_  ,   lowerCamelCase_							  =					config_and_inputs
												lowerCamelCase_							  =					{"""pixel_values""": pixel_values}
												return config, inputs_dict





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

					SCREAMING_SNAKE_CASE			    =    False
					SCREAMING_SNAKE_CASE			    =    False
					SCREAMING_SNAKE_CASE			    =    False
					SCREAMING_SNAKE_CASE			    =    False
					SCREAMING_SNAKE_CASE			    =    False

					def    lowercase__      (	self					:     Tuple   ):
												lowerCamelCase_							  =					TFRegNetModelTester(self   )
												lowerCamelCase_							  =					ConfigTester(self   ,					config_class=__UpperCamelCase   ,					has_text_modality=__UpperCamelCase   )

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

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

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

					def    lowercase__      (	self					:     Dict   ):
												lowerCamelCase_  ,   lowerCamelCase_							  =					self.model_tester.prepare_config_and_inputs_for_common()

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

																			lowerCamelCase_							  =					["""pixel_values"""]
																			self.assertListEqual(arg_names[:1]   ,					__UpperCamelCase   )

					def    lowercase__      (	self					:     Any   ):
												lowerCamelCase_							  =					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__UpperCamelCase   )

					def    lowercase__      (	self					:     int   ):
												def check_hidden_states_output(__UpperCamelCase					:     Union[str, Any]   ,					__UpperCamelCase					:     str   ,					__UpperCamelCase					:     Any   ):
																			lowerCamelCase_							  =					model_class(__UpperCamelCase   )
																			lowerCamelCase_							  =					model(**self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   )   ,					training=__UpperCamelCase   )

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

																			lowerCamelCase_							  =					self.model_tester.num_stages
																			self.assertEqual(len(__UpperCamelCase   )   ,					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]   ,					)

												lowerCamelCase_  ,   lowerCamelCase_							  =					self.model_tester.prepare_config_and_inputs_for_common()
												lowerCamelCase_							  =					["""basic""", """bottleneck"""]
												for model_class in self.all_model_classes:
																			for layer_type in layers_type:
																										lowerCamelCase_							  =					layer_type
																										lowerCamelCase_							  =					True
																										check_hidden_states_output(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   )

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

																										check_hidden_states_output(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   )

					def    lowercase__      (	self					:     Optional[Any]   ):
												lowerCamelCase_  ,   lowerCamelCase_							  =					self.model_tester.prepare_config_and_inputs_for_common()

												def check_equivalence(__UpperCamelCase					:     List[str]   ,					__UpperCamelCase					:     Optional[Any]   ,					__UpperCamelCase					:     Tuple   ,					__UpperCamelCase					:     List[Any]={}   ):
																			lowerCamelCase_							  =					model(__UpperCamelCase   ,					return_dict=__UpperCamelCase   ,					**__UpperCamelCase   )
																			lowerCamelCase_							  =					model(__UpperCamelCase   ,					return_dict=__UpperCamelCase   ,					**__UpperCamelCase   ).to_tuple()

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

																										recursive_check(__UpperCamelCase   ,					__UpperCamelCase   )

												for model_class in self.all_model_classes:
																			lowerCamelCase_							  =					model_class(__UpperCamelCase   )

																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   )
																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   )
																			check_equivalence(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   )

																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   ,					return_labels=__UpperCamelCase   )
																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   ,					return_labels=__UpperCamelCase   )
																			check_equivalence(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   )

																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   )
																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   )
																			check_equivalence(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   ,					{"""output_hidden_states""": True}   )

																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   ,					return_labels=__UpperCamelCase   )
																			lowerCamelCase_							  =					self._prepare_for_class(__UpperCamelCase   ,					__UpperCamelCase   ,					return_labels=__UpperCamelCase   )
																			check_equivalence(__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase   ,					{"""output_hidden_states""": True}   )

					def    lowercase__      (	self					:     Union[str, Any]   ):
												lowerCamelCase_							  =					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase   )



					@slow
					def    lowercase__      (	self					:     List[Any]   ):
												for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			lowerCamelCase_							  =					TFRegNetModel.from_pretrained(__UpperCamelCase   )
																			self.assertIsNotNone(__UpperCamelCase   )



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





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

					@cached_property
					def    lowercase__      (	self					:     Union[str, Any]   ):
												return (
												    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
												    if is_vision_available()
												    else None
												)



					@slow
					def    lowercase__      (	self					:     List[str]   ):
												lowerCamelCase_							  =					TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

												lowerCamelCase_							  =					self.default_image_processor
												lowerCamelCase_							  =					prepare_img()
												lowerCamelCase_							  =					image_processor(images=__UpperCamelCase   ,					return_tensors="""tf"""   )

												# forward pass
												lowerCamelCase_							  =					model(**__UpperCamelCase   ,					training=__UpperCamelCase   )

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

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

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





