Path: blob/main/tests/pipelines/stable_diffusion_2/test_stable_diffusion.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,24DDIMScheduler,25DPMSolverMultistepScheduler,26EulerAncestralDiscreteScheduler,27EulerDiscreteScheduler,28LMSDiscreteScheduler,29PNDMScheduler,30StableDiffusionPipeline,31UNet2DConditionModel,32logging,33)34from diffusers.models.attention_processor import AttnProcessor35from diffusers.utils import load_numpy, nightly, slow, torch_device36from diffusers.utils.testing_utils import CaptureLogger, require_torch_gpu3738from ...pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS39from ...test_pipelines_common import PipelineTesterMixin404142torch.backends.cuda.matmul.allow_tf32 = False434445class StableDiffusion2PipelineFastTests(PipelineTesterMixin, unittest.TestCase):46pipeline_class = StableDiffusionPipeline47params = TEXT_TO_IMAGE_PARAMS48batch_params = TEXT_TO_IMAGE_BATCH_PARAMS4950def get_dummy_components(self):51torch.manual_seed(0)52unet = UNet2DConditionModel(53block_out_channels=(32, 64),54layers_per_block=2,55sample_size=32,56in_channels=4,57out_channels=4,58down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),59up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),60cross_attention_dim=32,61# SD2-specific config below62attention_head_dim=(2, 4),63use_linear_projection=True,64)65scheduler = DDIMScheduler(66beta_start=0.00085,67beta_end=0.012,68beta_schedule="scaled_linear",69clip_sample=False,70set_alpha_to_one=False,71)72torch.manual_seed(0)73vae = AutoencoderKL(74block_out_channels=[32, 64],75in_channels=3,76out_channels=3,77down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],78up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],79latent_channels=4,80sample_size=128,81)82torch.manual_seed(0)83text_encoder_config = CLIPTextConfig(84bos_token_id=0,85eos_token_id=2,86hidden_size=32,87intermediate_size=37,88layer_norm_eps=1e-05,89num_attention_heads=4,90num_hidden_layers=5,91pad_token_id=1,92vocab_size=1000,93# SD2-specific config below94hidden_act="gelu",95projection_dim=512,96)97text_encoder = CLIPTextModel(text_encoder_config)98tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")99100components = {101"unet": unet,102"scheduler": scheduler,103"vae": vae,104"text_encoder": text_encoder,105"tokenizer": tokenizer,106"safety_checker": None,107"feature_extractor": None,108}109return components110111def get_dummy_inputs(self, device, seed=0):112if str(device).startswith("mps"):113generator = torch.manual_seed(seed)114else:115generator = torch.Generator(device=device).manual_seed(seed)116inputs = {117"prompt": "A painting of a squirrel eating a burger",118"generator": generator,119"num_inference_steps": 2,120"guidance_scale": 6.0,121"output_type": "numpy",122}123return inputs124125def test_stable_diffusion_ddim(self):126device = "cpu" # ensure determinism for the device-dependent torch.Generator127components = self.get_dummy_components()128sd_pipe = StableDiffusionPipeline(**components)129sd_pipe = sd_pipe.to(device)130sd_pipe.set_progress_bar_config(disable=None)131132inputs = self.get_dummy_inputs(device)133image = sd_pipe(**inputs).images134image_slice = image[0, -3:, -3:, -1]135136assert image.shape == (1, 64, 64, 3)137expected_slice = np.array([0.5649, 0.6022, 0.4804, 0.5270, 0.5585, 0.4643, 0.5159, 0.4963, 0.4793])138139assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2140141def test_stable_diffusion_pndm(self):142device = "cpu" # ensure determinism for the device-dependent torch.Generator143components = self.get_dummy_components()144components["scheduler"] = PNDMScheduler(skip_prk_steps=True)145sd_pipe = StableDiffusionPipeline(**components)146sd_pipe = sd_pipe.to(device)147sd_pipe.set_progress_bar_config(disable=None)148149inputs = self.get_dummy_inputs(device)150image = sd_pipe(**inputs).images151image_slice = image[0, -3:, -3:, -1]152153assert image.shape == (1, 64, 64, 3)154expected_slice = np.array([0.5099, 0.5677, 0.4671, 0.5128, 0.5697, 0.4676, 0.5277, 0.4964, 0.4946])155156assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2157158def test_stable_diffusion_k_lms(self):159device = "cpu" # ensure determinism for the device-dependent torch.Generator160components = self.get_dummy_components()161components["scheduler"] = LMSDiscreteScheduler.from_config(components["scheduler"].config)162sd_pipe = StableDiffusionPipeline(**components)163sd_pipe = sd_pipe.to(device)164sd_pipe.set_progress_bar_config(disable=None)165166inputs = self.get_dummy_inputs(device)167image = sd_pipe(**inputs).images168image_slice = image[0, -3:, -3:, -1]169170assert image.shape == (1, 64, 64, 3)171expected_slice = np.array([0.4717, 0.5376, 0.4568, 0.5225, 0.5734, 0.4797, 0.5467, 0.5074, 0.5043])172173assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2174175def test_stable_diffusion_k_euler_ancestral(self):176device = "cpu" # ensure determinism for the device-dependent torch.Generator177components = self.get_dummy_components()178components["scheduler"] = EulerAncestralDiscreteScheduler.from_config(components["scheduler"].config)179sd_pipe = StableDiffusionPipeline(**components)180sd_pipe = sd_pipe.to(device)181sd_pipe.set_progress_bar_config(disable=None)182183inputs = self.get_dummy_inputs(device)184image = sd_pipe(**inputs).images185image_slice = image[0, -3:, -3:, -1]186187assert image.shape == (1, 64, 64, 3)188expected_slice = np.array([0.4715, 0.5376, 0.4569, 0.5224, 0.5734, 0.4797, 0.5465, 0.5074, 0.5046])189190assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2191192def test_stable_diffusion_k_euler(self):193device = "cpu" # ensure determinism for the device-dependent torch.Generator194components = self.get_dummy_components()195components["scheduler"] = EulerDiscreteScheduler.from_config(components["scheduler"].config)196sd_pipe = StableDiffusionPipeline(**components)197sd_pipe = sd_pipe.to(device)198sd_pipe.set_progress_bar_config(disable=None)199200inputs = self.get_dummy_inputs(device)201image = sd_pipe(**inputs).images202image_slice = image[0, -3:, -3:, -1]203204assert image.shape == (1, 64, 64, 3)205expected_slice = np.array([0.4717, 0.5376, 0.4568, 0.5225, 0.5734, 0.4797, 0.5467, 0.5074, 0.5043])206207assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2208209def test_stable_diffusion_long_prompt(self):210components = self.get_dummy_components()211components["scheduler"] = LMSDiscreteScheduler.from_config(components["scheduler"].config)212sd_pipe = StableDiffusionPipeline(**components)213sd_pipe = sd_pipe.to(torch_device)214sd_pipe.set_progress_bar_config(disable=None)215216do_classifier_free_guidance = True217negative_prompt = None218num_images_per_prompt = 1219logger = logging.get_logger("diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion")220221prompt = 25 * "@"222with CaptureLogger(logger) as cap_logger_3:223text_embeddings_3 = sd_pipe._encode_prompt(224prompt, torch_device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt225)226227prompt = 100 * "@"228with CaptureLogger(logger) as cap_logger:229text_embeddings = sd_pipe._encode_prompt(230prompt, torch_device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt231)232233negative_prompt = "Hello"234with CaptureLogger(logger) as cap_logger_2:235text_embeddings_2 = sd_pipe._encode_prompt(236prompt, torch_device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt237)238239assert text_embeddings_3.shape == text_embeddings_2.shape == text_embeddings.shape240assert text_embeddings.shape[1] == 77241242assert cap_logger.out == cap_logger_2.out243# 100 - 77 + 1 (BOS token) + 1 (EOS token) = 25244assert cap_logger.out.count("@") == 25245assert cap_logger_3.out == ""246247248@slow249@require_torch_gpu250class StableDiffusion2PipelineSlowTests(unittest.TestCase):251def tearDown(self):252super().tearDown()253gc.collect()254torch.cuda.empty_cache()255256def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):257generator = torch.Generator(device=generator_device).manual_seed(seed)258latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))259latents = torch.from_numpy(latents).to(device=device, dtype=dtype)260inputs = {261"prompt": "a photograph of an astronaut riding a horse",262"latents": latents,263"generator": generator,264"num_inference_steps": 3,265"guidance_scale": 7.5,266"output_type": "numpy",267}268return inputs269270def test_stable_diffusion_default_ddim(self):271pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")272pipe.to(torch_device)273pipe.set_progress_bar_config(disable=None)274275inputs = self.get_inputs(torch_device)276image = pipe(**inputs).images277image_slice = image[0, -3:, -3:, -1].flatten()278279assert image.shape == (1, 512, 512, 3)280expected_slice = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])281assert np.abs(image_slice - expected_slice).max() < 1e-4282283def test_stable_diffusion_pndm(self):284pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")285pipe.scheduler = PNDMScheduler.from_config(pipe.scheduler.config)286pipe.to(torch_device)287pipe.set_progress_bar_config(disable=None)288289inputs = self.get_inputs(torch_device)290image = pipe(**inputs).images291image_slice = image[0, -3:, -3:, -1].flatten()292293assert image.shape == (1, 512, 512, 3)294expected_slice = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])295assert np.abs(image_slice - expected_slice).max() < 1e-4296297def test_stable_diffusion_k_lms(self):298pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")299pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)300pipe.to(torch_device)301pipe.set_progress_bar_config(disable=None)302303inputs = self.get_inputs(torch_device)304image = pipe(**inputs).images305image_slice = image[0, -3:, -3:, -1].flatten()306307assert image.shape == (1, 512, 512, 3)308expected_slice = np.array([0.10440, 0.13115, 0.11100, 0.10141, 0.11440, 0.07215, 0.11332, 0.09693, 0.10006])309assert np.abs(image_slice - expected_slice).max() < 1e-4310311def test_stable_diffusion_attention_slicing(self):312torch.cuda.reset_peak_memory_stats()313pipe = StableDiffusionPipeline.from_pretrained(314"stabilityai/stable-diffusion-2-base", torch_dtype=torch.float16315)316pipe = pipe.to(torch_device)317pipe.set_progress_bar_config(disable=None)318319# enable attention slicing320pipe.enable_attention_slicing()321inputs = self.get_inputs(torch_device, dtype=torch.float16)322image_sliced = pipe(**inputs).images323324mem_bytes = torch.cuda.max_memory_allocated()325torch.cuda.reset_peak_memory_stats()326# make sure that less than 3.3 GB is allocated327assert mem_bytes < 3.3 * 10**9328329# disable slicing330pipe.disable_attention_slicing()331inputs = self.get_inputs(torch_device, dtype=torch.float16)332image = pipe(**inputs).images333334# make sure that more than 3.3 GB is allocated335mem_bytes = torch.cuda.max_memory_allocated()336assert mem_bytes > 3.3 * 10**9337assert np.abs(image_sliced - image).max() < 1e-3338339def test_stable_diffusion_text2img_intermediate_state(self):340number_of_steps = 0341342def callback_fn(step: int, timestep: int, latents: torch.FloatTensor) -> None:343callback_fn.has_been_called = True344nonlocal number_of_steps345number_of_steps += 1346if step == 1:347latents = latents.detach().cpu().numpy()348assert latents.shape == (1, 4, 64, 64)349latents_slice = latents[0, -3:, -3:, -1]350expected_slice = np.array(351[-0.3862, -0.4507, -1.1729, 0.0686, -1.1045, 0.7124, -1.8301, 0.1903, 1.2773]352)353354assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2355elif step == 2:356latents = latents.detach().cpu().numpy()357assert latents.shape == (1, 4, 64, 64)358latents_slice = latents[0, -3:, -3:, -1]359expected_slice = np.array(360[0.2720, -0.1863, -0.7383, -0.5029, -0.7534, 0.3970, -0.7646, 0.4468, 1.2686]361)362363assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2364365callback_fn.has_been_called = False366367pipe = StableDiffusionPipeline.from_pretrained(368"stabilityai/stable-diffusion-2-base", torch_dtype=torch.float16369)370pipe = pipe.to(torch_device)371pipe.set_progress_bar_config(disable=None)372pipe.enable_attention_slicing()373374inputs = self.get_inputs(torch_device, dtype=torch.float16)375pipe(**inputs, callback=callback_fn, callback_steps=1)376assert callback_fn.has_been_called377assert number_of_steps == inputs["num_inference_steps"]378379def test_stable_diffusion_pipeline_with_sequential_cpu_offloading(self):380torch.cuda.empty_cache()381torch.cuda.reset_max_memory_allocated()382torch.cuda.reset_peak_memory_stats()383384pipe = StableDiffusionPipeline.from_pretrained(385"stabilityai/stable-diffusion-2-base", torch_dtype=torch.float16386)387pipe = pipe.to(torch_device)388pipe.set_progress_bar_config(disable=None)389pipe.enable_attention_slicing(1)390pipe.enable_sequential_cpu_offload()391392inputs = self.get_inputs(torch_device, dtype=torch.float16)393_ = pipe(**inputs)394395mem_bytes = torch.cuda.max_memory_allocated()396# make sure that less than 2.8 GB is allocated397assert mem_bytes < 2.8 * 10**9398399def test_stable_diffusion_pipeline_with_model_offloading(self):400torch.cuda.empty_cache()401torch.cuda.reset_max_memory_allocated()402torch.cuda.reset_peak_memory_stats()403404inputs = self.get_inputs(torch_device, dtype=torch.float16)405406# Normal inference407408pipe = StableDiffusionPipeline.from_pretrained(409"stabilityai/stable-diffusion-2-base",410torch_dtype=torch.float16,411)412pipe.unet.set_attn_processor(AttnProcessor())413pipe.to(torch_device)414pipe.set_progress_bar_config(disable=None)415outputs = pipe(**inputs)416mem_bytes = torch.cuda.max_memory_allocated()417418# With model offloading419420# Reload but don't move to cuda421pipe = StableDiffusionPipeline.from_pretrained(422"stabilityai/stable-diffusion-2-base",423torch_dtype=torch.float16,424)425pipe.unet.set_attn_processor(AttnProcessor())426427torch.cuda.empty_cache()428torch.cuda.reset_max_memory_allocated()429torch.cuda.reset_peak_memory_stats()430431pipe.enable_model_cpu_offload()432pipe.set_progress_bar_config(disable=None)433inputs = self.get_inputs(torch_device, dtype=torch.float16)434outputs_offloaded = pipe(**inputs)435mem_bytes_offloaded = torch.cuda.max_memory_allocated()436437assert np.abs(outputs.images - outputs_offloaded.images).max() < 1e-3438assert mem_bytes_offloaded < mem_bytes439assert mem_bytes_offloaded < 3 * 10**9440for module in pipe.text_encoder, pipe.unet, pipe.vae:441assert module.device == torch.device("cpu")442443# With attention slicing444torch.cuda.empty_cache()445torch.cuda.reset_max_memory_allocated()446torch.cuda.reset_peak_memory_stats()447448pipe.enable_attention_slicing()449_ = pipe(**inputs)450mem_bytes_slicing = torch.cuda.max_memory_allocated()451assert mem_bytes_slicing < mem_bytes_offloaded452453454@nightly455@require_torch_gpu456class StableDiffusion2PipelineNightlyTests(unittest.TestCase):457def tearDown(self):458super().tearDown()459gc.collect()460torch.cuda.empty_cache()461462def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):463generator = torch.Generator(device=generator_device).manual_seed(seed)464latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))465latents = torch.from_numpy(latents).to(device=device, dtype=dtype)466inputs = {467"prompt": "a photograph of an astronaut riding a horse",468"latents": latents,469"generator": generator,470"num_inference_steps": 50,471"guidance_scale": 7.5,472"output_type": "numpy",473}474return inputs475476def test_stable_diffusion_2_0_default_ddim(self):477sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base").to(torch_device)478sd_pipe.set_progress_bar_config(disable=None)479480inputs = self.get_inputs(torch_device)481image = sd_pipe(**inputs).images[0]482483expected_image = load_numpy(484"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"485"/stable_diffusion_2_text2img/stable_diffusion_2_0_base_ddim.npy"486)487max_diff = np.abs(expected_image - image).max()488assert max_diff < 1e-3489490def test_stable_diffusion_2_1_default_pndm(self):491sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)492sd_pipe.set_progress_bar_config(disable=None)493494inputs = self.get_inputs(torch_device)495image = sd_pipe(**inputs).images[0]496497expected_image = load_numpy(498"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"499"/stable_diffusion_2_text2img/stable_diffusion_2_1_base_pndm.npy"500)501max_diff = np.abs(expected_image - image).max()502assert max_diff < 1e-3503504def test_stable_diffusion_ddim(self):505sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)506sd_pipe.scheduler = DDIMScheduler.from_config(sd_pipe.scheduler.config)507sd_pipe.set_progress_bar_config(disable=None)508509inputs = self.get_inputs(torch_device)510image = sd_pipe(**inputs).images[0]511512expected_image = load_numpy(513"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"514"/stable_diffusion_2_text2img/stable_diffusion_2_1_base_ddim.npy"515)516max_diff = np.abs(expected_image - image).max()517assert max_diff < 1e-3518519def test_stable_diffusion_lms(self):520sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)521sd_pipe.scheduler = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config)522sd_pipe.set_progress_bar_config(disable=None)523524inputs = self.get_inputs(torch_device)525image = sd_pipe(**inputs).images[0]526527expected_image = load_numpy(528"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"529"/stable_diffusion_2_text2img/stable_diffusion_2_1_base_lms.npy"530)531max_diff = np.abs(expected_image - image).max()532assert max_diff < 1e-3533534def test_stable_diffusion_euler(self):535sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)536sd_pipe.scheduler = EulerDiscreteScheduler.from_config(sd_pipe.scheduler.config)537sd_pipe.set_progress_bar_config(disable=None)538539inputs = self.get_inputs(torch_device)540image = sd_pipe(**inputs).images[0]541542expected_image = load_numpy(543"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"544"/stable_diffusion_2_text2img/stable_diffusion_2_1_base_euler.npy"545)546max_diff = np.abs(expected_image - image).max()547assert max_diff < 1e-3548549def test_stable_diffusion_dpm(self):550sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)551sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config)552sd_pipe.set_progress_bar_config(disable=None)553554inputs = self.get_inputs(torch_device)555inputs["num_inference_steps"] = 25556image = sd_pipe(**inputs).images[0]557558expected_image = load_numpy(559"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"560"/stable_diffusion_2_text2img/stable_diffusion_2_1_base_dpm_multi.npy"561)562max_diff = np.abs(expected_image - image).max()563assert max_diff < 1e-3564565566