Path: blob/main/tests/pipelines/pndm/test_pndm.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 PNDMPipeline, PNDMScheduler, UNet2DModel21from diffusers.utils.testing_utils import require_torch, slow, torch_device222324torch.backends.cuda.matmul.allow_tf32 = False252627class PNDMPipelineFastTests(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 = PNDMScheduler()4546pndm = PNDMPipeline(unet=unet, scheduler=scheduler)47pndm.to(torch_device)48pndm.set_progress_bar_config(disable=None)4950generator = torch.manual_seed(0)51image = pndm(generator=generator, num_inference_steps=20, output_type="numpy").images5253generator = torch.manual_seed(0)54image_from_tuple = pndm(generator=generator, num_inference_steps=20, 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([1.0, 1.0, 0.0, 1.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 PNDMPipelineIntegrationTests(unittest.TestCase):69def test_inference_cifar10(self):70model_id = "google/ddpm-cifar10-32"7172unet = UNet2DModel.from_pretrained(model_id)73scheduler = PNDMScheduler()7475pndm = PNDMPipeline(unet=unet, scheduler=scheduler)76pndm.to(torch_device)77pndm.set_progress_bar_config(disable=None)78generator = torch.manual_seed(0)79image = pndm(generator=generator, output_type="numpy").images8081image_slice = image[0, -3:, -3:, -1]8283assert image.shape == (1, 32, 32, 3)84expected_slice = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125])8586assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2878889