Path: blob/main/tests/pipelines/repaint/test_repaint.py
1450 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 torch2021from diffusers import RePaintPipeline, RePaintScheduler, UNet2DModel22from diffusers.utils.testing_utils import load_image, load_numpy, nightly, require_torch_gpu, skip_mps, torch_device2324from ...pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS25from ...test_pipelines_common import PipelineTesterMixin262728torch.backends.cuda.matmul.allow_tf32 = False293031class RepaintPipelineFastTests(PipelineTesterMixin, unittest.TestCase):32pipeline_class = RePaintPipeline33params = IMAGE_INPAINTING_PARAMS - {"width", "height", "guidance_scale"}34required_optional_params = PipelineTesterMixin.required_optional_params - {35"latents",36"num_images_per_prompt",37"callback",38"callback_steps",39}40batch_params = IMAGE_INPAINTING_BATCH_PARAMS41test_cpu_offload = False4243def get_dummy_components(self):44torch.manual_seed(0)45torch.manual_seed(0)46unet = UNet2DModel(47block_out_channels=(32, 64),48layers_per_block=2,49sample_size=32,50in_channels=3,51out_channels=3,52down_block_types=("DownBlock2D", "AttnDownBlock2D"),53up_block_types=("AttnUpBlock2D", "UpBlock2D"),54)55scheduler = RePaintScheduler()56components = {"unet": unet, "scheduler": scheduler}57return components5859def get_dummy_inputs(self, device, seed=0):60if str(device).startswith("mps"):61generator = torch.manual_seed(seed)62else:63generator = torch.Generator(device=device).manual_seed(seed)64image = np.random.RandomState(seed).standard_normal((1, 3, 32, 32))65image = torch.from_numpy(image).to(device=device, dtype=torch.float32)66mask = (image > 0).to(device=device, dtype=torch.float32)67inputs = {68"image": image,69"mask_image": mask,70"generator": generator,71"num_inference_steps": 5,72"eta": 0.0,73"jump_length": 2,74"jump_n_sample": 2,75"output_type": "numpy",76}77return inputs7879def test_repaint(self):80device = "cpu" # ensure determinism for the device-dependent torch.Generator81components = self.get_dummy_components()82sd_pipe = RePaintPipeline(**components)83sd_pipe = sd_pipe.to(device)84sd_pipe.set_progress_bar_config(disable=None)8586inputs = self.get_dummy_inputs(device)87image = sd_pipe(**inputs).images88image_slice = image[0, -3:, -3:, -1]8990assert image.shape == (1, 32, 32, 3)91expected_slice = np.array([1.0000, 0.5426, 0.5497, 0.2200, 1.0000, 1.0000, 0.5623, 1.0000, 0.6274])9293assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-39495@skip_mps96def test_save_load_local(self):97return super().test_save_load_local()9899# RePaint can hardly be made deterministic since the scheduler is currently always100# nondeterministic101@unittest.skip("non-deterministic pipeline")102def test_inference_batch_single_identical(self):103return super().test_inference_batch_single_identical()104105@skip_mps106def test_dict_tuple_outputs_equivalent(self):107return super().test_dict_tuple_outputs_equivalent()108109@skip_mps110def test_save_load_optional_components(self):111return super().test_save_load_optional_components()112113@skip_mps114def test_attention_slicing_forward_pass(self):115return super().test_attention_slicing_forward_pass()116117118@nightly119@require_torch_gpu120class RepaintPipelineNightlyTests(unittest.TestCase):121def tearDown(self):122super().tearDown()123gc.collect()124torch.cuda.empty_cache()125126def test_celebahq(self):127original_image = load_image(128"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"129"repaint/celeba_hq_256.png"130)131mask_image = load_image(132"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"133)134expected_image = load_numpy(135"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"136"repaint/celeba_hq_256_result.npy"137)138139model_id = "google/ddpm-ema-celebahq-256"140unet = UNet2DModel.from_pretrained(model_id)141scheduler = RePaintScheduler.from_pretrained(model_id)142143repaint = RePaintPipeline(unet=unet, scheduler=scheduler).to(torch_device)144repaint.set_progress_bar_config(disable=None)145repaint.enable_attention_slicing()146147generator = torch.manual_seed(0)148output = repaint(149original_image,150mask_image,151num_inference_steps=250,152eta=0.0,153jump_length=10,154jump_n_sample=10,155generator=generator,156output_type="np",157)158image = output.images[0]159160assert image.shape == (256, 256, 3)161assert np.abs(expected_image - image).mean() < 1e-2162163164