Path: blob/main/tests/pipelines/stable_diffusion/test_stable_diffusion_pix2pix_zero.py
1451 views
# coding=utf-81# Copyright 2023 HuggingFace Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.1415import gc16import unittest1718import numpy as np19import torch20from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer2122from diffusers import (23AutoencoderKL,24DDIMInverseScheduler,25DDIMScheduler,26DDPMScheduler,27EulerAncestralDiscreteScheduler,28LMSDiscreteScheduler,29StableDiffusionPix2PixZeroPipeline,30UNet2DConditionModel,31)32from diffusers.utils import load_numpy, slow, torch_device33from diffusers.utils.testing_utils import load_image, load_pt, require_torch_gpu, skip_mps3435from ...pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS36from ...test_pipelines_common import PipelineTesterMixin373839torch.backends.cuda.matmul.allow_tf32 = False404142@skip_mps43class StableDiffusionPix2PixZeroPipelineFastTests(PipelineTesterMixin, unittest.TestCase):44pipeline_class = StableDiffusionPix2PixZeroPipeline45params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS46batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS4748@classmethod49def setUpClass(cls):50cls.source_embeds = load_pt(51"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/src_emb_0.pt"52)5354cls.target_embeds = load_pt(55"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/tgt_emb_0.pt"56)5758def get_dummy_components(self):59torch.manual_seed(0)60unet = UNet2DConditionModel(61block_out_channels=(32, 64),62layers_per_block=2,63sample_size=32,64in_channels=4,65out_channels=4,66down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),67up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),68cross_attention_dim=32,69)70scheduler = DDIMScheduler()71torch.manual_seed(0)72vae = AutoencoderKL(73block_out_channels=[32, 64],74in_channels=3,75out_channels=3,76down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],77up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],78latent_channels=4,79)80torch.manual_seed(0)81text_encoder_config = CLIPTextConfig(82bos_token_id=0,83eos_token_id=2,84hidden_size=32,85intermediate_size=37,86layer_norm_eps=1e-05,87num_attention_heads=4,88num_hidden_layers=5,89pad_token_id=1,90vocab_size=1000,91)92text_encoder = CLIPTextModel(text_encoder_config)93tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")9495components = {96"unet": unet,97"scheduler": scheduler,98"vae": vae,99"text_encoder": text_encoder,100"tokenizer": tokenizer,101"safety_checker": None,102"feature_extractor": None,103"inverse_scheduler": None,104"caption_generator": None,105"caption_processor": None,106}107return components108109def get_dummy_inputs(self, device, seed=0):110generator = torch.manual_seed(seed)111112inputs = {113"prompt": "A painting of a squirrel eating a burger",114"generator": generator,115"num_inference_steps": 2,116"guidance_scale": 6.0,117"cross_attention_guidance_amount": 0.15,118"source_embeds": self.source_embeds,119"target_embeds": self.target_embeds,120"output_type": "numpy",121}122return inputs123124def test_stable_diffusion_pix2pix_zero_default_case(self):125device = "cpu" # ensure determinism for the device-dependent torch.Generator126components = self.get_dummy_components()127sd_pipe = StableDiffusionPix2PixZeroPipeline(**components)128sd_pipe = sd_pipe.to(device)129sd_pipe.set_progress_bar_config(disable=None)130131inputs = self.get_dummy_inputs(device)132image = sd_pipe(**inputs).images133image_slice = image[0, -3:, -3:, -1]134assert image.shape == (1, 64, 64, 3)135expected_slice = np.array([0.5184, 0.503, 0.4917, 0.4022, 0.3455, 0.464, 0.5324, 0.5323, 0.4894])136137assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3138139def test_stable_diffusion_pix2pix_zero_negative_prompt(self):140device = "cpu" # ensure determinism for the device-dependent torch.Generator141components = self.get_dummy_components()142sd_pipe = StableDiffusionPix2PixZeroPipeline(**components)143sd_pipe = sd_pipe.to(device)144sd_pipe.set_progress_bar_config(disable=None)145146inputs = self.get_dummy_inputs(device)147negative_prompt = "french fries"148output = sd_pipe(**inputs, negative_prompt=negative_prompt)149image = output.images150image_slice = image[0, -3:, -3:, -1]151152assert image.shape == (1, 64, 64, 3)153expected_slice = np.array([0.5464, 0.5072, 0.5012, 0.4124, 0.3624, 0.466, 0.5413, 0.5468, 0.4927])154155assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3156157def test_stable_diffusion_pix2pix_zero_euler(self):158device = "cpu" # ensure determinism for the device-dependent torch.Generator159components = self.get_dummy_components()160components["scheduler"] = EulerAncestralDiscreteScheduler(161beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear"162)163sd_pipe = StableDiffusionPix2PixZeroPipeline(**components)164sd_pipe = sd_pipe.to(device)165sd_pipe.set_progress_bar_config(disable=None)166167inputs = self.get_dummy_inputs(device)168image = sd_pipe(**inputs).images169image_slice = image[0, -3:, -3:, -1]170171assert image.shape == (1, 64, 64, 3)172expected_slice = np.array([0.5114, 0.5051, 0.5222, 0.5279, 0.5037, 0.5156, 0.4604, 0.4966, 0.504])173174assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3175176def test_stable_diffusion_pix2pix_zero_ddpm(self):177device = "cpu" # ensure determinism for the device-dependent torch.Generator178components = self.get_dummy_components()179components["scheduler"] = DDPMScheduler()180sd_pipe = StableDiffusionPix2PixZeroPipeline(**components)181sd_pipe = sd_pipe.to(device)182sd_pipe.set_progress_bar_config(disable=None)183184inputs = self.get_dummy_inputs(device)185image = sd_pipe(**inputs).images186image_slice = image[0, -3:, -3:, -1]187188assert image.shape == (1, 64, 64, 3)189expected_slice = np.array([0.5185, 0.5027, 0.492, 0.401, 0.3445, 0.464, 0.5321, 0.5327, 0.4892])190191assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3192193# Non-determinism caused by the scheduler optimizing the latent inputs during inference194@unittest.skip("non-deterministic pipeline")195def test_inference_batch_single_identical(self):196return super().test_inference_batch_single_identical()197198199@slow200@require_torch_gpu201class StableDiffusionPix2PixZeroPipelineSlowTests(unittest.TestCase):202def tearDown(self):203super().tearDown()204gc.collect()205torch.cuda.empty_cache()206207@classmethod208def setUpClass(cls):209cls.source_embeds = load_pt(210"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/cat.pt"211)212213cls.target_embeds = load_pt(214"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/dog.pt"215)216217def get_inputs(self, seed=0):218generator = torch.manual_seed(seed)219220inputs = {221"prompt": "turn him into a cyborg",222"generator": generator,223"num_inference_steps": 3,224"guidance_scale": 7.5,225"cross_attention_guidance_amount": 0.15,226"source_embeds": self.source_embeds,227"target_embeds": self.target_embeds,228"output_type": "numpy",229}230return inputs231232def test_stable_diffusion_pix2pix_zero_default(self):233pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(234"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16235)236pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)237pipe.to(torch_device)238pipe.set_progress_bar_config(disable=None)239pipe.enable_attention_slicing()240241inputs = self.get_inputs()242image = pipe(**inputs).images243image_slice = image[0, -3:, -3:, -1].flatten()244245assert image.shape == (1, 512, 512, 3)246expected_slice = np.array([0.5742, 0.5757, 0.5747, 0.5781, 0.5688, 0.5713, 0.5742, 0.5664, 0.5747])247248assert np.abs(expected_slice - image_slice).max() < 5e-2249250def test_stable_diffusion_pix2pix_zero_k_lms(self):251pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(252"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16253)254pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)255pipe.to(torch_device)256pipe.set_progress_bar_config(disable=None)257pipe.enable_attention_slicing()258259inputs = self.get_inputs()260image = pipe(**inputs).images261image_slice = image[0, -3:, -3:, -1].flatten()262263assert image.shape == (1, 512, 512, 3)264expected_slice = np.array([0.6367, 0.5459, 0.5146, 0.5479, 0.4905, 0.4753, 0.4961, 0.4629, 0.4624])265266assert np.abs(expected_slice - image_slice).max() < 5e-2267268def test_stable_diffusion_pix2pix_zero_intermediate_state(self):269number_of_steps = 0270271def callback_fn(step: int, timestep: int, latents: torch.FloatTensor) -> None:272callback_fn.has_been_called = True273nonlocal number_of_steps274number_of_steps += 1275if step == 1:276latents = latents.detach().cpu().numpy()277assert latents.shape == (1, 4, 64, 64)278latents_slice = latents[0, -3:, -3:, -1]279expected_slice = np.array([0.1345, 0.268, 0.1539, 0.0726, 0.0959, 0.2261, -0.2673, 0.0277, -0.2062])280281assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2282elif step == 2:283latents = latents.detach().cpu().numpy()284assert latents.shape == (1, 4, 64, 64)285latents_slice = latents[0, -3:, -3:, -1]286expected_slice = np.array([0.1393, 0.2637, 0.1617, 0.0724, 0.0987, 0.2271, -0.2666, 0.0299, -0.2104])287288assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2289290callback_fn.has_been_called = False291292pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(293"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16294)295pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)296pipe = pipe.to(torch_device)297pipe.set_progress_bar_config(disable=None)298pipe.enable_attention_slicing()299300inputs = self.get_inputs()301pipe(**inputs, callback=callback_fn, callback_steps=1)302assert callback_fn.has_been_called303assert number_of_steps == 3304305def test_stable_diffusion_pipeline_with_sequential_cpu_offloading(self):306torch.cuda.empty_cache()307torch.cuda.reset_max_memory_allocated()308torch.cuda.reset_peak_memory_stats()309310pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(311"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16312)313pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)314pipe = pipe.to(torch_device)315pipe.set_progress_bar_config(disable=None)316pipe.enable_attention_slicing(1)317pipe.enable_sequential_cpu_offload()318319inputs = self.get_inputs()320_ = pipe(**inputs)321322mem_bytes = torch.cuda.max_memory_allocated()323# make sure that less than 8.2 GB is allocated324assert mem_bytes < 8.2 * 10**9325326327@slow328@require_torch_gpu329class InversionPipelineSlowTests(unittest.TestCase):330def tearDown(self):331super().tearDown()332gc.collect()333torch.cuda.empty_cache()334335@classmethod336def setUpClass(cls):337raw_image = load_image(338"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/cat_6.png"339)340341raw_image = raw_image.convert("RGB").resize((512, 512))342343cls.raw_image = raw_image344345def test_stable_diffusion_pix2pix_inversion(self):346pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(347"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16348)349pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)350351caption = "a photography of a cat with flowers"352pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)353pipe.enable_model_cpu_offload()354pipe.set_progress_bar_config(disable=None)355356generator = torch.manual_seed(0)357output = pipe.invert(caption, image=self.raw_image, generator=generator, num_inference_steps=10)358inv_latents = output[0]359360image_slice = inv_latents[0, -3:, -3:, -1].flatten()361362assert inv_latents.shape == (1, 4, 64, 64)363expected_slice = np.array([0.8447, -0.0730, 0.7588, -1.2070, -0.4678, 0.1511, -0.8555, 1.1816, -0.7666])364365assert np.abs(expected_slice - image_slice.cpu().numpy()).max() < 5e-2366367def test_stable_diffusion_2_pix2pix_inversion(self):368pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(369"stabilityai/stable-diffusion-2-1", safety_checker=None, torch_dtype=torch.float16370)371pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)372373caption = "a photography of a cat with flowers"374pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)375pipe.enable_model_cpu_offload()376pipe.set_progress_bar_config(disable=None)377378generator = torch.manual_seed(0)379output = pipe.invert(caption, image=self.raw_image, generator=generator, num_inference_steps=10)380inv_latents = output[0]381382image_slice = inv_latents[0, -3:, -3:, -1].flatten()383384assert inv_latents.shape == (1, 4, 64, 64)385expected_slice = np.array([0.8970, -0.1611, 0.4766, -1.1162, -0.5923, 0.1050, -0.9678, 1.0537, -0.6050])386387assert np.abs(expected_slice - image_slice.cpu().numpy()).max() < 5e-2388389def test_stable_diffusion_pix2pix_full(self):390# numpy array of https://huggingface.co/datasets/hf-internal-testing/diffusers-images/blob/main/pix2pix/dog.png391expected_image = load_numpy(392"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/dog.npy"393)394395pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(396"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16397)398pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)399400caption = "a photography of a cat with flowers"401pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)402pipe.enable_model_cpu_offload()403pipe.set_progress_bar_config(disable=None)404405generator = torch.manual_seed(0)406output = pipe.invert(caption, image=self.raw_image, generator=generator)407inv_latents = output[0]408409source_prompts = 4 * ["a cat sitting on the street", "a cat playing in the field", "a face of a cat"]410target_prompts = 4 * ["a dog sitting on the street", "a dog playing in the field", "a face of a dog"]411412source_embeds = pipe.get_embeds(source_prompts)413target_embeds = pipe.get_embeds(target_prompts)414415image = pipe(416caption,417source_embeds=source_embeds,418target_embeds=target_embeds,419num_inference_steps=50,420cross_attention_guidance_amount=0.15,421generator=generator,422latents=inv_latents,423negative_prompt=caption,424output_type="np",425).images426427max_diff = np.abs(expected_image - image).mean()428assert max_diff < 0.05429430def test_stable_diffusion_2_pix2pix_full(self):431# numpy array of https://huggingface.co/datasets/hf-internal-testing/diffusers-images/blob/main/pix2pix/dog_2.png432expected_image = load_numpy(433"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/dog_2.npy"434)435436pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(437"stabilityai/stable-diffusion-2-1", safety_checker=None, torch_dtype=torch.float16438)439pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)440441caption = "a photography of a cat with flowers"442pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)443pipe.enable_model_cpu_offload()444pipe.set_progress_bar_config(disable=None)445446generator = torch.manual_seed(0)447output = pipe.invert(caption, image=self.raw_image, generator=generator)448inv_latents = output[0]449450source_prompts = 4 * ["a cat sitting on the street", "a cat playing in the field", "a face of a cat"]451target_prompts = 4 * ["a dog sitting on the street", "a dog playing in the field", "a face of a dog"]452453source_embeds = pipe.get_embeds(source_prompts)454target_embeds = pipe.get_embeds(target_prompts)455456image = pipe(457caption,458source_embeds=source_embeds,459target_embeds=target_embeds,460num_inference_steps=125,461cross_attention_guidance_amount=0.015,462generator=generator,463latents=inv_latents,464negative_prompt=caption,465output_type="np",466).images467468mean_diff = np.abs(expected_image - image).mean()469assert mean_diff < 0.25470471472