test_modeling_utils.py 8.66 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# coding=utf-8
# Copyright 2022 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Patrick von Platen's avatar
Patrick von Platen committed
16

17
18
19
20
21
import tempfile
import unittest

import torch

22
23
24
25
26
27
28
29
30
31
32
33
from diffusers import (
    BDDM,
    DDIM,
    DDPM,
    GLIDE,
    PNDM,
    DDIMScheduler,
    DDPMScheduler,
    LatentDiffusion,
    PNDMScheduler,
    UNetModel,
)
34
from diffusers.configuration_utils import ConfigMixin
Patrick von Platen's avatar
Patrick von Platen committed
35
from diffusers.pipeline_utils import DiffusionPipeline
36
from diffusers.pipelines.pipeline_bddm import DiffWave
Patrick von Platen's avatar
Patrick von Platen committed
37
from diffusers.testing_utils import floats_tensor, slow, torch_device
38
39


Patrick von Platen's avatar
Patrick von Platen committed
40
torch.backends.cuda.matmul.allow_tf32 = False
41
42


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class ConfigTester(unittest.TestCase):
    def test_load_not_from_mixin(self):
        with self.assertRaises(ValueError):
            ConfigMixin.from_config("dummy_path")

    def test_save_load(self):
        class SampleObject(ConfigMixin):
            config_name = "config.json"

            def __init__(
                self,
                a=2,
                b=5,
                c=(2, 5),
                d="for diffusion",
                e=[1, 3],
            ):
60
                self.register_to_config(a=a, b=b, c=c, d=d, e=e)
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

        obj = SampleObject()
        config = obj.config

        assert config["a"] == 2
        assert config["b"] == 5
        assert config["c"] == (2, 5)
        assert config["d"] == "for diffusion"
        assert config["e"] == [1, 3]

        with tempfile.TemporaryDirectory() as tmpdirname:
            obj.save_config(tmpdirname)
            new_obj = SampleObject.from_config(tmpdirname)
            new_config = new_obj.config

Patrick von Platen's avatar
Patrick von Platen committed
76
77
78
79
        # unfreeze configs
        config = dict(config)
        new_config = dict(new_config)

80
81
82
83
84
        assert config.pop("c") == (2, 5)  # instantiated as tuple
        assert new_config.pop("c") == [2, 5]  # saved & loaded as list because of json
        assert config == new_config


85
class ModelTesterMixin(unittest.TestCase):
Patrick von Platen's avatar
Patrick von Platen committed
86
87
    @property
    def dummy_input(self):
Patrick von Platen's avatar
up  
Patrick von Platen committed
88
        batch_size = 4
Patrick von Platen's avatar
Patrick von Platen committed
89
90
91
        num_channels = 3
        sizes = (32, 32)

Patrick von Platen's avatar
Patrick von Platen committed
92
        noise = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
93
        time_step = torch.tensor([10]).to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
94
95
96

        return (noise, time_step)

97
    def test_from_pretrained_save_pretrained(self):
Patrick von Platen's avatar
improve  
Patrick von Platen committed
98
        model = UNetModel(ch=32, ch_mult=(1, 2), num_res_blocks=2, attn_resolutions=(16,), resolution=32)
Patrick von Platen's avatar
Patrick von Platen committed
99
        model.to(torch_device)
100
101
102
103

        with tempfile.TemporaryDirectory() as tmpdirname:
            model.save_pretrained(tmpdirname)
            new_model = UNetModel.from_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
104
            new_model.to(torch_device)
105

Patrick von Platen's avatar
Patrick von Platen committed
106
        dummy_input = self.dummy_input
107

Patrick von Platen's avatar
Patrick von Platen committed
108
109
        image = model(*dummy_input)
        new_image = new_model(*dummy_input)
110
111

        assert (image - new_image).abs().sum() < 1e-5, "Models don't give the same forward pass"
Patrick von Platen's avatar
Patrick von Platen committed
112
113
114

    def test_from_pretrained_hub(self):
        model = UNetModel.from_pretrained("fusing/ddpm_dummy")
Patrick von Platen's avatar
Patrick von Platen committed
115
        model.to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
116
117
118
119

        image = model(*self.dummy_input)

        assert image is not None, "Make sure output is not None"
120
121


122
123
124
125
class PipelineTesterMixin(unittest.TestCase):
    def test_from_pretrained_save_pretrained(self):
        # 1. Load models
        model = UNetModel(ch=32, ch_mult=(1, 2), num_res_blocks=2, attn_resolutions=(16,), resolution=32)
Patrick von Platen's avatar
Patrick von Platen committed
126
        schedular = DDPMScheduler(timesteps=10)
127
128
129
130
131
132

        ddpm = DDPM(model, schedular)

        with tempfile.TemporaryDirectory() as tmpdirname:
            ddpm.save_pretrained(tmpdirname)
            new_ddpm = DDPM.from_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
133
134

        generator = torch.manual_seed(0)
135

patil-suraj's avatar
patil-suraj committed
136
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
137
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
138
        new_image = new_ddpm(generator=generator)
139
140
141
142
143
144
145
146
147
148
149
150
151

        assert (image - new_image).abs().sum() < 1e-5, "Models don't give the same forward pass"

    @slow
    def test_from_pretrained_hub(self):
        model_path = "fusing/ddpm-cifar10"

        ddpm = DDPM.from_pretrained(model_path)
        ddpm_from_hub = DiffusionPipeline.from_pretrained(model_path)

        ddpm.noise_scheduler.num_timesteps = 10
        ddpm_from_hub.noise_scheduler.num_timesteps = 10

Patrick von Platen's avatar
Patrick von Platen committed
152
        generator = torch.manual_seed(0)
153

patil-suraj's avatar
patil-suraj committed
154
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
155
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
156
        new_image = ddpm_from_hub(generator=generator)
157
158

        assert (image - new_image).abs().sum() < 1e-5, "Models don't give the same forward pass"
Patrick von Platen's avatar
Patrick von Platen committed
159
160
161
162
163
164

    @slow
    def test_ddpm_cifar10(self):
        generator = torch.manual_seed(0)
        model_id = "fusing/ddpm-cifar10"

Patrick von Platen's avatar
Patrick von Platen committed
165
        unet = UNetModel.from_pretrained(model_id)
Patrick von Platen's avatar
Patrick von Platen committed
166
        noise_scheduler = DDPMScheduler.from_config(model_id)
Patrick von Platen's avatar
Patrick von Platen committed
167
        noise_scheduler = noise_scheduler.set_format("pt")
Patrick von Platen's avatar
Patrick von Platen committed
168
169

        ddpm = DDPM(unet=unet, noise_scheduler=noise_scheduler)
Patrick von Platen's avatar
Patrick von Platen committed
170
171
172
173
174
175
176
177
178
179
180
181
182
        image = ddpm(generator=generator)

        image_slice = image[0, -1, -3:, -3:].cpu()

        assert image.shape == (1, 3, 32, 32)
        expected_slice = torch.tensor([0.2250, 0.3375, 0.2360, 0.0930, 0.3440, 0.3156, 0.1937, 0.3585, 0.1761])
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

    @slow
    def test_ddim_cifar10(self):
        generator = torch.manual_seed(0)
        model_id = "fusing/ddpm-cifar10"

Patrick von Platen's avatar
Patrick von Platen committed
183
        unet = UNetModel.from_pretrained(model_id)
Patrick von Platen's avatar
Patrick von Platen committed
184
        noise_scheduler = DDIMScheduler(tensor_format="pt")
Patrick von Platen's avatar
Patrick von Platen committed
185
186

        ddim = DDIM(unet=unet, noise_scheduler=noise_scheduler)
Patrick von Platen's avatar
Patrick von Platen committed
187
188
189
190
191
        image = ddim(generator=generator, eta=0.0)

        image_slice = image[0, -1, -3:, -3:].cpu()

        assert image.shape == (1, 3, 32, 32)
Patrick von Platen's avatar
Patrick von Platen committed
192
193
194
        expected_slice = torch.tensor(
            [-0.7383, -0.7385, -0.7298, -0.7364, -0.7414, -0.7239, -0.6737, -0.6813, -0.7068]
        )
Patrick von Platen's avatar
Patrick von Platen committed
195
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2
patil-suraj's avatar
patil-suraj committed
196

Patrick von Platen's avatar
Patrick von Platen committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    @slow
    def test_pndm_cifar10(self):
        generator = torch.manual_seed(0)
        model_id = "fusing/ddpm-cifar10"

        unet = UNetModel.from_pretrained(model_id)
        noise_scheduler = PNDMScheduler(tensor_format="pt")

        pndm = PNDM(unet=unet, noise_scheduler=noise_scheduler)
        image = pndm(generator=generator)

        image_slice = image[0, -1, -3:, -3:].cpu()

        assert image.shape == (1, 3, 32, 32)
        expected_slice = torch.tensor(
            [-0.7888, -0.7870, -0.7759, -0.7823, -0.8014, -0.7608, -0.6818, -0.7130, -0.7471]
        )
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

patil-suraj's avatar
patil-suraj committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
    @slow
    def test_ldm_text2img(self):
        model_id = "fusing/latent-diffusion-text2im-large"
        ldm = LatentDiffusion.from_pretrained(model_id)

        prompt = "A painting of a squirrel eating a burger"
        generator = torch.manual_seed(0)
        image = ldm([prompt], generator=generator, num_inference_steps=20)

        image_slice = image[0, -1, -3:, -3:].cpu()
        print(image_slice.shape)

        assert image.shape == (1, 3, 256, 256)
        expected_slice = torch.tensor([0.7295, 0.7358, 0.7256, 0.7435, 0.7095, 0.6884, 0.7325, 0.6921, 0.6458])
Patrick von Platen's avatar
update  
Patrick von Platen committed
230
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2
231

anton-l's avatar
anton-l committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    @slow
    def test_glide_text2img(self):
        model_id = "fusing/glide-base"
        glide = GLIDE.from_pretrained(model_id)

        prompt = "a pencil sketch of a corgi"
        generator = torch.manual_seed(0)
        image = glide(prompt, generator=generator, num_inference_steps_upscale=20)

        image_slice = image[0, :3, :3, -1].cpu()

        assert image.shape == (1, 256, 256, 3)
        expected_slice = torch.tensor([0.7119, 0.7073, 0.6460, 0.7780, 0.7423, 0.6926, 0.7378, 0.7189, 0.7784])
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

247
248
249
250
251
252
253
254
255
256
257
258
259
260
    def test_module_from_pipeline(self):
        model = DiffWave(num_res_layers=4)
        noise_scheduler = DDPMScheduler(timesteps=12)

        bddm = BDDM(model, noise_scheduler)

        # check if the library name for the diffwave moduel is set to pipeline module
        self.assertTrue(bddm.config["diffwave"][0] == "pipeline_bddm")

        # check if we can save and load the pipeline
        with tempfile.TemporaryDirectory() as tmpdirname:
            bddm.save_pretrained(tmpdirname)
            _ = BDDM.from_pretrained(tmpdirname)
            # check if the same works using the DifusionPipeline class
261
            _ = DiffusionPipeline.from_pretrained(tmpdirname)