





import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
					from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor

class 							__SCREAMING_SNAKE_CASE       :






							def __init__(    self	,			__lowerCAmelCase	,			__lowerCAmelCase=13	,			__lowerCAmelCase=32	,			__lowerCAmelCase=3	,			__lowerCAmelCase=4	,			__lowerCAmelCase=[10, 20, 30, 40]	,			__lowerCAmelCase=[2, 2, 3, 2]	,			__lowerCAmelCase=True	,			__lowerCAmelCase=True	,			__lowerCAmelCase=37	,			__lowerCAmelCase="gelu"	,			__lowerCAmelCase=10	,			__lowerCAmelCase=0.02	,			__lowerCAmelCase=["stage2", "stage3", "stage4"]	,			__lowerCAmelCase=[2, 3, 4]	,			__lowerCAmelCase=None	,			):
														UpperCamelCase__					  =      parent
														UpperCamelCase__					  =      batch_size
														UpperCamelCase__					  =      image_size
														UpperCamelCase__					  =      num_channels
														UpperCamelCase__					  =      num_stages
														UpperCamelCase__					  =      hidden_sizes
														UpperCamelCase__					  =      depths
														UpperCamelCase__					  =      is_training
														UpperCamelCase__					  =      use_labels
														UpperCamelCase__					  =      intermediate_size
														UpperCamelCase__					  =      hidden_act
														UpperCamelCase__					  =      num_labels
														UpperCamelCase__					  =      initializer_range
														UpperCamelCase__					  =      out_features
														UpperCamelCase__					  =      out_indices
														UpperCamelCase__					  =      scope






							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 ConvNextConfig(
														    num_channels=self.num_channels	,			hidden_sizes=self.hidden_sizes	,			depths=self.depths	,			num_stages=self.num_stages	,			hidden_act=self.hidden_act	,			is_decoder=__lowerCAmelCase	,			initializer_range=self.initializer_range	,			out_features=self.out_features	,			out_indices=self.out_indices	,			num_labels=self.num_labels	,			)






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	):
														UpperCamelCase__					  =      ConvNextModel(config=__lowerCAmelCase	)
														model.to(__lowerCAmelCase	)
														model.eval()
														UpperCamelCase__					  =      model(__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__					  =      ConvNextForImageClassification(__lowerCAmelCase	)
														model.to(__lowerCAmelCase	)
														model.eval()
														UpperCamelCase__					  =      model(__lowerCAmelCase	,			labels=__lowerCAmelCase	)
														self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)	)






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	):
														UpperCamelCase__					  =      ConvNextBackbone(config=__lowerCAmelCase	)
														model.to(__lowerCAmelCase	)
														model.eval()
														UpperCamelCase__					  =      model(__lowerCAmelCase	)

														# verify hidden states
														self.parent.assertEqual(len(result.feature_maps	)	,			len(config.out_features	)	)
														self.parent.assertListEqual(list(result.feature_maps[0].shape	)	,			[self.batch_size, self.hidden_sizes[1], 4, 4]	)

														# verify channels
														self.parent.assertEqual(len(model.channels	)	,			len(config.out_features	)	)
														self.parent.assertListEqual(model.channels	,			config.hidden_sizes[1:]	)

														# verify backbone works with out_features=None
														UpperCamelCase__					  =      None
														UpperCamelCase__					  =      ConvNextBackbone(config=__lowerCAmelCase	)
														model.to(__lowerCAmelCase	)
														model.eval()
														UpperCamelCase__					  =      model(__lowerCAmelCase	)

														# verify feature maps
														self.parent.assertEqual(len(result.feature_maps	)	,			1	)
														self.parent.assertListEqual(list(result.feature_maps[0].shape	)	,			[self.batch_size, self.hidden_sizes[-1], 1, 1]	)

														# verify channels
														self.parent.assertEqual(len(model.channels	)	,			1	)
														self.parent.assertListEqual(model.channels	,			[config.hidden_sizes[-1]]	)







							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_torch
class 							__SCREAMING_SNAKE_CASE       (  snake_case_ ,		snake_case_ ,		unittest.TestCase							):
							snake_case  :   Any      =							(
							    (
							        ConvNextModel,
							        ConvNextForImageClassification,
							        ConvNextBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							snake_case  :   Optional[int]      =							(
							    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
							    if is_torch_available()
							    else {}
							)

							snake_case  :   Dict      =							True
							snake_case  :   Optional[Any]      =							False
							snake_case  :   Tuple      =							False
							snake_case  :   str      =							False
							snake_case  :   int      =							False






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      ConvNextModelTester(self	)
														UpperCamelCase__					  =      ConfigTester(self	,			config_class=__lowerCAmelCase	,			has_text_modality=__lowerCAmelCase	,			hidden_size=37	)






							def 					_lowerCamelCase		(    self	):
														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 					_lowerCamelCase		(    self	):
														return






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






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






							@unittest.skip(reason="""ConvNext does not use feedforward chunking"""	)
							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.forward	)
																					# 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	):
														UpperCamelCase__					  =      self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_backbone(*__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														def check_hidden_states_output(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	):
																					UpperCamelCase__					  =      model_class(__lowerCAmelCase	)
																					model.to(__lowerCAmelCase	)
																					model.eval()

																					with torch.no_grad():
																												UpperCamelCase__					  =      model(**self._prepare_for_class(__lowerCAmelCase	,			__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	)

																					# ConvNext'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__					  =      self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					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__					  =      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 CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					UpperCamelCase__					  =      ConvNextModel.from_pretrained(__lowerCAmelCase	)
																					self.assertIsNotNone(__lowerCAmelCase	)






def      _UpperCamelCase  ():






							"""simple docstring"""





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

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






							@cached_property
							def 					_lowerCamelCase		(    self	):
														return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""	) if is_vision_available() else None







							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""	).to(__lowerCAmelCase	)

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

														# forward pass
														with torch.no_grad():
																					UpperCamelCase__					  =      model(**__lowerCAmelCase	)

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

														UpperCamelCase__					  =      torch.tensor([-0.0260, -0.4739, 0.1911]	).to(__lowerCAmelCase	)

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






@require_torch
class 							__SCREAMING_SNAKE_CASE       (  unittest.TestCase ,		snake_case_							):
							snake_case  :   Dict      =							(ConvNextBackbone,) if is_torch_available() else ()
							snake_case  :   List[Any]      =							ConvNextConfig

							snake_case  :   List[str]      =							False






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      ConvNextModelTester(self	)






# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/

import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()




class        _SCREAMING_SNAKE_CASE	( snake_case_     ,			snake_case_     ,			snake_case_     ,			unittest.TestCase		):
	lowerCAmelCase__   =					StableDiffusionControlNetImgaImgPipeline
	lowerCAmelCase__   =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
	lowerCAmelCase__   =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	lowerCAmelCase__   =					IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'control_image'}		)
	lowerCAmelCase__   =					IMAGE_TO_IMAGE_IMAGE_PARAMS



	def        SCREAMING_SNAKE_CASE_(       self					)							->			int:
					torch.manual_seed(0					)
					lowerCamelCase_         =     UNetaDConditionModel(
					    block_out_channels=(32, 64)		,    layers_per_block=2		,    sample_size=32		,    in_channels=4		,    out_channels=4		,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")		,    up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")		,    cross_attention_dim=32		,    )
					torch.manual_seed(0					)
					lowerCamelCase_         =     ControlNetModel(
					    block_out_channels=(32, 64)		,    layers_per_block=2		,    in_channels=4		,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")		,    cross_attention_dim=32		,    conditioning_embedding_out_channels=(16, 32)		,    )
					torch.manual_seed(0					)
					lowerCamelCase_         =     DDIMScheduler(
					    beta_start=0.0_0_0_8_5		,    beta_end=0.0_1_2		,    beta_schedule="scaled_linear"		,    clip_sample=lowercase		,    set_alpha_to_one=lowercase		,    )
					torch.manual_seed(0					)
					lowerCamelCase_         =     AutoencoderKL(
					    block_out_channels=[32, 64]		,    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=32		,    intermediate_size=37		,    layer_norm_eps=1e-05		,    num_attention_heads=4		,    num_hidden_layers=5		,    pad_token_id=1		,    vocab_size=1000		,    )
					lowerCamelCase_         =     CLIPTextModel(lowercase					)
					lowerCamelCase_         =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)

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



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase=0					)							->			int:
					if str(lowercase					).startswith("mps"					):
									lowerCamelCase_         =     torch.manual_seed(lowercase					)
					else:
									lowerCamelCase_         =     torch.Generator(device=lowercase					).manual_seed(lowercase					)

					lowerCamelCase_         =     2
					lowerCamelCase_         =     randn_tensor(
					    (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)		,    generator=lowercase		,    device=torch.device(lowercase					)		,    )
					lowerCamelCase_         =     floats_tensor(control_image.shape		,    rng=random.Random(lowercase					)					).to(lowercase					)
					lowerCamelCase_         =     image.cpu().permute(0		,    2		,    3		,    1					)[0]
					lowerCamelCase_         =     Image.fromarray(np.uinta(lowercase					)					).convert("RGB"					).resize((64, 64)					)
					lowerCamelCase_         =     {
					    "prompt": "A painting of a squirrel eating a burger",
					    "generator": generator,
					    "num_inference_steps": 2,
					    "guidance_scale": 6.0,
					    "output_type": "numpy",
					    "image": image,
					    "control_image": control_image,
					}

					return inputs



	def        SCREAMING_SNAKE_CASE_(       self					)							->			List[str]:
					return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3					)



	@unittest.skipIf(
	    torch_device != "cuda" or not is_xformers_available()		,    reason="XFormers attention is only available with CUDA and `xformers` installed"		,    )
	def        SCREAMING_SNAKE_CASE_(       self					)							->			List[str]:
					self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Any:
					self._test_inference_batch_single_identical(expected_max_diff=2e-3					)




class        _SCREAMING_SNAKE_CASE	( snake_case_     ,			snake_case_     ,			unittest.TestCase		):
	lowerCAmelCase__   =					StableDiffusionControlNetImgaImgPipeline
	lowerCAmelCase__   =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
	lowerCAmelCase__   =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	lowerCAmelCase__   =					frozenset([]		)  # TO_DO: add image_params once refactored VaeImageProcessor.preprocess



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Dict:
					torch.manual_seed(0					)
					lowerCamelCase_         =     UNetaDConditionModel(
					    block_out_channels=(32, 64)		,    layers_per_block=2		,    sample_size=32		,    in_channels=4		,    out_channels=4		,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")		,    up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")		,    cross_attention_dim=32		,    )
					torch.manual_seed(0					)

					def init_weights(lowercase					):
									if isinstance(lowercase		,    torch.nn.Convad					):
													torch.nn.init.normal(m.weight					)
													m.bias.data.fill_(1.0					)

					lowerCamelCase_         =     ControlNetModel(
					    block_out_channels=(32, 64)		,    layers_per_block=2		,    in_channels=4		,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")		,    cross_attention_dim=32		,    conditioning_embedding_out_channels=(16, 32)		,    )
					controlneta.controlnet_down_blocks.apply(lowercase					)

					torch.manual_seed(0					)
					lowerCamelCase_         =     ControlNetModel(
					    block_out_channels=(32, 64)		,    layers_per_block=2		,    in_channels=4		,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")		,    cross_attention_dim=32		,    conditioning_embedding_out_channels=(16, 32)		,    )
					controlneta.controlnet_down_blocks.apply(lowercase					)

					torch.manual_seed(0					)
					lowerCamelCase_         =     DDIMScheduler(
					    beta_start=0.0_0_0_8_5		,    beta_end=0.0_1_2		,    beta_schedule="scaled_linear"		,    clip_sample=lowercase		,    set_alpha_to_one=lowercase		,    )
					torch.manual_seed(0					)
					lowerCamelCase_         =     AutoencoderKL(
					    block_out_channels=[32, 64]		,    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=32		,    intermediate_size=37		,    layer_norm_eps=1e-05		,    num_attention_heads=4		,    num_hidden_layers=5		,    pad_token_id=1		,    vocab_size=1000		,    )
					lowerCamelCase_         =     CLIPTextModel(lowercase					)
					lowerCamelCase_         =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)

					lowerCamelCase_         =     MultiControlNetModel([controlneta, controlneta]					)

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



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase=0					)							->			List[Any]:
					if str(lowercase					).startswith("mps"					):
									lowerCamelCase_         =     torch.manual_seed(lowercase					)
					else:
									lowerCamelCase_         =     torch.Generator(device=lowercase					).manual_seed(lowercase					)

					lowerCamelCase_         =     2

					lowerCamelCase_         =     [
					    randn_tensor(
					        (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)		,    generator=lowercase		,    device=torch.device(lowercase					)		,    ),
					    randn_tensor(
					        (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)		,    generator=lowercase		,    device=torch.device(lowercase					)		,    ),
					]

					lowerCamelCase_         =     floats_tensor(control_image[0].shape		,    rng=random.Random(lowercase					)					).to(lowercase					)
					lowerCamelCase_         =     image.cpu().permute(0		,    2		,    3		,    1					)[0]
					lowerCamelCase_         =     Image.fromarray(np.uinta(lowercase					)					).convert("RGB"					).resize((64, 64)					)
					lowerCamelCase_         =     {
					    "prompt": "A painting of a squirrel eating a burger",
					    "generator": generator,
					    "num_inference_steps": 2,
					    "guidance_scale": 6.0,
					    "output_type": "numpy",
					    "image": image,
					    "control_image": control_image,
					}

					return inputs



	def        SCREAMING_SNAKE_CASE_(       self					)							->			List[Any]:
					lowerCamelCase_         =     self.get_dummy_components()
					lowerCamelCase_         =     self.pipeline_class(**lowercase					)
					pipe.to(lowercase					)

					lowerCamelCase_         =     1_0.0
					lowerCamelCase_         =     4

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     steps
					lowerCamelCase_         =     scale
					lowerCamelCase_         =     pipe(**lowercase					)[0]

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     steps
					lowerCamelCase_         =     scale
					lowerCamelCase_         =     pipe(**lowercase		,    control_guidance_start=0.1		,    control_guidance_end=0.2					)[0]

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     steps
					lowerCamelCase_         =     scale
					lowerCamelCase_         =     pipe(**lowercase		,    control_guidance_start=[0.1, 0.3]		,    control_guidance_end=[0.2, 0.7]					)[0]

					lowerCamelCase_         =     self.get_dummy_inputs(lowercase					)
					lowerCamelCase_         =     steps
					lowerCamelCase_         =     scale
					lowerCamelCase_         =     pipe(**lowercase		,    control_guidance_start=0.4		,    control_guidance_end=[0.5, 0.8]					)[0]

					# make sure that all outputs are different
					assert np.sum(np.abs(output_a - output_a					)					) > 1e-3
					assert np.sum(np.abs(output_a - output_a					)					) > 1e-3
					assert np.sum(np.abs(output_a - output_a					)					) > 1e-3



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Dict:
					return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3					)



	@unittest.skipIf(
	    torch_device != "cuda" or not is_xformers_available()		,    reason="XFormers attention is only available with CUDA and `xformers` installed"		,    )
	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Union[str, Any]:
					self._test_inference_batch_single_identical(expected_max_diff=2e-3					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			int:
					lowerCamelCase_         =     self.get_dummy_components()
					lowerCamelCase_         =     self.pipeline_class(**lowercase					)
					pipe.to(lowercase					)
					pipe.set_progress_bar_config(disable=lowercase					)
					with tempfile.TemporaryDirectory() as tmpdir:
									try:
													# save_pretrained is not implemented for Multi-ControlNet
													pipe.save_pretrained(lowercase					)
									except NotImplementedError:
													pass




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



	def        SCREAMING_SNAKE_CASE_(       self					)							->			List[Any]:
					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					lowerCamelCase_         =     ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny"					)

					lowerCamelCase_         =     StableDiffusionControlNetImgaImgPipeline.from_pretrained(
					    "runwayml/stable-diffusion-v1-5"		,    safety_checker=lowercase		,    controlnet=lowercase					)
					pipe.enable_model_cpu_offload()
					pipe.set_progress_bar_config(disable=lowercase					)

					lowerCamelCase_         =     torch.Generator(device="cpu"					).manual_seed(0					)
					lowerCamelCase_         =     "evil space-punk bird"
					lowerCamelCase_         =     load_image(
					    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"					).resize((512, 512)					)
					lowerCamelCase_         =     load_image(
					    "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png"					).resize((512, 512)					)

					lowerCamelCase_         =     pipe(
					    lowercase		,    lowercase		,    control_image=lowercase		,    generator=lowercase		,    output_type="np"		,    num_inference_steps=50		,    strength=0.6		,    )

					lowerCamelCase_         =     output.images[0]

					assert image.shape == (512, 512, 3)

					lowerCamelCase_         =     load_numpy(
					    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy"					)

					assert np.abs(expected_image - image					).max() < 9e-2


