Path: blob/main/tests/pipelines/karras_ve/test_karras_ve.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 unittest1617import numpy as np18import torch1920from diffusers import KarrasVePipeline, KarrasVeScheduler, UNet2DModel21from diffusers.utils.testing_utils import require_torch, slow, torch_device222324torch.backends.cuda.matmul.allow_tf32 = False252627class KarrasVePipelineFastTests(unittest.TestCase):28@property29def dummy_uncond_unet(self):30torch.manual_seed(0)31model = UNet2DModel(32block_out_channels=(32, 64),33layers_per_block=2,34sample_size=32,35in_channels=3,36out_channels=3,37down_block_types=("DownBlock2D", "AttnDownBlock2D"),38up_block_types=("AttnUpBlock2D", "UpBlock2D"),39)40return model4142def test_inference(self):43unet = self.dummy_uncond_unet44scheduler = KarrasVeScheduler()4546pipe = KarrasVePipeline(unet=unet, scheduler=scheduler)47pipe.to(torch_device)48pipe.set_progress_bar_config(disable=None)4950generator = torch.manual_seed(0)51image = pipe(num_inference_steps=2, generator=generator, output_type="numpy").images5253generator = torch.manual_seed(0)54image_from_tuple = pipe(num_inference_steps=2, generator=generator, output_type="numpy", return_dict=False)[0]5556image_slice = image[0, -3:, -3:, -1]57image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]5859assert image.shape == (1, 32, 32, 3)60expected_slice = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])6162assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-263assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2646566@slow67@require_torch68class KarrasVePipelineIntegrationTests(unittest.TestCase):69def test_inference(self):70model_id = "google/ncsnpp-celebahq-256"71model = UNet2DModel.from_pretrained(model_id)72scheduler = KarrasVeScheduler()7374pipe = KarrasVePipeline(unet=model, scheduler=scheduler)75pipe.to(torch_device)76pipe.set_progress_bar_config(disable=None)7778generator = torch.manual_seed(0)79image = pipe(num_inference_steps=20, generator=generator, output_type="numpy").images8081image_slice = image[0, -3:, -3:, -1]82assert image.shape == (1, 256, 256, 3)83expected_slice = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586])8485assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2868788