
import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 (
			    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
			    MODEL_MAPPING,
			    LevitForImageClassification,
			    LevitForImageClassificationWithTeacher,
			    LevitModel,
			)
			from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import LevitImageProcessor




class        _SCREAMING_SNAKE_CASE	( snake_case_		):



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					lowerCamelCase_         =     self.config_class(**self.inputs_dict					)
					self.parent.assertTrue(hasattr(lowercase		,    "hidden_sizes"					)					)
					self.parent.assertTrue(hasattr(lowercase		,    "num_attention_heads"					)					)




class        _SCREAMING_SNAKE_CASE	:



	def __init__(       self		,    lowercase		,    lowercase=13		,    lowercase=64		,    lowercase=3		,    lowercase=3		,    lowercase=2		,    lowercase=1		,    lowercase=16		,    lowercase=[128, 256, 384]		,    lowercase=[4, 6, 8]		,    lowercase=[2, 3, 4]		,    lowercase=[16, 16, 16]		,    lowercase=0		,    lowercase=[2, 2, 2]		,    lowercase=[2, 2, 2]		,    lowercase=0.0_2		,    lowercase=True		,    lowercase=True		,    lowercase=2		,    )							->			Any:
					lowerCamelCase_         =     parent
					lowerCamelCase_         =     batch_size
					lowerCamelCase_         =     image_size
					lowerCamelCase_         =     num_channels
					lowerCamelCase_         =     kernel_size
					lowerCamelCase_         =     stride
					lowerCamelCase_         =     padding
					lowerCamelCase_         =     hidden_sizes
					lowerCamelCase_         =     num_attention_heads
					lowerCamelCase_         =     depths
					lowerCamelCase_         =     key_dim
					lowerCamelCase_         =     drop_path_rate
					lowerCamelCase_         =     patch_size
					lowerCamelCase_         =     attention_ratio
					lowerCamelCase_         =     mlp_ratio
					lowerCamelCase_         =     initializer_range
					lowerCamelCase_         =     [
					    ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
					    ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
					]
					lowerCamelCase_         =     is_training
					lowerCamelCase_         =     use_labels
					lowerCamelCase_         =     num_labels
					lowerCamelCase_         =     initializer_range



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					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        SCREAMING_SNAKE_CASE_(       self					)							->			List[Any]:
					return LevitConfig(
					    image_size=self.image_size		,    num_channels=self.num_channels		,    kernel_size=self.kernel_size		,    stride=self.stride		,    padding=self.padding		,    patch_size=self.patch_size		,    hidden_sizes=self.hidden_sizes		,    num_attention_heads=self.num_attention_heads		,    depths=self.depths		,    key_dim=self.key_dim		,    drop_path_rate=self.drop_path_rate		,    mlp_ratio=self.mlp_ratio		,    attention_ratio=self.attention_ratio		,    initializer_range=self.initializer_range		,    down_ops=self.down_ops		,    )



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase		,    lowercase					)							->			str:
					lowerCamelCase_         =     LevitModel(config=lowercase					)
					model.to(lowercase					)
					model.eval()
					lowerCamelCase_         =     model(lowercase					)
					lowerCamelCase_         =     (self.image_size, self.image_size)
					lowerCamelCase_      ,       lowerCamelCase_         =     image_size[0], image_size[1]
					for _ in range(4					):
									lowerCamelCase_         =     floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1					)
									lowerCamelCase_         =     floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1					)
					self.parent.assertEqual(
					    result.last_hidden_state.shape		,    (self.batch_size, ceil(height / 4					) * ceil(width / 4					), self.hidden_sizes[-1])		,    )



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase		,    lowercase					)							->			List[str]:
					lowerCamelCase_         =     self.num_labels
					lowerCamelCase_         =     LevitForImageClassification(lowercase					)
					model.to(lowercase					)
					model.eval()
					lowerCamelCase_         =     model(lowercase		,    labels=lowercase					)
					self.parent.assertEqual(result.logits.shape		,    (self.batch_size, self.num_labels)					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Union[str, Any]:
					lowerCamelCase_         =     self.prepare_config_and_inputs()
					lowerCamelCase_      ,       lowerCamelCase_      ,       lowerCamelCase_         =     config_and_inputs
					lowerCamelCase_         =     {"pixel_values": pixel_values}
					return config, inputs_dict




@require_torch
class        _SCREAMING_SNAKE_CASE	( snake_case_     ,			snake_case_     ,			unittest.TestCase		):
	lowerCAmelCase__   =					(
	    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
	    if is_torch_available()
	    else ()
	)
	lowerCAmelCase__   =					(
	    {
	        'feature-extraction': LevitModel,
	        'image-classification': (LevitForImageClassification, LevitForImageClassificationWithTeacher),
	    }
	    if is_torch_available()
	    else {}
	)

	lowerCAmelCase__   =					False
	lowerCAmelCase__   =					False
	lowerCAmelCase__   =					False
	lowerCAmelCase__   =					False
	lowerCAmelCase__   =					False



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Dict:
					lowerCamelCase_         =     LevitModelTester(self					)
					lowerCamelCase_         =     ConfigTester(self		,    config_class=lowercase		,    has_text_modality=lowercase		,    hidden_size=37					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[Any]:
					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        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					return



	@unittest.skip(reason="Levit does not use inputs_embeds"					)
	def        SCREAMING_SNAKE_CASE_(       self					)							->			Tuple:
					pass



	@unittest.skip(reason="Levit does not support input and output embeddings"					)
	def        SCREAMING_SNAKE_CASE_(       self					)							->			int:
					pass



	@unittest.skip(reason="Levit does not output attentions"					)
	def        SCREAMING_SNAKE_CASE_(       self					)							->			List[str]:
					pass



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					lowerCamelCase_      ,       lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs_for_common()

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

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



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[int]:
					def check_hidden_states_output(lowercase		,    lowercase		,    lowercase					):
									lowerCamelCase_         =     model_class(lowercase					)
									model.to(lowercase					)
									model.eval()

									with torch.no_grad():
													lowerCamelCase_         =     model(**self._prepare_for_class(lowercase		,    lowercase					)					)

									lowerCamelCase_         =     outputs.hidden_states

									lowerCamelCase_         =     len(self.model_tester.depths					) + 1
									self.assertEqual(len(lowercase					)		,    lowercase					)

									lowerCamelCase_         =     (self.model_tester.image_size, self.model_tester.image_size)
									lowerCamelCase_      ,       lowerCamelCase_         =     image_size[0], image_size[1]
									for _ in range(4					):
													lowerCamelCase_         =     floor(
													    (
													        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
													        / self.model_tester.stride
													    )
													    + 1					)
													lowerCamelCase_         =     floor(
													    (
													        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
													        / self.model_tester.stride
													    )
													    + 1					)
									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]					)		,    [
									        height * width,
									        self.model_tester.hidden_sizes[0],
									    ]		,    )

					lowerCamelCase_      ,       lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									lowerCamelCase_         =     True
									check_hidden_states_output(lowercase		,    lowercase		,    lowercase					)

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

									check_hidden_states_output(lowercase		,    lowercase		,    lowercase					)



	@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."					)
	def        SCREAMING_SNAKE_CASE_(       self					)							->			str:
					pass



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase		,    lowercase=False					)							->			Dict:
					lowerCamelCase_         =     super()._prepare_for_class(lowercase		,    lowercase		,    return_labels=lowercase					)

					if return_labels:
									if model_class.__name__ == "LevitForImageClassificationWithTeacher":
													del inputs_dict["labels"]

					return inputs_dict



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Dict:
					lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowercase					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[Any]:
					lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowercase					)



	def        SCREAMING_SNAKE_CASE_(       self					)							->			int:
					if not self.model_tester.is_training:
									return

					lowerCamelCase_      ,       lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs_for_common()
					lowerCamelCase_         =     True

					for model_class in self.all_model_classes:
									# LevitForImageClassificationWithTeacher supports inference-only
									if (
									    model_class in get_values(lowercase					)
									    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
									):
													continue
									lowerCamelCase_         =     model_class(lowercase					)
									model.to(lowercase					)
									model.train()
									lowerCamelCase_         =     self._prepare_for_class(lowercase		,    lowercase		,    return_labels=lowercase					)
									lowerCamelCase_         =     model(**lowercase					).loss
									loss.backward()



	def        SCREAMING_SNAKE_CASE_(       self					)							->			str:
					lowerCamelCase_      ,       lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs_for_common()
					if not self.model_tester.is_training:
									return

					lowerCamelCase_         =     False
					lowerCamelCase_         =     True

					for model_class in self.all_model_classes:
									if model_class in get_values(lowercase					) or not model_class.supports_gradient_checkpointing:
													continue
									# LevitForImageClassificationWithTeacher supports inference-only
									if model_class.__name__ == "LevitForImageClassificationWithTeacher":
													continue
									lowerCamelCase_         =     model_class(lowercase					)
									model.gradient_checkpointing_enable()
									model.to(lowercase					)
									model.train()
									lowerCamelCase_         =     self._prepare_for_class(lowercase		,    lowercase		,    return_labels=lowercase					)
									lowerCamelCase_         =     model(**lowercase					).loss
									loss.backward()



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Any:
					lowerCamelCase_      ,       lowerCamelCase_         =     self.model_tester.prepare_config_and_inputs_for_common()

					lowerCamelCase_         =     [
					    {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
					    {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
					    {"title": "regression", "num_labels": 1, "dtype": torch.float},
					]

					for model_class in self.all_model_classes:
									if (
									    model_class
									    not in [
									        *get_values(lowercase					),
									    ]
									    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
									):
													continue

									for problem_type in problem_types:
													with self.subTest(msg=f'Testing {model_class} with {problem_type["title"]}'					):
																	lowerCamelCase_         =     problem_type["title"]
																	lowerCamelCase_         =     problem_type["num_labels"]

																	lowerCamelCase_         =     model_class(lowercase					)
																	model.to(lowercase					)
																	model.train()

																	lowerCamelCase_         =     self._prepare_for_class(lowercase		,    lowercase		,    return_labels=lowercase					)

																	if problem_type["num_labels"] > 1:
																					lowerCamelCase_         =     inputs["labels"].unsqueeze(1					).repeat(1		,    problem_type["num_labels"]					)

																	lowerCamelCase_         =     inputs["labels"].to(problem_type["dtype"]					)

																	# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																	# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																	# they have the same size." which is a symptom something in wrong for the regression problem.
																	# See https://github.com/huggingface/transformers/issues/11780
																	with warnings.catch_warnings(record=lowercase					) as warning_list:
																					lowerCamelCase_         =     model(**lowercase					).loss
																	for w in warning_list:
																					if "Using a target size that is different to the input size" in str(w.message					):
																									raise ValueError(
																									    f'Something is going wrong in the regression problem: intercepted {w.message}'					)

																	loss.backward()



	@slow
	def        SCREAMING_SNAKE_CASE_(       self					)							->			str:
					for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase_         =     LevitModel.from_pretrained(lowercase					)
									self.assertIsNotNone(lowercase					)





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





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



	@cached_property
	def        SCREAMING_SNAKE_CASE_(       self					)							->			Dict:
					return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)



	@slow
	def        SCREAMING_SNAKE_CASE_(       self					)							->			Optional[Any]:
					lowerCamelCase_         =     LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(
					    lowercase					)

					lowerCamelCase_         =     self.default_image_processor
					lowerCamelCase_         =     prepare_img()
					lowerCamelCase_         =     image_processor(images=lowercase		,    return_tensors="pt"					).to(lowercase					)

					# forward pass
					with torch.no_grad():
									lowerCamelCase_         =     model(**lowercase					)

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

					lowerCamelCase_         =     torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7]					).to(lowercase					)

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




# 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


