


import gc
import random
import unittest

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

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

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


enable_full_determinism()



class  lowerCAmelCase				(				_A      ,				_A      ,				_A      ,				unittest.TestCase							):
	_lowerCamelCase   :					Optional[int]			      = StableDiffusionInstructPixaPixPipeline
	_lowerCamelCase   :					Union[str, Any]			      = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width""", """cross_attention_kwargs"""}
	_lowerCamelCase   :					int			      = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
	_lowerCamelCase   :					int			      = IMAGE_TO_IMAGE_IMAGE_PARAMS
	_lowerCamelCase   :					str			      = IMAGE_TO_IMAGE_IMAGE_PARAMS



	def 				lowercase     (					self    ):
		torch.manual_seed(0    )
		lowerCAmelCase					:    Optional[int]      							= UNetaDConditionModel(
		    block_out_channels=(32, 64) ,					layers_per_block=2 ,					sample_size=32 ,					in_channels=8 ,					out_channels=4 ,					down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,					up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,					cross_attention_dim=32 ,					)
		lowerCAmelCase					:    Union[str, Any]      							= PNDMScheduler(skip_prk_steps=snake_case__    )
		torch.manual_seed(0    )
		lowerCAmelCase					:    Optional[Any]      							= 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					:    Optional[int]      							= CLIPTextConfig(
		    bos_token_id=0 ,					eos_token_id=2 ,					hidden_size=32 ,					intermediate_size=37 ,					layer_norm_eps=1e-0_5 ,					num_attention_heads=4 ,					num_hidden_layers=5 ,					pad_token_id=1 ,					vocab_size=1000 ,					)
		lowerCAmelCase					:    Optional[Any]      							= CLIPTextModel(snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

		lowerCAmelCase					:    Optional[Any]      							= {
		    "unet": unet,
		    "scheduler": scheduler,
		    "vae": vae,
		    "text_encoder": text_encoder,
		    "tokenizer": tokenizer,
		    "safety_checker": None,
		    "feature_extractor": None,
		}
		return components



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



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

		lowerCAmelCase					:    Dict      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    Optional[Any]      							= sd_pipe(**snake_case__    ).images
		lowerCAmelCase					:    Optional[Any]      							= image[0, -3:, -3:, -1]
		assert image.shape == (1, 32, 32, 3)
		lowerCAmelCase					:    Union[str, Any]      							= np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5]    )

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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= "cpu"  # ensure determinism for the device-dependent torch.Generator
		lowerCAmelCase					:    Any      							= self.get_dummy_components()
		lowerCAmelCase					:    List[Any]      							= StableDiffusionInstructPixaPixPipeline(**snake_case__    )
		lowerCAmelCase					:    Optional[Any]      							= sd_pipe.to(snake_case__    )
		sd_pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Optional[int]      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    List[str]      							= "french fries"
		lowerCAmelCase					:    int      							= sd_pipe(**snake_case__ ,					negative_prompt=snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= output.images
		lowerCAmelCase					:    Any      							= image[0, -3:, -3:, -1]

		assert image.shape == (1, 32, 32, 3)
		lowerCAmelCase					:    Optional[int]      							= np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1]    )

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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[Any]      							= "cpu"  # ensure determinism for the device-dependent torch.Generator
		lowerCAmelCase					:    List[Any]      							= self.get_dummy_components()
		lowerCAmelCase					:    Optional[int]      							= StableDiffusionInstructPixaPixPipeline(**snake_case__    )
		lowerCAmelCase					:    List[Any]      							= sd_pipe.to(snake_case__    )
		sd_pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Tuple      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    int      							= [inputs["prompt"]] * 2

		lowerCAmelCase					:    Optional[Any]      							= np.array(inputs['image']    ).astype(np.floataa    ) / 2_5_5.0
		lowerCAmelCase					:    Union[str, Any]      							= torch.from_numpy(snake_case__    ).unsqueeze(0    ).to(snake_case__    )
		lowerCAmelCase					:    Tuple      							= image / 2 + 0.5
		lowerCAmelCase					:    Tuple      							= image.permute(0 ,					3 ,					1 ,					2    )
		lowerCAmelCase					:    Dict      							= image.repeat(2 ,					1 ,					1 ,					1    )

		lowerCAmelCase					:    List[Any]      							= sd_pipe(**snake_case__    ).images
		lowerCAmelCase					:    Tuple      							= image[-1, -3:, -3:, -1]

		assert image.shape == (2, 32, 32, 3)
		lowerCAmelCase					:    str      							= np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9]    )

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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    int      							= "cpu"  # ensure determinism for the device-dependent torch.Generator
		lowerCAmelCase					:    Dict      							= self.get_dummy_components()
		lowerCAmelCase					:    Any      							= EulerAncestralDiscreteScheduler(
		    beta_start=0.0_0_0_8_5 ,					beta_end=0.0_1_2 ,					beta_schedule='scaled_linear'    )
		lowerCAmelCase					:    Tuple      							= StableDiffusionInstructPixaPixPipeline(**snake_case__    )
		lowerCAmelCase					:    str      							= sd_pipe.to(snake_case__    )
		sd_pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Dict      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    Dict      							= sd_pipe(**snake_case__    ).images
		lowerCAmelCase					:    int      							= image[0, -3:, -3:, -1]

		lowerCAmelCase					:    Optional[int]      							= [round(snake_case__ ,					4    ) for x in image_slice.flatten().tolist()]
		print(','.join([str(snake_case__    ) for x in slice]    )    )

		assert image.shape == (1, 32, 32, 3)
		lowerCAmelCase					:    str      							= np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6]    )

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



	def 				lowercase     (					self    ):
		super().test_inference_batch_single_identical(expected_max_diff=3e-3    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[Any]      							= self.get_dummy_components()
		lowerCAmelCase					:    List[Any]      							= StableDiffusionInstructPixaPixPipeline(**snake_case__    )
		lowerCAmelCase					:    List[Any]      							= VaeImageProcessor(do_resize=snake_case__ ,					do_normalize=snake_case__    )
		lowerCAmelCase					:    Any      							= pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Union[str, Any]      							= pipe(**self.get_dummy_inputs_by_type(snake_case__ ,					input_image_type='pt'    )    )[0]

		lowerCAmelCase					:    Dict      							= components["vae"]
		lowerCAmelCase					:    Optional[Any]      							= self.get_dummy_inputs_by_type(snake_case__ ,					input_image_type='pt'    )

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

		lowerCAmelCase					:    Dict      							= pipe(**snake_case__    )[0]

		lowerCAmelCase					:    str      							= np.abs(out - out_latents_inputs    ).max()
		self.assertLess(snake_case__ ,					1e-4 ,					'passing latents as image input generate different result from passing image'    )



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



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[Any]      							= StableDiffusionInstructPixaPixPipeline.from_pretrained(
		    'timbrooks/instruct-pix2pix' ,					safety_checker=snake_case__    )
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )
		pipe.enable_attention_slicing()

		lowerCAmelCase					:    int      							= self.get_inputs()
		lowerCAmelCase					:    List[str]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    Dict      							= image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 512, 512, 3)
		lowerCAmelCase					:    Dict      							= np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5]    )

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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[str]      							= StableDiffusionInstructPixaPixPipeline.from_pretrained(
		    'timbrooks/instruct-pix2pix' ,					safety_checker=snake_case__    )
		lowerCAmelCase					:    List[str]      							= LMSDiscreteScheduler.from_config(pipe.scheduler.config    )
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )
		pipe.enable_attention_slicing()

		lowerCAmelCase					:    Optional[Any]      							= self.get_inputs()
		lowerCAmelCase					:    Dict      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    Any      							= image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 512, 512, 3)
		lowerCAmelCase					:    Optional[Any]      							= np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1]    )

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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= StableDiffusionInstructPixaPixPipeline.from_pretrained(
		    'timbrooks/instruct-pix2pix' ,					safety_checker=snake_case__    )
		lowerCAmelCase					:    Any      							= DDIMScheduler.from_config(pipe.scheduler.config    )
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )
		pipe.enable_attention_slicing()

		lowerCAmelCase					:    Tuple      							= self.get_inputs()
		lowerCAmelCase					:    str      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    Union[str, Any]      							= image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 512, 512, 3)
		lowerCAmelCase					:    List[Any]      							= np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3]    )

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



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= 0

		def callback_fn(snake_case__ ,					snake_case__ ,					snake_case__    ) -> None:
			lowerCAmelCase					:    Union[str, Any]      							= True
			nonlocal number_of_steps
			number_of_steps += 1
			if step == 1:
				lowerCAmelCase					:    Optional[int]      							= latents.detach().cpu().numpy()
				assert latents.shape == (1, 4, 64, 64)
				lowerCAmelCase					:    Any      							= latents[0, -3:, -3:, -1]
				lowerCAmelCase					:    Optional[Any]      							= np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3]    )

				assert np.abs(latents_slice.flatten() - expected_slice    ).max() < 5e-2
			elif step == 2:
				lowerCAmelCase					:    Tuple      							= latents.detach().cpu().numpy()
				assert latents.shape == (1, 4, 64, 64)
				lowerCAmelCase					:    List[str]      							= latents[0, -3:, -3:, -1]
				lowerCAmelCase					:    Tuple      							= np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5]    )

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

		lowerCAmelCase					:    Any      							= False

		lowerCAmelCase					:    Tuple      							= StableDiffusionInstructPixaPixPipeline.from_pretrained(
		    'timbrooks/instruct-pix2pix' ,					safety_checker=snake_case__ ,					torch_dtype=torch.floataa    )
		lowerCAmelCase					:    Optional[Any]      							= pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )
		pipe.enable_attention_slicing()

		lowerCAmelCase					:    Dict      							= self.get_inputs()
		pipe(**snake_case__ ,					callback=snake_case__ ,					callback_steps=1    )
		assert callback_fn.has_been_called
		assert number_of_steps == 3



	def 				lowercase     (					self    ):
		torch.cuda.empty_cache()
		torch.cuda.reset_max_memory_allocated()
		torch.cuda.reset_peak_memory_stats()

		lowerCAmelCase					:    int      							= StableDiffusionInstructPixaPixPipeline.from_pretrained(
		    'timbrooks/instruct-pix2pix' ,					safety_checker=snake_case__ ,					torch_dtype=torch.floataa    )
		lowerCAmelCase					:    int      							= pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )
		pipe.enable_attention_slicing(1    )
		pipe.enable_sequential_cpu_offload()

		lowerCAmelCase					:    Any      							= self.get_inputs()
		lowerCAmelCase					:    int      							= pipe(**snake_case__    )

		lowerCAmelCase					:    Dict      							= torch.cuda.max_memory_allocated()
		# make sure that less than 2.2 GB is allocated
		assert mem_bytes < 2.2 * 10**9



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Any      							= self.get_inputs()
		# resize to resolution that is divisible by 8 but not 16 or 32
		lowerCAmelCase					:    Optional[int]      							= inputs["image"].resize((504, 504)    )

		lowerCAmelCase					:    List[Any]      							= "timbrooks/instruct-pix2pix"
		lowerCAmelCase					:    List[str]      							= StableDiffusionInstructPixaPixPipeline.from_pretrained(
		    snake_case__ ,					safety_checker=snake_case__ ,					)
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )
		pipe.enable_attention_slicing()

		lowerCAmelCase					:    Optional[int]      							= pipe(**snake_case__    )
		lowerCAmelCase					:    Any      							= output.images[0]

		lowerCAmelCase					:    Union[str, Any]      							= image[255:258, 383:386, -1]

		assert image.shape == (504, 504, 3)
		lowerCAmelCase					:    Optional[int]      							= np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0]    )

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




'''simple docstring'''




import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class  lowerCAmelCase				(				a      ,				unittest.TestCase							):
	_lowerCamelCase   :					List[Any]			      = LDMTextToImagePipeline
	_lowerCamelCase   :					Optional[Any]			      = TEXT_TO_IMAGE_PARAMS - {
	    """negative_prompt""",
	    """negative_prompt_embeds""",
	    """cross_attention_kwargs""",
	    """prompt_embeds""",
	}
	_lowerCamelCase   :					List[str]			      = PipelineTesterMixin.required_optional_params - {
	    """num_images_per_prompt""",
	    """callback""",
	    """callback_steps""",
	}
	_lowerCamelCase   :					Union[str, Any]			      = TEXT_TO_IMAGE_BATCH_PARAMS
	_lowerCamelCase   :					Optional[int]			      = False



	def 				lowercase     (					self    ):
		torch.manual_seed(0    )
		lowerCAmelCase					:    Dict      							= 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 ,					)
		lowerCAmelCase					:    int      							= DDIMScheduler(
		    beta_start=0.0_0_0_8_5 ,					beta_end=0.0_1_2 ,					beta_schedule='scaled_linear' ,					clip_sample=snake_case__ ,					set_alpha_to_one=snake_case__ ,					)
		torch.manual_seed(0    )
		lowerCAmelCase					:    str      							= 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					:    Any      							= CLIPTextConfig(
		    bos_token_id=0 ,					eos_token_id=2 ,					hidden_size=32 ,					intermediate_size=37 ,					layer_norm_eps=1e-0_5 ,					num_attention_heads=4 ,					num_hidden_layers=5 ,					pad_token_id=1 ,					vocab_size=1000 ,					)
		lowerCAmelCase					:    str      							= CLIPTextModel(snake_case__    )
		lowerCAmelCase					:    str      							= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

		lowerCAmelCase					:    List[Any]      							= {
		    'unet': unet,
		    'scheduler': scheduler,
		    'vqvae': vae,
		    'bert': text_encoder,
		    'tokenizer': tokenizer,
		}
		return components



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=0    ):
		if str(snake_case__    ).startswith('mps'    ):
			lowerCAmelCase					:    Optional[int]      							= torch.manual_seed(snake_case__    )
		else:
			lowerCAmelCase					:    str      							= torch.Generator(device=snake_case__    ).manual_seed(snake_case__    )
		lowerCAmelCase					:    Tuple      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'generator': generator,
		    'num_inference_steps': 2,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[str]      							= 'cpu'  # ensure determinism for the device-dependent torch.Generator

		lowerCAmelCase					:    Optional[Any]      							= self.get_dummy_components()
		lowerCAmelCase					:    Optional[Any]      							= LDMTextToImagePipeline(**snake_case__    )
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Tuple      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    Union[str, Any]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    str      							= image[0, -3:, -3:, -1]

		assert image.shape == (1, 16, 16, 3)
		lowerCAmelCase					:    List[Any]      							= np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]    )

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



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



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=torch.floataa ,					snake_case__=0    ):
		lowerCAmelCase					:    List[str]      							= torch.manual_seed(snake_case__    )
		lowerCAmelCase					:    int      							= np.random.RandomState(snake_case__    ).standard_normal((1, 4, 32, 32)    )
		lowerCAmelCase					:    Optional[Any]      							= torch.from_numpy(snake_case__    ).to(device=snake_case__ ,					dtype=snake_case__    )
		lowerCAmelCase					:    List[str]      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'latents': latents,
		    'generator': generator,
		    'num_inference_steps': 3,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'    ).to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Optional[Any]      							= self.get_inputs(snake_case__    )
		lowerCAmelCase					:    List[Any]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    str      							= image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 256, 256, 3)
		lowerCAmelCase					:    Tuple      							= np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]    )
		lowerCAmelCase					:    int      							= np.abs(expected_slice - image_slice    ).max()
		assert max_diff < 1e-3



@nightly
@require_torch_gpu
class  lowerCAmelCase				(				unittest.TestCase							):



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=torch.floataa ,					snake_case__=0    ):
		lowerCAmelCase					:    List[str]      							= torch.manual_seed(snake_case__    )
		lowerCAmelCase					:    Any      							= np.random.RandomState(snake_case__    ).standard_normal((1, 4, 32, 32)    )
		lowerCAmelCase					:    List[Any]      							= torch.from_numpy(snake_case__    ).to(device=snake_case__ ,					dtype=snake_case__    )
		lowerCAmelCase					:    List[str]      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'latents': latents,
		    'generator': generator,
		    'num_inference_steps': 50,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'    ).to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    int      							= self.get_inputs(snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= pipe(**snake_case__    ).images[0]

		lowerCAmelCase					:    Optional[int]      							= load_numpy(
		    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'    )
		lowerCAmelCase					:    List[str]      							= np.abs(expected_image - image    ).max()
		assert max_diff < 1e-3
