





import itertools
import json
import os
import unittest

from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class 							__SCREAMING_SNAKE_CASE       (  snake_case_ ,		unittest.TestCase							):
							snake_case  :   Tuple      =							RobertaTokenizer
							snake_case  :   Any      =							RobertaTokenizerFast
							snake_case  :   str      =							True
							snake_case  :   Optional[Any]      =							{"""cls_token""": """<s>"""}






							def 					_lowerCamelCase		(    self	):
														super().setUp()

														# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
														UpperCamelCase__					  =      [
														    """l""",
														    """o""",
														    """w""",
														    """e""",
														    """r""",
														    """s""",
														    """t""",
														    """i""",
														    """d""",
														    """n""",
														    """\u0120""",
														    """\u0120l""",
														    """\u0120n""",
														    """\u0120lo""",
														    """\u0120low""",
														    """er""",
														    """\u0120lowest""",
														    """\u0120newer""",
														    """\u0120wider""",
														    """<unk>""",
														]
														UpperCamelCase__					  =      dict(zip(__lowerCAmelCase	,			range(len(__lowerCAmelCase	)	)	)	)
														UpperCamelCase__					  =      ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
														UpperCamelCase__					  =      {"""unk_token""": """<unk>"""}

														UpperCamelCase__					  =      os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES["""vocab_file"""]	)
														UpperCamelCase__					  =      os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES["""merges_file"""]	)
														with open(self.vocab_file	,			"""w"""	,			encoding="""utf-8"""	) as fp:
																					fp.write(json.dumps(__lowerCAmelCase	) + """\n"""	)
														with open(self.merges_file	,			"""w"""	,			encoding="""utf-8"""	) as fp:
																					fp.write("""\n""".join(__lowerCAmelCase	)	)






							def 					_lowerCamelCase		(    self	,			**__lowerCAmelCase	):
														kwargs.update(self.special_tokens_map	)
														return self.tokenizer_class.from_pretrained(self.tmpdirname	,			**__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	,			**__lowerCAmelCase	):
														kwargs.update(self.special_tokens_map	)
														return RobertaTokenizerFast.from_pretrained(self.tmpdirname	,			**__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	):
														UpperCamelCase__					  =      """lower newer"""
														UpperCamelCase__					  =      """lower newer"""
														return input_text, output_text






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.tokenizer_class(self.vocab_file	,			self.merges_file	,			**self.special_tokens_map	)
														UpperCamelCase__					  =      """lower newer"""
														UpperCamelCase__					  =      ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
														UpperCamelCase__					  =      tokenizer.tokenize(__lowerCAmelCase	)  # , add_prefix_space=True)
														self.assertListEqual(__lowerCAmelCase	,			__lowerCAmelCase	)

														UpperCamelCase__					  =      tokens + [tokenizer.unk_token]
														UpperCamelCase__					  =      [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
														self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase	)	,			__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.get_tokenizer()

														self.assertListEqual(tokenizer.encode("""Hello world!"""	,			add_special_tokens=__lowerCAmelCase	)	,			[0, 31414, 232, 328, 2]	)
														self.assertListEqual(
														    tokenizer.encode("""Hello world! cécé herlolip 418"""	,			add_special_tokens=__lowerCAmelCase	)	,			[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]	,			)






							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.tokenizer_class.from_pretrained("""roberta-base"""	)

														UpperCamelCase__					  =      tokenizer.encode("""sequence builders"""	,			add_special_tokens=__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.encode("""multi-sequence build"""	,			add_special_tokens=__lowerCAmelCase	)

														UpperCamelCase__					  =      tokenizer.encode(
														    """sequence builders"""	,			add_special_tokens=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.encode(
														    """sequence builders"""	,			"""multi-sequence build"""	,			add_special_tokens=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	)

														UpperCamelCase__					  =      tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase	,			__lowerCAmelCase	)

														assert encoded_sentence == encoded_text_from_decode
														assert encoded_pair == encoded_pair_from_decode






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.get_tokenizer()

														UpperCamelCase__					  =      """Encode this sequence."""
														UpperCamelCase__					  =      tokenizer.byte_encoder[""" """.encode("""utf-8"""	)[0]]

														# Testing encoder arguments
														UpperCamelCase__					  =      tokenizer.encode(__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.convert_ids_to_tokens(encoded[0]	)[0]
														self.assertNotEqual(__lowerCAmelCase	,			__lowerCAmelCase	)

														UpperCamelCase__					  =      tokenizer.encode(__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.convert_ids_to_tokens(encoded[0]	)[0]
														self.assertEqual(__lowerCAmelCase	,			__lowerCAmelCase	)

														tokenizer.add_special_tokens({"""bos_token""": """<s>"""}	)
														UpperCamelCase__					  =      tokenizer.encode(__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.convert_ids_to_tokens(encoded[1]	)[0]
														self.assertNotEqual(__lowerCAmelCase	,			__lowerCAmelCase	)

														# Testing spaces after special tokens
														UpperCamelCase__					  =      """<mask>"""
														tokenizer.add_special_tokens(
														    {"""mask_token""": AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	)}	)  # mask token has a left space
														UpperCamelCase__					  =      tokenizer.convert_tokens_to_ids(__lowerCAmelCase	)

														UpperCamelCase__					  =      """Encode <mask> sequence"""
														UpperCamelCase__					  =      """Encode <mask>sequence"""

														UpperCamelCase__					  =      tokenizer.encode(__lowerCAmelCase	)
														UpperCamelCase__					  =      encoded.index(__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1]	)[0]
														self.assertEqual(__lowerCAmelCase	,			__lowerCAmelCase	)

														UpperCamelCase__					  =      tokenizer.encode(__lowerCAmelCase	)
														UpperCamelCase__					  =      encoded.index(__lowerCAmelCase	)
														UpperCamelCase__					  =      tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1]	)[0]
														self.assertNotEqual(__lowerCAmelCase	,			__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														pass






							def 					_lowerCamelCase		(    self	):
														for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																					with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""	):
																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase	,			**__lowerCAmelCase	)
																												UpperCamelCase__					  =      self.tokenizer_class.from_pretrained(__lowerCAmelCase	,			**__lowerCAmelCase	)
																												UpperCamelCase__					  =      """A, <mask> AllenNLP sentence."""
																												UpperCamelCase__					  =      tokenizer_r.encode_plus(__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	,			return_token_type_ids=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_p.encode_plus(__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	,			return_token_type_ids=__lowerCAmelCase	)

																												# token_type_ids should put 0 everywhere
																												self.assertEqual(sum(tokens_r["""token_type_ids"""]	)	,			sum(tokens_p["""token_type_ids"""]	)	)

																												# attention_mask should put 1 everywhere, so sum over length should be 1
																												self.assertEqual(
																												    sum(tokens_r["""attention_mask"""]	) / len(tokens_r["""attention_mask"""]	)	,			sum(tokens_p["""attention_mask"""]	) / len(tokens_p["""attention_mask"""]	)	,			)

																												UpperCamelCase__					  =      tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""]	)
																												UpperCamelCase__					  =      tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""]	)

																												# Rust correctly handles the space before the mask while python doesnt
																												self.assertSequenceEqual(tokens_p["""input_ids"""]	,			[0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]	)
																												self.assertSequenceEqual(tokens_r["""input_ids"""]	,			[0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]	)

																												self.assertSequenceEqual(
																												    __lowerCAmelCase	,			["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""]	)
																												self.assertSequenceEqual(
																												    __lowerCAmelCase	,			["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""]	)






							def 					_lowerCamelCase		(    self	):
														for trim_offsets, add_prefix_space in itertools.product([True, False]	,			repeat=2	):
																					UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																					    self.tmpdirname	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)

																					UpperCamelCase__					  =      json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__()	)
																					UpperCamelCase__					  =      json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__()	)

																					self.assertEqual(pre_tokenizer_state["""add_prefix_space"""]	,			__lowerCAmelCase	)

																					self.assertEqual(post_processor_state["""add_prefix_space"""]	,			__lowerCAmelCase	)
																					self.assertEqual(post_processor_state["""trim_offsets"""]	,			__lowerCAmelCase	)







							def 					_lowerCamelCase		(    self	):
														# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
														# `trim_offsets`
														for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																					with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""	):
																												UpperCamelCase__					  =      """hello"""  # `hello` is a token in the vocabulary of `pretrained_name`
																												UpperCamelCase__					  =      f"""{text_of_1_token} {text_of_1_token}"""

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(0, len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(len(__lowerCAmelCase	) + 1, len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(0, len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(len(__lowerCAmelCase	) + 1, len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(0, len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(len(__lowerCAmelCase	), len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(0, len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(len(__lowerCAmelCase	), len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)

																												UpperCamelCase__					  =      f""" {text}"""

																												# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
																												#     pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
																												# )
																												# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
																												# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
																												# self.assertEqual(
																												#     encoding.offset_mapping[1],
																												#     (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
																												# )

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(1, 1 + len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(1 + len(__lowerCAmelCase	) + 1, 1 + len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(0, 1 + len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(1 + len(__lowerCAmelCase	), 1 + len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)

																												UpperCamelCase__					  =      self.rust_tokenizer_class.from_pretrained(
																												    __lowerCAmelCase	,			use_fast=__lowerCAmelCase	,			add_prefix_space=__lowerCAmelCase	,			trim_offsets=__lowerCAmelCase	)
																												UpperCamelCase__					  =      tokenizer_r(__lowerCAmelCase	,			return_offsets_mapping=__lowerCAmelCase	,			add_special_tokens=__lowerCAmelCase	)
																												self.assertEqual(encoding.offset_mapping[0]	,			(0, 1 + len(__lowerCAmelCase	))	)
																												self.assertEqual(
																												    encoding.offset_mapping[1]	,			(1 + len(__lowerCAmelCase	), 1 + len(__lowerCAmelCase	) + 1 + len(__lowerCAmelCase	))	,			)






# 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


