Path: blob/main/tests/pipelines/latent_diffusion/test_latent_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 AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNet2DConditionModel23from diffusers.utils.testing_utils import load_numpy, nightly, require_torch_gpu, slow, torch_device2425from ...pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS26from ...test_pipelines_common import PipelineTesterMixin272829torch.backends.cuda.matmul.allow_tf32 = False303132class LDMTextToImagePipelineFastTests(PipelineTesterMixin, unittest.TestCase):33pipeline_class = LDMTextToImagePipeline34params = TEXT_TO_IMAGE_PARAMS - {35"negative_prompt",36"negative_prompt_embeds",37"cross_attention_kwargs",38"prompt_embeds",39}40required_optional_params = PipelineTesterMixin.required_optional_params - {41"num_images_per_prompt",42"callback",43"callback_steps",44}45batch_params = TEXT_TO_IMAGE_BATCH_PARAMS46test_cpu_offload = False4748def get_dummy_components(self):49torch.manual_seed(0)50unet = UNet2DConditionModel(51block_out_channels=(32, 64),52layers_per_block=2,53sample_size=32,54in_channels=4,55out_channels=4,56down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),57up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),58cross_attention_dim=32,59)60scheduler = DDIMScheduler(61beta_start=0.00085,62beta_end=0.012,63beta_schedule="scaled_linear",64clip_sample=False,65set_alpha_to_one=False,66)67torch.manual_seed(0)68vae = AutoencoderKL(69block_out_channels=(32, 64),70in_channels=3,71out_channels=3,72down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D"),73up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D"),74latent_channels=4,75)76torch.manual_seed(0)77text_encoder_config = CLIPTextConfig(78bos_token_id=0,79eos_token_id=2,80hidden_size=32,81intermediate_size=37,82layer_norm_eps=1e-05,83num_attention_heads=4,84num_hidden_layers=5,85pad_token_id=1,86vocab_size=1000,87)88text_encoder = CLIPTextModel(text_encoder_config)89tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")9091components = {92"unet": unet,93"scheduler": scheduler,94"vqvae": vae,95"bert": text_encoder,96"tokenizer": tokenizer,97}98return components99100def get_dummy_inputs(self, device, seed=0):101if str(device).startswith("mps"):102generator = torch.manual_seed(seed)103else:104generator = torch.Generator(device=device).manual_seed(seed)105inputs = {106"prompt": "A painting of a squirrel eating a burger",107"generator": generator,108"num_inference_steps": 2,109"guidance_scale": 6.0,110"output_type": "numpy",111}112return inputs113114def test_inference_text2img(self):115device = "cpu" # ensure determinism for the device-dependent torch.Generator116117components = self.get_dummy_components()118pipe = LDMTextToImagePipeline(**components)119pipe.to(device)120pipe.set_progress_bar_config(disable=None)121122inputs = self.get_dummy_inputs(device)123image = pipe(**inputs).images124image_slice = image[0, -3:, -3:, -1]125126assert image.shape == (1, 16, 16, 3)127expected_slice = np.array([0.59450, 0.64078, 0.55509, 0.51229, 0.69640, 0.36960, 0.59296, 0.60801, 0.49332])128129assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3130131132@slow133@require_torch_gpu134class LDMTextToImagePipelineSlowTests(unittest.TestCase):135def tearDown(self):136super().tearDown()137gc.collect()138torch.cuda.empty_cache()139140def get_inputs(self, device, dtype=torch.float32, seed=0):141generator = torch.manual_seed(seed)142latents = np.random.RandomState(seed).standard_normal((1, 4, 32, 32))143latents = torch.from_numpy(latents).to(device=device, dtype=dtype)144inputs = {145"prompt": "A painting of a squirrel eating a burger",146"latents": latents,147"generator": generator,148"num_inference_steps": 3,149"guidance_scale": 6.0,150"output_type": "numpy",151}152return inputs153154def test_ldm_default_ddim(self):155pipe = LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256").to(torch_device)156pipe.set_progress_bar_config(disable=None)157158inputs = self.get_inputs(torch_device)159image = pipe(**inputs).images160image_slice = image[0, -3:, -3:, -1].flatten()161162assert image.shape == (1, 256, 256, 3)163expected_slice = np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878])164max_diff = np.abs(expected_slice - image_slice).max()165assert max_diff < 1e-3166167168@nightly169@require_torch_gpu170class LDMTextToImagePipelineNightlyTests(unittest.TestCase):171def tearDown(self):172super().tearDown()173gc.collect()174torch.cuda.empty_cache()175176def get_inputs(self, device, dtype=torch.float32, seed=0):177generator = torch.manual_seed(seed)178latents = np.random.RandomState(seed).standard_normal((1, 4, 32, 32))179latents = torch.from_numpy(latents).to(device=device, dtype=dtype)180inputs = {181"prompt": "A painting of a squirrel eating a burger",182"latents": latents,183"generator": generator,184"num_inference_steps": 50,185"guidance_scale": 6.0,186"output_type": "numpy",187}188return inputs189190def test_ldm_default_ddim(self):191pipe = LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256").to(torch_device)192pipe.set_progress_bar_config(disable=None)193194inputs = self.get_inputs(torch_device)195image = pipe(**inputs).images[0]196197expected_image = load_numpy(198"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"199)200max_diff = np.abs(expected_image - image).max()201assert max_diff < 1e-3202203204