




import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
		from transformers import (
		    FlaxBertModel,
		    FlaxCLIPVisionModel,
		    FlaxVisionTextDualEncoderModel,
		    FlaxViTModel,
		    VisionTextDualEncoderConfig,
		    VisionTextDualEncoderProcessor,
		)
		from transformers.modeling_flax_pytorch_utils import (
		    convert_pytorch_state_dict_to_flax,
		    load_flax_weights_in_pytorch_model,
		)


if is_torch_available():
		import torch

		from transformers import VisionTextDualEncoderModel

if is_vision_available():
		from PIL import Image


def 		lowerCamelCase__       (						_A				):







	'''simple docstring'''





	if isinstance(_A	,      collections.abc.Iterable				):
		return x
	return (x, x)
@require_flax
class 						UpperCAmelCase  :







						'''simple docstring'''





						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	Union[str, Any]			,      __lowercase				:	List[Any]		):






							"""simple docstring"""






							pass






						def 			snake_case__		(		self				:	Tuple		):






							"""simple docstring"""






							pass






						def 			snake_case__		(		self				:	Dict		):






							"""simple docstring"""






							pass






						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	np.ndarray			,      __lowercase				:	np.ndarray			,      __lowercase				:	float		):






							"""simple docstring"""






							snake_case_						       =	np.abs((a - b)		).max()
							self.assertLessEqual(__lowercase			,      __lowercase			,      f"Difference between torch and flax is {diff} (>= {tol})."		)






						def 			snake_case__		(		self				:	Tuple			,      __lowercase				:	Optional[int]			,      __lowercase				:	int			,      __lowercase				:	Optional[Any]			,      __lowercase				:	Union[str, Any]			,      __lowercase				:	Union[str, Any]=None			,      **__lowercase				:	Tuple		):






							"""simple docstring"""






							snake_case_						       =	VisionTextDualEncoderConfig.from_vision_text_configs(__lowercase			,      __lowercase		)

							snake_case_						       =	FlaxVisionTextDualEncoderModel(__lowercase		)

							snake_case_						       =	model(input_ids=__lowercase			,      pixel_values=__lowercase			,      attention_mask=__lowercase		)

							self.assertEqual(output["text_embeds"].shape			,      (input_ids.shape[0], config.projection_dim)		)
							self.assertEqual(output["image_embeds"].shape			,      (pixel_values.shape[0], config.projection_dim)		)






						def 			snake_case__		(		self				:	List[str]			,      __lowercase				:	int			,      __lowercase				:	Any			,      __lowercase				:	Union[str, Any]			,      __lowercase				:	Dict			,      __lowercase				:	Tuple=None			,      **__lowercase				:	Dict		):






							"""simple docstring"""






							snake_case_       , snake_case_						       =	self.get_vision_text_model(__lowercase			,      __lowercase		)
							snake_case_						       =	{"vision_model": vision_model, "text_model": text_model}
							snake_case_						       =	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowercase		)

							snake_case_						       =	model(input_ids=__lowercase			,      pixel_values=__lowercase			,      attention_mask=__lowercase		)

							self.assertEqual(output["text_embeds"].shape			,      (input_ids.shape[0], model.config.projection_dim)		)
							self.assertEqual(output["image_embeds"].shape			,      (pixel_values.shape[0], model.config.projection_dim)		)






						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	List[str]			,      __lowercase				:	Any			,      __lowercase				:	Any			,      __lowercase				:	Union[str, Any]			,      __lowercase				:	Union[str, Any]=None			,      **__lowercase				:	str		):






							"""simple docstring"""






							snake_case_       , snake_case_						       =	self.get_vision_text_model(__lowercase			,      __lowercase		)
							snake_case_						       =	{"vision_model": vision_model, "text_model": text_model}
							snake_case_						       =	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowercase		)

							snake_case_						       =	model(input_ids=__lowercase			,      pixel_values=__lowercase			,      attention_mask=__lowercase		)
							snake_case_						       =	output[0]

							with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(__lowercase		)
								snake_case_						       =	FlaxVisionTextDualEncoderModel.from_pretrained(__lowercase		)

								snake_case_						       =	model(input_ids=__lowercase			,      pixel_values=__lowercase			,      attention_mask=__lowercase		)
								snake_case_						       =	after_output[0]
								snake_case_						       =	np.amax(np.abs(out_a - out_a		)		)
								self.assertLessEqual(__lowercase			,      1E-3		)






						def 			snake_case__		(		self				:	List[Any]			,      __lowercase				:	Union[str, Any]			,      __lowercase				:	Optional[Any]			,      __lowercase				:	Any			,      __lowercase				:	List[str]			,      __lowercase				:	int=None			,      **__lowercase				:	Any		):






							"""simple docstring"""






							snake_case_       , snake_case_						       =	self.get_vision_text_model(__lowercase			,      __lowercase		)
							snake_case_						       =	{"vision_model": vision_model, "text_model": text_model}
							snake_case_						       =	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowercase		)

							snake_case_						       =	model(
							    input_ids=__lowercase			,      pixel_values=__lowercase			,      attention_mask=__lowercase			,      output_attentions=__lowercase		)

							snake_case_						       =	output.vision_model_output.attentions
							self.assertEqual(len(__lowercase		)			,      vision_config.num_hidden_layers		)

							# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
							snake_case_						       =	to_atuple(vision_model.config.image_size		)
							snake_case_						       =	to_atuple(vision_model.config.patch_size		)
							snake_case_						       =	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
							snake_case_						       =	num_patches + 1
							self.assertEqual(vision_attentions[0].shape[-3:]			,      (vision_config.num_attention_heads, seq_len, seq_len)		)

							snake_case_						       =	output.text_model_output.attentions
							self.assertEqual(len(__lowercase		)			,      text_config.num_hidden_layers		)

							self.assertEqual(
							    text_attentions[0].shape[-3:]			,      (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,      )






						def 			snake_case__		(		self				:	int			,      __lowercase				:	int			,      __lowercase				:	Tuple			,      __lowercase				:	List[Any]		):






							"""simple docstring"""






							pt_model.to(__lowercase		)
							pt_model.eval()

							# prepare inputs
							snake_case_						       =	inputs_dict
							snake_case_						       =	{k: torch.tensor(v.tolist()		) for k, v in flax_inputs.items()}

							with torch.no_grad():
								snake_case_						       =	pt_model(**__lowercase		).to_tuple()

							snake_case_						       =	fx_model(**__lowercase		).to_tuple()
							self.assertEqual(len(__lowercase		)			,      len(__lowercase		)			,      "Output lengths differ between Flax and PyTorch"		)
							for fx_output, pt_output in zip(fx_outputs[:4]			,      pt_outputs[:4]		):
								self.assert_almost_equals(__lowercase			,      pt_output.numpy()			,      4E-2		)

							# PT -> Flax
							with tempfile.TemporaryDirectory() as tmpdirname:
								pt_model.save_pretrained(__lowercase		)
								snake_case_						       =	FlaxVisionTextDualEncoderModel.from_pretrained(__lowercase			,      from_pt=__lowercase		)

							snake_case_						       =	fx_model_loaded(**__lowercase		).to_tuple()
							self.assertEqual(len(__lowercase		)			,      len(__lowercase		)			,      "Output lengths differ between Flax and PyTorch"		)
							for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]			,      pt_outputs[:4]		):
								self.assert_almost_equals(__lowercase			,      pt_output.numpy()			,      4E-2		)

							# Flax -> PT
							with tempfile.TemporaryDirectory() as tmpdirname:
								fx_model.save_pretrained(__lowercase		)
								snake_case_						       =	VisionTextDualEncoderModel.from_pretrained(__lowercase			,      from_flax=__lowercase		)

							pt_model_loaded.to(__lowercase		)
							pt_model_loaded.eval()

							with torch.no_grad():
								snake_case_						       =	pt_model_loaded(**__lowercase		).to_tuple()

							self.assertEqual(len(__lowercase		)			,      len(__lowercase		)			,      "Output lengths differ between Flax and PyTorch"		)
							for fx_output, pt_output_loaded in zip(fx_outputs[:4]			,      pt_outputs_loaded[:4]		):
								self.assert_almost_equals(__lowercase			,      pt_output_loaded.numpy()			,      4E-2		)






						def 			snake_case__		(		self				:	List[Any]			,      __lowercase				:	Any			,      __lowercase				:	Optional[Any]			,      __lowercase				:	List[Any]		):






							"""simple docstring"""






							snake_case_						       =	VisionTextDualEncoderConfig.from_vision_text_configs(__lowercase			,      __lowercase		)

							snake_case_						       =	VisionTextDualEncoderModel(__lowercase		)
							snake_case_						       =	FlaxVisionTextDualEncoderModel(__lowercase		)

							snake_case_						       =	convert_pytorch_state_dict_to_flax(pt_model.state_dict()			,      __lowercase		)
							snake_case_						       =	fx_state

							self.check_pt_flax_equivalence(__lowercase			,      __lowercase			,      __lowercase		)






						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	int			,      __lowercase				:	Dict			,      __lowercase				:	Dict		):






							"""simple docstring"""






							snake_case_						       =	VisionTextDualEncoderConfig.from_vision_text_configs(__lowercase			,      __lowercase		)

							snake_case_						       =	VisionTextDualEncoderModel(__lowercase		)
							snake_case_						       =	FlaxVisionTextDualEncoderModel(__lowercase		)

							snake_case_						       =	load_flax_weights_in_pytorch_model(__lowercase			,      fx_model.params		)

							self.check_pt_flax_equivalence(__lowercase			,      __lowercase			,      __lowercase		)






						def 			snake_case__		(		self				:	Union[str, Any]		):






							"""simple docstring"""






							snake_case_						       =	self.prepare_config_and_inputs()
							self.check_model_from_pretrained_configs(**__lowercase		)






						def 			snake_case__		(		self				:	str		):






							"""simple docstring"""






							snake_case_						       =	self.prepare_config_and_inputs()
							self.check_vision_text_dual_encoder_from_pretrained(**__lowercase		)






						def 			snake_case__		(		self				:	Dict		):






							"""simple docstring"""






							snake_case_						       =	self.prepare_config_and_inputs()
							self.check_save_load(**__lowercase		)






						def 			snake_case__		(		self				:	List[Any]		):






							"""simple docstring"""






							snake_case_						       =	self.prepare_config_and_inputs()
							self.check_vision_text_output_attention(**__lowercase		)






						@is_pt_flax_cross_test
						def 			snake_case__		(		self				:	str		):






							"""simple docstring"""






							snake_case_						       =	self.prepare_config_and_inputs()
							snake_case_						       =	config_inputs_dict.pop("vision_config"		)
							snake_case_						       =	config_inputs_dict.pop("text_config"		)

							snake_case_						       =	config_inputs_dict

							self.check_equivalence_pt_to_flax(__lowercase			,      __lowercase			,      __lowercase		)
							self.check_equivalence_flax_to_pt(__lowercase			,      __lowercase			,      __lowercase		)






						@slow
						def 			snake_case__		(		self				:	str		):






							"""simple docstring"""






							snake_case_       , snake_case_						       =	self.get_pretrained_model_and_inputs()

							snake_case_						       =	model_a(**__lowercase		)
							snake_case_						       =	outputs[0]

							with tempfile.TemporaryDirectory() as tmp_dirname:
								model_a.save_pretrained(__lowercase		)
								snake_case_						       =	FlaxVisionTextDualEncoderModel.from_pretrained(__lowercase		)

								snake_case_						       =	model_a(**__lowercase		)
								snake_case_						       =	after_outputs[0]
								snake_case_						       =	np.amax(np.abs(out_a - out_a		)		)
								self.assertLessEqual(__lowercase			,      1E-5		)







@require_flax
class 						UpperCAmelCase  (							UpperCAmelCase__			,  unittest.TestCase     ):







						'''simple docstring'''





						def 			snake_case__		(		self				:	List[Any]		):






							"""simple docstring"""






							snake_case_						       =	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
							    "hf-internal-testing/tiny-random-vit"			,      "hf-internal-testing/tiny-bert"			,      vision_from_pt=__lowercase			,      text_from_pt=__lowercase			,      )
							snake_case_						       =	13
							snake_case_						       =	floats_tensor(
							    [
							        batch_size,
							        model.config.vision_config.num_channels,
							        model.config.vision_config.image_size,
							        model.config.vision_config.image_size,
							    ]		)
							snake_case_						       =	ids_tensor([batch_size, 4]			,      model.config.text_config.vocab_size		)
							snake_case_						       =	random_attention_mask([batch_size, 4]		)
							snake_case_						       =	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

							return model, inputs






						def 			snake_case__		(		self				:	List[str]			,      __lowercase				:	List[str]			,      __lowercase				:	Tuple		):






							"""simple docstring"""






							snake_case_						       =	FlaxViTModel(__lowercase		)
							snake_case_						       =	FlaxBertModel(__lowercase		)
							return vision_model, text_model






						def 			snake_case__		(		self				:	Optional[Any]		):






							"""simple docstring"""






							snake_case_						       =	FlaxViTModelTester(self		)
							snake_case_						       =	FlaxBertModelTester(self		)
							snake_case_						       =	vit_model_tester.prepare_config_and_inputs()
							snake_case_						       =	bert_model_tester.prepare_config_and_inputs()

							snake_case_       , snake_case_						       =	vision_config_and_inputs

							snake_case_       , snake_case_       , snake_case_       , snake_case_						       =	text_config_and_inputs

							# make sure that cross attention layers are added
							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": attention_mask,
							    "input_ids": input_ids,
							    "token_type_ids": token_type_ids,
							}







@require_torch
class 						UpperCAmelCase  (							UpperCAmelCase__			,  unittest.TestCase     ):







						'''simple docstring'''





						def 			snake_case__		(		self				:	Optional[Any]		):






							"""simple docstring"""






							snake_case_						       =	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
							    "hf-internal-testing/tiny-random-clip"			,      "hf-internal-testing/tiny-bert"			,      vision_from_pt=__lowercase			,      text_from_pt=__lowercase			,      )
							snake_case_						       =	13
							snake_case_						       =	floats_tensor(
							    [
							        batch_size,
							        model.config.vision_config.num_channels,
							        model.config.vision_config.image_size,
							        model.config.vision_config.image_size,
							    ]		)
							snake_case_						       =	ids_tensor([batch_size, 4]			,      model.config.text_config.vocab_size		)
							snake_case_						       =	random_attention_mask([batch_size, 4]		)
							snake_case_						       =	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

							return model, inputs






						def 			snake_case__		(		self				:	List[Any]			,      __lowercase				:	int			,      __lowercase				:	int		):






							"""simple docstring"""






							snake_case_						       =	FlaxCLIPVisionModel(__lowercase		)
							snake_case_						       =	FlaxBertModel(__lowercase		)
							return vision_model, text_model






						def 			snake_case__		(		self				:	Any		):






							"""simple docstring"""






							snake_case_						       =	FlaxCLIPVisionModelTester(self		)
							snake_case_						       =	FlaxBertModelTester(self		)
							snake_case_						       =	clip_model_tester.prepare_config_and_inputs()
							snake_case_						       =	bert_model_tester.prepare_config_and_inputs()

							snake_case_       , snake_case_						       =	vision_config_and_inputs

							snake_case_       , snake_case_       , snake_case_       , snake_case_						       =	text_config_and_inputs

							# make sure that cross attention layers are added
							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": attention_mask,
							    "input_ids": input_ids,
							    "token_type_ids": token_type_ids,
							}







@require_flax
@require_vision
class 						UpperCAmelCase  (							unittest.TestCase     ):







						'''simple docstring'''





						@slow
						def 			snake_case__		(		self				:	str		):






							"""simple docstring"""






							snake_case_						       =	FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"			,      logit_scale_init_value=1.0		)
							snake_case_						       =	VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"		)

							snake_case_						       =	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
							snake_case_						       =	processor(
							    text=["una foto di un gatto", "una foto di un cane"]			,      images=__lowercase			,      padding=__lowercase			,      return_tensors="np"		)

							snake_case_						       =	model(**__lowercase		)

							# verify the logits
							self.assertEqual(outputs.logits_per_image.shape			,      (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])		)
							self.assertEqual(
							    outputs.logits_per_text.shape			,      (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])			,      )

							snake_case_						       =	np.array([[1.228_4727, 0.310_4122]]		)

							self.assertTrue(np.allclose(outputs.logits_per_image			,      __lowercase			,      atol=1E-3		)		)






import tempfile

import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel

from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device

from ..test_pipelines_common import to_np
class 						UpperCAmelCase  :







						'''simple docstring'''





						def 			snake_case__		(		self				:	List[Any]		):






							"""simple docstring"""






							torch.manual_seed(0		)
							snake_case_						       =	TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5"		)

							torch.manual_seed(0		)
							snake_case_						       =	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5"		)

							torch.manual_seed(0		)
							snake_case_						       =	UNetaDConditionModel(
							    sample_size=32			,      layers_per_block=1			,      block_out_channels=[32, 64]			,      down_block_types=[
							        "ResnetDownsampleBlock2D",
							        "SimpleCrossAttnDownBlock2D",
							    ]			,      mid_block_type="UNetMidBlock2DSimpleCrossAttn"			,      up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"]			,      in_channels=3			,      out_channels=6			,      cross_attention_dim=32			,      encoder_hid_dim=32			,      attention_head_dim=8			,      addition_embed_type="text"			,      addition_embed_type_num_heads=2			,      cross_attention_norm="group_norm"			,      resnet_time_scale_shift="scale_shift"			,      act_fn="gelu"			,      )
							unet.set_attn_processor(AttnAddedKVProcessor()		)  # For reproducibility tests

							torch.manual_seed(0		)
							snake_case_						       =	DDPMScheduler(
							    num_train_timesteps=10_00			,      beta_schedule="squaredcos_cap_v2"			,      beta_start=0.0001			,      beta_end=0.02			,      thresholding=__lowercase			,      dynamic_thresholding_ratio=0.95			,      sample_max_value=1.0			,      prediction_type="epsilon"			,      variance_type="learned_range"			,      )

							torch.manual_seed(0		)
							snake_case_						       =	IFWatermarker()

							return {
							    "text_encoder": text_encoder,
							    "tokenizer": tokenizer,
							    "unet": unet,
							    "scheduler": scheduler,
							    "watermarker": watermarker,
							    "safety_checker": None,
							    "feature_extractor": None,
							}






						def 			snake_case__		(		self				:	List[str]		):






							"""simple docstring"""






							torch.manual_seed(0		)
							snake_case_						       =	TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5"		)

							torch.manual_seed(0		)
							snake_case_						       =	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5"		)

							torch.manual_seed(0		)
							snake_case_						       =	UNetaDConditionModel(
							    sample_size=32			,      layers_per_block=[1, 2]			,      block_out_channels=[32, 64]			,      down_block_types=[
							        "ResnetDownsampleBlock2D",
							        "SimpleCrossAttnDownBlock2D",
							    ]			,      mid_block_type="UNetMidBlock2DSimpleCrossAttn"			,      up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"]			,      in_channels=6			,      out_channels=6			,      cross_attention_dim=32			,      encoder_hid_dim=32			,      attention_head_dim=8			,      addition_embed_type="text"			,      addition_embed_type_num_heads=2			,      cross_attention_norm="group_norm"			,      resnet_time_scale_shift="scale_shift"			,      act_fn="gelu"			,      class_embed_type="timestep"			,      mid_block_scale_factor=1.414			,      time_embedding_act_fn="gelu"			,      time_embedding_dim=32			,      )
							unet.set_attn_processor(AttnAddedKVProcessor()		)  # For reproducibility tests

							torch.manual_seed(0		)
							snake_case_						       =	DDPMScheduler(
							    num_train_timesteps=10_00			,      beta_schedule="squaredcos_cap_v2"			,      beta_start=0.0001			,      beta_end=0.02			,      thresholding=__lowercase			,      dynamic_thresholding_ratio=0.95			,      sample_max_value=1.0			,      prediction_type="epsilon"			,      variance_type="learned_range"			,      )

							torch.manual_seed(0		)
							snake_case_						       =	DDPMScheduler(
							    num_train_timesteps=10_00			,      beta_schedule="squaredcos_cap_v2"			,      beta_start=0.0001			,      beta_end=0.02			,      )

							torch.manual_seed(0		)
							snake_case_						       =	IFWatermarker()

							return {
							    "text_encoder": text_encoder,
							    "tokenizer": tokenizer,
							    "unet": unet,
							    "scheduler": scheduler,
							    "image_noising_scheduler": image_noising_scheduler,
							    "watermarker": watermarker,
							    "safety_checker": None,
							    "feature_extractor": None,
							}






						def 			snake_case__		(		self				:	List[str]		):






							"""simple docstring"""






							snake_case_						       =	self.get_dummy_components()
							snake_case_						       =	self.pipeline_class(**__lowercase		)
							pipe.to(__lowercase		)
							pipe.set_progress_bar_config(disable=__lowercase		)

							snake_case_						       =	self.get_dummy_inputs(__lowercase		)

							snake_case_						       =	inputs["prompt"]
							snake_case_						       =	inputs["generator"]
							snake_case_						       =	inputs["num_inference_steps"]
							snake_case_						       =	inputs["output_type"]

							if "image" in inputs:
								snake_case_						       =	inputs["image"]
							else:
								snake_case_						       =	None

							if "mask_image" in inputs:
								snake_case_						       =	inputs["mask_image"]
							else:
								snake_case_						       =	None

							if "original_image" in inputs:
								snake_case_						       =	inputs["original_image"]
							else:
								snake_case_						       =	None

							snake_case_       , snake_case_						       =	pipe.encode_prompt(__lowercase		)

							# inputs with prompt converted to embeddings
							snake_case_						       =	{
							    "prompt_embeds": prompt_embeds,
							    "negative_prompt_embeds": negative_prompt_embeds,
							    "generator": generator,
							    "num_inference_steps": num_inference_steps,
							    "output_type": output_type,
							}

							if image is not None:
								snake_case_						       =	image

							if mask_image is not None:
								snake_case_						       =	mask_image

							if original_image is not None:
								snake_case_						       =	original_image

							# set all optional components to None
							for optional_component in pipe._optional_components:
								setattr(__lowercase			,      __lowercase			,      __lowercase		)

							snake_case_						       =	pipe(**__lowercase		)[0]

							with tempfile.TemporaryDirectory() as tmpdir:
								pipe.save_pretrained(__lowercase		)
								snake_case_						       =	self.pipeline_class.from_pretrained(__lowercase		)
								pipe_loaded.to(__lowercase		)
								pipe_loaded.set_progress_bar_config(disable=__lowercase		)

							pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()		)  # For reproducibility tests

							for optional_component in pipe._optional_components:
								self.assertTrue(
								    getattr(__lowercase			,      __lowercase		) is None			,      f"`{optional_component}` did not stay set to None after loading."			,      )

							snake_case_						       =	self.get_dummy_inputs(__lowercase		)

							snake_case_						       =	inputs["generator"]
							snake_case_						       =	inputs["num_inference_steps"]
							snake_case_						       =	inputs["output_type"]

							# inputs with prompt converted to embeddings
							snake_case_						       =	{
							    "prompt_embeds": prompt_embeds,
							    "negative_prompt_embeds": negative_prompt_embeds,
							    "generator": generator,
							    "num_inference_steps": num_inference_steps,
							    "output_type": output_type,
							}

							if image is not None:
								snake_case_						       =	image

							if mask_image is not None:
								snake_case_						       =	mask_image

							if original_image is not None:
								snake_case_						       =	original_image

							snake_case_						       =	pipe_loaded(**__lowercase		)[0]

							snake_case_						       =	np.abs(to_np(__lowercase		) - to_np(__lowercase		)		).max()
							self.assertLess(__lowercase			,      1E-4		)






						def 			snake_case__		(		self				:	Union[str, Any]		):






							"""simple docstring"""






							snake_case_						       =	self.get_dummy_components()
							snake_case_						       =	self.pipeline_class(**__lowercase		)
							pipe.to(__lowercase		)
							pipe.set_progress_bar_config(disable=__lowercase		)

							snake_case_						       =	self.get_dummy_inputs(__lowercase		)
							snake_case_						       =	pipe(**__lowercase		)[0]

							with tempfile.TemporaryDirectory() as tmpdir:
								pipe.save_pretrained(__lowercase		)
								snake_case_						       =	self.pipeline_class.from_pretrained(__lowercase		)
								pipe_loaded.to(__lowercase		)
								pipe_loaded.set_progress_bar_config(disable=__lowercase		)

							pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()		)  # For reproducibility tests

							snake_case_						       =	self.get_dummy_inputs(__lowercase		)
							snake_case_						       =	pipe_loaded(**__lowercase		)[0]

							snake_case_						       =	np.abs(to_np(__lowercase		) - to_np(__lowercase		)		).max()
							self.assertLess(__lowercase			,      1E-4		)
