test_modeling_utils.py 37.5 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

patil-suraj's avatar
patil-suraj committed
17
import inspect
18
import math
19
20
21
import tempfile
import unittest

22
import numpy as np
23
24
import torch

Patrick von Platen's avatar
Patrick von Platen committed
25
from diffusers import (
patil-suraj's avatar
patil-suraj committed
26
    AutoencoderKL,
Patrick von Platen's avatar
Patrick von Platen committed
27
    DDIMPipeline,
28
    DDIMScheduler,
Patrick von Platen's avatar
Patrick von Platen committed
29
    DDPMPipeline,
30
    DDPMScheduler,
Patrick von Platen's avatar
Patrick von Platen committed
31
    GlidePipeline,
Patrick von Platen's avatar
Patrick von Platen committed
32
33
    GlideSuperResUNetModel,
    GlideTextToImageUNetModel,
Patrick von Platen's avatar
Patrick von Platen committed
34
    LatentDiffusionPipeline,
patil-suraj's avatar
patil-suraj committed
35
    LatentDiffusionUncondPipeline,
Patrick von Platen's avatar
Patrick von Platen committed
36
    NCSNpp,
Patrick von Platen's avatar
Patrick von Platen committed
37
    PNDMPipeline,
38
    PNDMScheduler,
Patrick von Platen's avatar
Patrick von Platen committed
39
40
    ScoreSdeVePipeline,
    ScoreSdeVeScheduler,
Patrick von Platen's avatar
Patrick von Platen committed
41
42
    ScoreSdeVpPipeline,
    ScoreSdeVpScheduler,
Patrick von Platen's avatar
Patrick von Platen committed
43
    UNetConditionalModel,
anton-l's avatar
anton-l committed
44
    UNetLDMModel,
45
    UNetUnconditionalModel,
patil-suraj's avatar
patil-suraj committed
46
    VQModel,
47
)
48
from diffusers.configuration_utils import ConfigMixin
Patrick von Platen's avatar
Patrick von Platen committed
49
from diffusers.pipeline_utils import DiffusionPipeline
Patrick von Platen's avatar
Patrick von Platen committed
50
from diffusers.pipelines.latent_diffusion.pipeline_latent_diffusion import LDMBertModel
Patrick von Platen's avatar
Patrick von Platen committed
51
from diffusers.testing_utils import floats_tensor, slow, torch_device
52
from diffusers.training_utils import EMAModel
Patrick von Platen's avatar
Patrick von Platen committed
53
from transformers import BertTokenizer
54
55


Patrick von Platen's avatar
Patrick von Platen committed
56
torch.backends.cuda.matmul.allow_tf32 = False
57
58


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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],
            ):
76
                self.register_to_config(a=a, b=b, c=c, d=d, e=e)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

        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
92
93
94
95
        # unfreeze configs
        config = dict(config)
        new_config = dict(new_config)

96
97
98
99
100
        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


patil-suraj's avatar
patil-suraj committed
101
class ModelTesterMixin:
102
    def test_from_pretrained_save_pretrained(self):
patil-suraj's avatar
patil-suraj committed
103
104
105
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()

        model = self.model_class(**init_dict)
Patrick von Platen's avatar
Patrick von Platen committed
106
        model.to(torch_device)
patil-suraj's avatar
patil-suraj committed
107
        model.eval()
108
109
110

        with tempfile.TemporaryDirectory() as tmpdirname:
            model.save_pretrained(tmpdirname)
patil-suraj's avatar
patil-suraj committed
111
            new_model = self.model_class.from_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
112
            new_model.to(torch_device)
113

patil-suraj's avatar
patil-suraj committed
114
115
        with torch.no_grad():
            image = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
116
117
118
            if isinstance(image, dict):
                image = image["sample"]

patil-suraj's avatar
patil-suraj committed
119
            new_image = new_model(**inputs_dict)
120

Patrick von Platen's avatar
Patrick von Platen committed
121
122
123
            if isinstance(new_image, dict):
                new_image = new_image["sample"]

patil-suraj's avatar
patil-suraj committed
124
        max_diff = (image - new_image).abs().sum().item()
Patrick von Platen's avatar
Patrick von Platen committed
125
        self.assertLessEqual(max_diff, 5e-5, "Models give different forward passes")
126

patil-suraj's avatar
patil-suraj committed
127
    def test_determinism(self):
patil-suraj's avatar
patil-suraj committed
128
129
130
131
132
133
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.eval()
        with torch.no_grad():
            first = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
134
135
136
            if isinstance(first, dict):
                first = first["sample"]

patil-suraj's avatar
patil-suraj committed
137
            second = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
138
139
            if isinstance(second, dict):
                second = second["sample"]
patil-suraj's avatar
patil-suraj committed
140
141
142
143
144
145
146

        out_1 = first.cpu().numpy()
        out_2 = second.cpu().numpy()
        out_1 = out_1[~np.isnan(out_1)]
        out_2 = out_2[~np.isnan(out_2)]
        max_diff = np.amax(np.abs(out_1 - out_2))
        self.assertLessEqual(max_diff, 1e-5)
147

patil-suraj's avatar
patil-suraj committed
148
    def test_output(self):
patil-suraj's avatar
patil-suraj committed
149
150
151
152
153
154
155
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.eval()

        with torch.no_grad():
            output = model(**inputs_dict)
156

Patrick von Platen's avatar
Patrick von Platen committed
157
158
159
            if isinstance(output, dict):
                output = output["sample"]

patil-suraj's avatar
patil-suraj committed
160
        self.assertIsNotNone(output)
161
        expected_shape = inputs_dict["sample"].shape
patil-suraj's avatar
patil-suraj committed
162
        self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
163

patil-suraj's avatar
patil-suraj committed
164
    def test_forward_signature(self):
patil-suraj's avatar
patil-suraj committed
165
166
167
168
169
170
171
        init_dict, _ = self.prepare_init_args_and_inputs_for_common()

        model = self.model_class(**init_dict)
        signature = inspect.signature(model.forward)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        arg_names = [*signature.parameters.keys()]

172
        expected_arg_names = ["sample", "timestep"]
patil-suraj's avatar
patil-suraj committed
173
        self.assertListEqual(arg_names[:2], expected_arg_names)
174

patil-suraj's avatar
patil-suraj committed
175
    def test_model_from_config(self):
patil-suraj's avatar
patil-suraj committed
176
177
178
179
180
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()

        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.eval()
181

patil-suraj's avatar
patil-suraj committed
182
183
184
185
186
187
188
        # test if the model can be loaded from the config
        # and has all the expected shape
        with tempfile.TemporaryDirectory() as tmpdirname:
            model.save_config(tmpdirname)
            new_model = self.model_class.from_config(tmpdirname)
            new_model.to(torch_device)
            new_model.eval()
189

patil-suraj's avatar
patil-suraj committed
190
191
192
193
194
        # check if all paramters shape are the same
        for param_name in model.state_dict().keys():
            param_1 = model.state_dict()[param_name]
            param_2 = new_model.state_dict()[param_name]
            self.assertEqual(param_1.shape, param_2.shape)
195

patil-suraj's avatar
patil-suraj committed
196
197
        with torch.no_grad():
            output_1 = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
198
199
200
201

            if isinstance(output_1, dict):
                output_1 = output_1["sample"]

patil-suraj's avatar
patil-suraj committed
202
            output_2 = new_model(**inputs_dict)
203

Patrick von Platen's avatar
Patrick von Platen committed
204
205
206
            if isinstance(output_2, dict):
                output_2 = output_2["sample"]

patil-suraj's avatar
patil-suraj committed
207
        self.assertEqual(output_1.shape, output_2.shape)
patil-suraj's avatar
patil-suraj committed
208
209

    def test_training(self):
patil-suraj's avatar
patil-suraj committed
210
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
211

patil-suraj's avatar
patil-suraj committed
212
213
214
215
        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.train()
        output = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
216
217
218
219

        if isinstance(output, dict):
            output = output["sample"]

220
        noise = torch.randn((inputs_dict["sample"].shape[0],) + self.output_shape).to(torch_device)
patil-suraj's avatar
patil-suraj committed
221
222
        loss = torch.nn.functional.mse_loss(output, noise)
        loss.backward()
223

224
225
226
227
228
229
230
231
232
    def test_ema_training(self):
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()

        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.train()
        ema_model = EMAModel(model, device=torch_device)

        output = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
233
234
235
236

        if isinstance(output, dict):
            output = output["sample"]

237
        noise = torch.randn((inputs_dict["sample"].shape[0],) + self.output_shape).to(torch_device)
238
239
240
241
        loss = torch.nn.functional.mse_loss(output, noise)
        loss.backward()
        ema_model.step(model)

patil-suraj's avatar
patil-suraj committed
242
243

class UnetModelTests(ModelTesterMixin, unittest.TestCase):
244
    model_class = UNetUnconditionalModel
patil-suraj's avatar
patil-suraj committed
245
246
247
248
249
250
251
252
253
254

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        noise = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor([10]).to(torch_device)

255
        return {"sample": noise, "timestep": time_step}
256

patil-suraj's avatar
patil-suraj committed
257
    @property
Patrick von Platen's avatar
Patrick von Platen committed
258
    def input_shape(self):
patil-suraj's avatar
patil-suraj committed
259
        return (3, 32, 32)
260

patil-suraj's avatar
patil-suraj committed
261
    @property
Patrick von Platen's avatar
Patrick von Platen committed
262
    def output_shape(self):
patil-suraj's avatar
patil-suraj committed
263
        return (3, 32, 32)
patil-suraj's avatar
patil-suraj committed
264
265
266
267
268

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "ch": 32,
            "ch_mult": (1, 2),
269
270
271
272
273
274
            "block_channels": (32, 64),
            "down_blocks": ("UNetResDownBlock2D", "UNetResAttnDownBlock2D"),
            "up_blocks": ("UNetResAttnUpBlock2D", "UNetResUpBlock2D"),
            "num_head_channels": None,
            "out_channels": 3,
            "in_channels": 3,
patil-suraj's avatar
patil-suraj committed
275
276
277
            "num_res_blocks": 2,
            "attn_resolutions": (16,),
            "resolution": 32,
278
            "image_size": 32,
patil-suraj's avatar
patil-suraj committed
279
280
281
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict
282

patil-suraj's avatar
patil-suraj committed
283
    def test_from_pretrained_hub(self):
284
285
286
        model, loading_info = UNetUnconditionalModel.from_pretrained(
            "fusing/ddpm_dummy", output_loading_info=True, ddpm=True
        )
patil-suraj's avatar
patil-suraj committed
287
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
288
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
289

patil-suraj's avatar
patil-suraj committed
290
        model.to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
291
        image = model(**self.dummy_input)["sample"]
patil-suraj's avatar
patil-suraj committed
292
293

        assert image is not None, "Make sure output is not None"
294

patil-suraj's avatar
patil-suraj committed
295
    def test_output_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
296
297
298
299
300
301
302
303
304
305
306
        model = UNetUnconditionalModel.from_pretrained("fusing/ddpm_dummy", ddpm=True)
        model.eval()

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        noise = torch.randn(1, model.config.in_channels, model.config.image_size, model.config.image_size)
        time_step = torch.tensor([10])

        with torch.no_grad():
Patrick von Platen's avatar
Patrick von Platen committed
307
            output = model(noise, time_step)["sample"]
Patrick von Platen's avatar
Patrick von Platen committed
308
309
310
311
312
313
314

        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
        expected_output_slice = torch.tensor([0.2891, -0.1899, 0.2595, -0.6214, 0.0968, -0.2622, 0.4688, 0.1311, 0.0053])
        # fmt: on
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))

315

Patrick von Platen's avatar
Patrick von Platen committed
316
317
class GlideSuperResUNetTests(ModelTesterMixin, unittest.TestCase):
    model_class = GlideSuperResUNetModel
patil-suraj's avatar
patil-suraj committed
318
319
320
321
322
323
324
325
326
327
328
329

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 6
        sizes = (32, 32)
        low_res_size = (4, 4)

        noise = torch.randn((batch_size, num_channels // 2) + sizes).to(torch_device)
        low_res = torch.randn((batch_size, 3) + low_res_size).to(torch_device)
        time_step = torch.tensor([10] * noise.shape[0], device=torch_device)

330
        return {"sample": noise, "timestep": time_step, "low_res": low_res}
331

patil-suraj's avatar
patil-suraj committed
332
    @property
Patrick von Platen's avatar
Patrick von Platen committed
333
    def input_shape(self):
patil-suraj's avatar
patil-suraj committed
334
        return (3, 32, 32)
335

patil-suraj's avatar
patil-suraj committed
336
    @property
Patrick von Platen's avatar
Patrick von Platen committed
337
    def output_shape(self):
patil-suraj's avatar
patil-suraj committed
338
        return (6, 32, 32)
339

patil-suraj's avatar
patil-suraj committed
340
341
342
    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "attention_resolutions": (2,),
343
            "channel_mult": (1, 2),
patil-suraj's avatar
patil-suraj committed
344
345
346
347
348
349
350
351
            "in_channels": 6,
            "out_channels": 6,
            "model_channels": 32,
            "num_head_channels": 8,
            "num_heads_upsample": 1,
            "num_res_blocks": 2,
            "resblock_updown": True,
            "resolution": 32,
352
            "use_scale_shift_norm": True,
patil-suraj's avatar
patil-suraj committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

    def test_output(self):
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.eval()

        with torch.no_grad():
            output = model(**inputs_dict)

        output, _ = torch.split(output, 3, dim=1)
367

patil-suraj's avatar
patil-suraj committed
368
        self.assertIsNotNone(output)
369
        expected_shape = inputs_dict["sample"].shape
patil-suraj's avatar
patil-suraj committed
370
        self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
371

patil-suraj's avatar
patil-suraj committed
372
    def test_from_pretrained_hub(self):
Patrick von Platen's avatar
Patrick von Platen committed
373
        model, loading_info = GlideSuperResUNetModel.from_pretrained(
374
375
            "fusing/glide-super-res-dummy", output_loading_info=True
        )
patil-suraj's avatar
patil-suraj committed
376
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
377
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
378
379
380
381
382

        model.to(torch_device)
        image = model(**self.dummy_input)

        assert image is not None, "Make sure output is not None"
383

patil-suraj's avatar
patil-suraj committed
384
    def test_output_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
385
        model = GlideSuperResUNetModel.from_pretrained("fusing/glide-super-res-dummy")
patil-suraj's avatar
patil-suraj committed
386
387
388
389

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)
390

391
        noise = torch.randn(1, 3, 64, 64)
patil-suraj's avatar
patil-suraj committed
392
393
        low_res = torch.randn(1, 3, 4, 4)
        time_step = torch.tensor([42] * noise.shape[0])
394

patil-suraj's avatar
patil-suraj committed
395
396
        with torch.no_grad():
            output = model(noise, time_step, low_res)
397

patil-suraj's avatar
patil-suraj committed
398
399
400
        output, _ = torch.split(output, 3, dim=1)
        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
401
        expected_output_slice = torch.tensor([-22.8782, -23.2652, -15.3966, -22.8034, -23.3159, -15.5640, -15.3970, -15.4614, - 10.4370])
patil-suraj's avatar
patil-suraj committed
402
403
        # fmt: on
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
patil-suraj's avatar
patil-suraj committed
404

anton-l's avatar
anton-l committed
405

Patrick von Platen's avatar
Patrick von Platen committed
406
407
class GlideTextToImageUNetModelTests(ModelTesterMixin, unittest.TestCase):
    model_class = GlideTextToImageUNetModel
408
409
410
411
412
413
414
415
416
417
418
419
420

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)
        transformer_dim = 32
        seq_len = 16

        noise = torch.randn((batch_size, num_channels) + sizes).to(torch_device)
        emb = torch.randn((batch_size, seq_len, transformer_dim)).to(torch_device)
        time_step = torch.tensor([10] * noise.shape[0], device=torch_device)

421
        return {"sample": noise, "timestep": time_step, "transformer_out": emb}
422
423

    @property
Patrick von Platen's avatar
Patrick von Platen committed
424
    def input_shape(self):
425
426
427
        return (3, 32, 32)

    @property
Patrick von Platen's avatar
Patrick von Platen committed
428
    def output_shape(self):
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        return (6, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "attention_resolutions": (2,),
            "channel_mult": (1, 2),
            "in_channels": 3,
            "out_channels": 6,
            "model_channels": 32,
            "num_head_channels": 8,
            "num_heads_upsample": 1,
            "num_res_blocks": 2,
            "resblock_updown": True,
            "resolution": 32,
            "use_scale_shift_norm": True,
            "transformer_dim": 32,
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

    def test_output(self):
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
        model = self.model_class(**init_dict)
        model.to(torch_device)
        model.eval()

        with torch.no_grad():
            output = model(**inputs_dict)

        output, _ = torch.split(output, 3, dim=1)

        self.assertIsNotNone(output)
461
        expected_shape = inputs_dict["sample"].shape
462
463
464
        self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")

    def test_from_pretrained_hub(self):
Patrick von Platen's avatar
Patrick von Platen committed
465
        model, loading_info = GlideTextToImageUNetModel.from_pretrained(
466
467
468
            "fusing/unet-glide-text2im-dummy", output_loading_info=True
        )
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
469
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
470
471
472
473
474
475
476

        model.to(torch_device)
        image = model(**self.dummy_input)

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

    def test_output_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
477
        model = GlideTextToImageUNetModel.from_pretrained("fusing/unet-glide-text2im-dummy")
478
479
480
481
482
483
484
485
486
487
488

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        noise = torch.randn((1, model.config.in_channels, model.config.resolution, model.config.resolution)).to(
            torch_device
        )
        emb = torch.randn((1, 16, model.config.transformer_dim)).to(torch_device)
        time_step = torch.tensor([10] * noise.shape[0], device=torch_device)

Patrick von Platen's avatar
Patrick von Platen committed
489
        model.to(torch_device)
490
491
492
493
        with torch.no_grad():
            output = model(noise, time_step, emb)

        output, _ = torch.split(output, 3, dim=1)
Patrick von Platen's avatar
Patrick von Platen committed
494
        output_slice = output[0, -1, -3:, -3:].cpu().flatten()
495
        # fmt: off
Patrick von Platen's avatar
Patrick von Platen committed
496
        expected_output_slice = torch.tensor([2.7766, -10.3558, -14.9149, -0.9376, -14.9175, -17.7679, -5.5565, -12.9521, -12.9845])
497
498
499
500
        # fmt: on
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))


patil-suraj's avatar
patil-suraj committed
501
class UNetLDMModelTests(ModelTesterMixin, unittest.TestCase):
502
    model_class = UNetUnconditionalModel
patil-suraj's avatar
patil-suraj committed
503
504
505
506
507
508
509
510
511
512

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 4
        sizes = (32, 32)

        noise = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor([10]).to(torch_device)

513
        return {"sample": noise, "timestep": time_step}
patil-suraj's avatar
patil-suraj committed
514
515

    @property
Patrick von Platen's avatar
Patrick von Platen committed
516
    def input_shape(self):
patil-suraj's avatar
patil-suraj committed
517
518
519
        return (4, 32, 32)

    @property
Patrick von Platen's avatar
Patrick von Platen committed
520
    def output_shape(self):
patil-suraj's avatar
patil-suraj committed
521
522
523
524
525
526
527
528
529
        return (4, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "image_size": 32,
            "in_channels": 4,
            "out_channels": 4,
            "num_res_blocks": 2,
            "attention_resolutions": (16,),
Patrick von Platen's avatar
Patrick von Platen committed
530
            "block_channels": (32, 64),
531
            "num_head_channels": 32,
patil-suraj's avatar
patil-suraj committed
532
            "conv_resample": True,
533
534
            "down_blocks": ("UNetResDownBlock2D", "UNetResDownBlock2D"),
            "up_blocks": ("UNetResUpBlock2D", "UNetResUpBlock2D"),
Patrick von Platen's avatar
Patrick von Platen committed
535
            "ldm": True,
patil-suraj's avatar
patil-suraj committed
536
537
538
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict
anton-l's avatar
anton-l committed
539

patil-suraj's avatar
patil-suraj committed
540
    def test_from_pretrained_hub(self):
Patrick von Platen's avatar
Patrick von Platen committed
541
542
543
        model, loading_info = UNetUnconditionalModel.from_pretrained(
            "fusing/unet-ldm-dummy", output_loading_info=True, ldm=True
        )
patil-suraj's avatar
patil-suraj committed
544
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
545
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
546
547

        model.to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
548
        image = model(**self.dummy_input)["sample"]
patil-suraj's avatar
patil-suraj committed
549
550
551
552

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

    def test_output_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
553
        model = UNetUnconditionalModel.from_pretrained("fusing/unet-ldm-dummy", ldm=True)
patil-suraj's avatar
patil-suraj committed
554
555
556
557
558
559
560
561
562
563
        model.eval()

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        noise = torch.randn(1, model.config.in_channels, model.config.image_size, model.config.image_size)
        time_step = torch.tensor([10] * noise.shape[0])

        with torch.no_grad():
Patrick von Platen's avatar
Patrick von Platen committed
564
            output = model(noise, time_step)["sample"]
patil-suraj's avatar
patil-suraj committed
565
566
567
568
569
570
571
572

        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
        expected_output_slice = torch.tensor([-13.3258, -20.1100, -15.9873, -17.6617, -23.0596, -17.9419, -13.3675, -16.1889, -12.3800])
        # fmt: on

        self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))

Patrick von Platen's avatar
Patrick von Platen committed
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
    def test_output_pretrained_spatial_transformer(self):
        model = UNetLDMModel.from_pretrained("fusing/unet-ldm-dummy-spatial")
        model.eval()

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        noise = torch.randn(1, model.config.in_channels, model.config.image_size, model.config.image_size)
        context = torch.ones((1, 16, 64), dtype=torch.float32)
        time_step = torch.tensor([10] * noise.shape[0])

        with torch.no_grad():
            output = model(noise, time_step, context=context)

        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
        expected_output_slice = torch.tensor([61.3445, 56.9005, 29.4339, 59.5497, 60.7375, 34.1719, 48.1951, 42.6569, 25.0890])
        # fmt: on

        self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))

patil-suraj's avatar
patil-suraj committed
595

596
class NCSNppModelTests(ModelTesterMixin, unittest.TestCase):
597
    model_class = UNetUnconditionalModel
598
599
600
601
602
603
604
605
606
607

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        noise = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor(batch_size * [10]).to(torch_device)

608
        return {"sample": noise, "timestep": time_step}
609
610

    @property
Patrick von Platen's avatar
Patrick von Platen committed
611
    def input_shape(self):
612
613
614
        return (3, 32, 32)

    @property
Patrick von Platen's avatar
Patrick von Platen committed
615
    def output_shape(self):
616
617
618
619
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
            "block_channels": [32, 64, 64, 64],
            "in_channels": 3,
            "num_res_blocks": 1,
            "out_channels": 3,
            "time_embedding_type": "fourier",
            "resnet_eps": 1e-6,
            "mid_block_scale_factor": math.sqrt(2.0),
            "resnet_num_groups": None,
            "down_blocks": [
                "UNetResSkipDownBlock2D",
                "UNetResAttnSkipDownBlock2D",
                "UNetResSkipDownBlock2D",
                "UNetResSkipDownBlock2D",
            ],
            "up_blocks": [
                "UNetResSkipUpBlock2D",
                "UNetResSkipUpBlock2D",
                "UNetResAttnSkipUpBlock2D",
                "UNetResSkipUpBlock2D",
            ],
640
641
642
643
644
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

    def test_from_pretrained_hub(self):
645
646
647
        model, loading_info = UNetUnconditionalModel.from_pretrained(
            "fusing/ncsnpp-ffhq-ve-dummy", sde=True, output_loading_info=True
        )
648
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
649
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

        model.to(torch_device)
        image = model(**self.dummy_input)

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

    def test_output_pretrained_ve_small(self):
        model = NCSNpp.from_pretrained("fusing/ncsnpp-cifar10-ve-dummy")
        model.eval()
        model.to(torch_device)

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

Patrick von Platen's avatar
Patrick von Platen committed
669
670
        noise = torch.ones((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor(batch_size * [1e-4]).to(torch_device)
671
672
673
674
675
676

        with torch.no_grad():
            output = model(noise, time_step)

        output_slice = output[0, -3:, -3:, -1].flatten().cpu()
        # fmt: off
Patrick von Platen's avatar
Patrick von Platen committed
677
        expected_output_slice = torch.tensor([0.1315, 0.0741, 0.0393, 0.0455, 0.0556, 0.0180, -0.0832, -0.0644, -0.0856])
678
679
        # fmt: on

Patrick von Platen's avatar
Patrick von Platen committed
680
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
681

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
    def test_output_pretrained_ve_mid(self):
        model = UNetUnconditionalModel.from_pretrained("fusing/celebahq_256-ncsnpp-ve", sde=True)
        model.to(torch_device)

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        batch_size = 4
        num_channels = 3
        sizes = (256, 256)

        noise = torch.ones((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor(batch_size * [1e-4]).to(torch_device)

        with torch.no_grad():
            output = model(noise, time_step)["sample"]

        output_slice = output[0, -3:, -3:, -1].flatten().cpu()
        # fmt: off
        expected_output_slice = torch.tensor([-4836.2231, -6487.1387, -3816.7969, -7964.9253, -10966.2842, -20043.6016, 8137.0571, 2340.3499, 544.6114])
        # fmt: on

        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))

707
    def test_output_pretrained_ve_large(self):
708
        model = UNetUnconditionalModel.from_pretrained("fusing/ncsnpp-ffhq-ve-dummy", sde=True)
709
710
711
712
713
714
715
716
717
718
        model.to(torch_device)

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

Patrick von Platen's avatar
Patrick von Platen committed
719
720
        noise = torch.ones((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor(batch_size * [1e-4]).to(torch_device)
721
722

        with torch.no_grad():
723
            output = model(noise, time_step)["sample"]
724
725
726

        output_slice = output[0, -3:, -3:, -1].flatten().cpu()
        # fmt: off
Patrick von Platen's avatar
Patrick von Platen committed
727
        expected_output_slice = torch.tensor([-0.0325, -0.0900, -0.0869, -0.0332, -0.0725, -0.0270, -0.0101, 0.0227, 0.0256])
728
729
        # fmt: on

Patrick von Platen's avatar
Patrick von Platen committed
730
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
731
732

    def test_output_pretrained_vp(self):
Patrick von Platen's avatar
Patrick von Platen committed
733
        model = NCSNpp.from_pretrained("fusing/cifar10-ddpmpp-vp")
734
735
736
737
738
739
740
741
742
743
        model.to(torch_device)

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

Patrick von Platen's avatar
Patrick von Platen committed
744
        noise = torch.randn((batch_size, num_channels) + sizes).to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
745
        time_step = torch.tensor(batch_size * [9.0]).to(torch_device)
746
747
748
749
750
751

        with torch.no_grad():
            output = model(noise, time_step)

        output_slice = output[0, -3:, -3:, -1].flatten().cpu()
        # fmt: off
Patrick von Platen's avatar
Patrick von Platen committed
752
        expected_output_slice = torch.tensor([0.3303, -0.2275, -2.8872, -0.1309, -1.2861, 3.4567, -1.0083, 2.5325, -1.3866])
753
754
        # fmt: on

Patrick von Platen's avatar
Patrick von Platen committed
755
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
756
757


patil-suraj's avatar
patil-suraj committed
758
759
760
761
762
763
764
765
766
767
768
class VQModelTests(ModelTesterMixin, unittest.TestCase):
    model_class = VQModel

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)

769
        return {"sample": image}
patil-suraj's avatar
patil-suraj committed
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "ch": 64,
            "out_ch": 3,
            "num_res_blocks": 1,
            "attn_resolutions": [],
            "in_channels": 3,
            "resolution": 32,
            "z_channels": 3,
            "n_embed": 256,
            "embed_dim": 3,
            "sane_index_shape": False,
            "ch_mult": (1,),
            "dropout": 0.0,
            "double_z": False,
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

    def test_forward_signature(self):
        pass

    def test_training(self):
        pass

    def test_from_pretrained_hub(self):
        model, loading_info = VQModel.from_pretrained("fusing/vqgan-dummy", output_loading_info=True)
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
807
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827

        model.to(torch_device)
        image = model(**self.dummy_input)

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

    def test_output_pretrained(self):
        model = VQModel.from_pretrained("fusing/vqgan-dummy")
        model.eval()

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        image = torch.randn(1, model.config.in_channels, model.config.resolution, model.config.resolution)
        with torch.no_grad():
            output = model(image)

        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
Patrick von Platen's avatar
up  
Patrick von Platen committed
828
        expected_output_slice = torch.tensor([-1.1321, 0.1056, 0.3505, -0.6461, -0.2014, 0.0419, -0.5763, -0.8462, -0.4218])
patil-suraj's avatar
patil-suraj committed
829
        # fmt: on
Patrick von Platen's avatar
up  
Patrick von Platen committed
830
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
patil-suraj's avatar
patil-suraj committed
831
832


Patrick von Platen's avatar
Patrick von Platen committed
833
class AutoencoderKLTests(ModelTesterMixin, unittest.TestCase):
patil-suraj's avatar
patil-suraj committed
834
835
836
837
838
839
840
841
842
843
    model_class = AutoencoderKL

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)

844
        return {"sample": image}
patil-suraj's avatar
patil-suraj committed
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "ch": 64,
            "ch_mult": (1,),
            "embed_dim": 4,
            "in_channels": 3,
            "num_res_blocks": 1,
            "out_ch": 3,
            "resolution": 32,
            "z_channels": 4,
patil-suraj's avatar
patil-suraj committed
864
            "attn_resolutions": [],
patil-suraj's avatar
patil-suraj committed
865
866
867
868
869
870
871
872
873
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

    def test_forward_signature(self):
        pass

    def test_training(self):
        pass
patil-suraj's avatar
patil-suraj committed
874

patil-suraj's avatar
patil-suraj committed
875
876
877
    def test_from_pretrained_hub(self):
        model, loading_info = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy", output_loading_info=True)
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
878
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898

        model.to(torch_device)
        image = model(**self.dummy_input)

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

    def test_output_pretrained(self):
        model = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy")
        model.eval()

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

        image = torch.randn(1, model.config.in_channels, model.config.resolution, model.config.resolution)
        with torch.no_grad():
            output = model(image, sample_posterior=True)

        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
Patrick von Platen's avatar
up  
Patrick von Platen committed
899
        expected_output_slice = torch.tensor([-0.0814, -0.0229, -0.1320, -0.4123, -0.0366, -0.3473, 0.0438, -0.1662, 0.1750])
patil-suraj's avatar
patil-suraj committed
900
        # fmt: on
Patrick von Platen's avatar
up  
Patrick von Platen committed
901
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
patil-suraj's avatar
patil-suraj committed
902
903


904
905
906
class PipelineTesterMixin(unittest.TestCase):
    def test_from_pretrained_save_pretrained(self):
        # 1. Load models
907
        model = UNetUnconditionalModel(
Patrick von Platen's avatar
Patrick von Platen committed
908
909
910
911
912
913
914
915
            block_channels=(32, 64),
            num_res_blocks=2,
            attn_resolutions=(16,),
            image_size=32,
            in_channels=3,
            out_channels=3,
            down_blocks=("UNetResDownBlock2D", "UNetResAttnDownBlock2D"),
            up_blocks=("UNetResAttnUpBlock2D", "UNetResUpBlock2D"),
916
        )
Patrick von Platen's avatar
Patrick von Platen committed
917
        schedular = DDPMScheduler(num_train_timesteps=10)
918

Patrick von Platen's avatar
Patrick von Platen committed
919
        ddpm = DDPMPipeline(model, schedular)
920
921
922

        with tempfile.TemporaryDirectory() as tmpdirname:
            ddpm.save_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
923
            new_ddpm = DDPMPipeline.from_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
924
925

        generator = torch.manual_seed(0)
926

patil-suraj's avatar
patil-suraj committed
927
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
928
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
929
        new_image = new_ddpm(generator=generator)
930
931
932
933
934

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

    @slow
    def test_from_pretrained_hub(self):
Lysandre Debut's avatar
Lysandre Debut committed
935
        model_path = "google/ddpm-cifar10"
936

Patrick von Platen's avatar
Patrick von Platen committed
937
        ddpm = DDPMPipeline.from_pretrained(model_path)
938
939
        ddpm_from_hub = DiffusionPipeline.from_pretrained(model_path)

940
941
        ddpm.scheduler.num_timesteps = 10
        ddpm_from_hub.scheduler.num_timesteps = 10
942

Patrick von Platen's avatar
Patrick von Platen committed
943
        generator = torch.manual_seed(0)
944

patil-suraj's avatar
patil-suraj committed
945
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
946
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
947
        new_image = ddpm_from_hub(generator=generator)
948
949

        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
950
951
952

    @slow
    def test_ddpm_cifar10(self):
Lysandre Debut's avatar
Lysandre Debut committed
953
        model_id = "google/ddpm-cifar10"
Patrick von Platen's avatar
Patrick von Platen committed
954

Lysandre Debut's avatar
Lysandre Debut committed
955
        unet = UNetUnconditionalModel.from_pretrained(model_id)
956
957
        scheduler = DDPMScheduler.from_config(model_id)
        scheduler = scheduler.set_format("pt")
Patrick von Platen's avatar
Patrick von Platen committed
958

959
        ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
Patrick von Platen's avatar
Patrick von Platen committed
960
961

        generator = torch.manual_seed(0)
Patrick von Platen's avatar
Patrick von Platen committed
962
963
964
965
966
        image = ddpm(generator=generator)

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

        assert image.shape == (1, 3, 32, 32)
Patrick von Platen's avatar
Patrick von Platen committed
967
        expected_slice = torch.tensor(
968
969
970
971
972
973
            [-0.1601, -0.2823, -0.6123, -0.2305, -0.3236, -0.4706, -0.1691, -0.2836, -0.3231]
        )
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

    @slow
    def test_ddim_lsun(self):
Lysandre Debut's avatar
Lysandre Debut committed
974
        model_id = "google/ddpm-lsun-bedroom-ema"
975

Lysandre Debut's avatar
Lysandre Debut committed
976
        unet = UNetUnconditionalModel.from_pretrained(model_id)
977
        scheduler = DDIMScheduler.from_config(model_id)
978

979
        ddpm = DDIMPipeline(unet=unet, scheduler=scheduler)
980
981

        generator = torch.manual_seed(0)
982
        image = ddpm(generator=generator)["sample"]
983
984
985
986
987
988

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

        assert image.shape == (1, 3, 256, 256)
        expected_slice = torch.tensor(
            [-0.9879, -0.9598, -0.9312, -0.9953, -0.9963, -0.9995, -0.9957, -1.0000, -0.9863]
Patrick von Platen's avatar
Patrick von Platen committed
989
        )
Patrick von Platen's avatar
Patrick von Platen committed
990
991
992
993
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

    @slow
    def test_ddim_cifar10(self):
Lysandre Debut's avatar
Lysandre Debut committed
994
        model_id = "google/ddpm-cifar10"
Patrick von Platen's avatar
Patrick von Platen committed
995

Lysandre Debut's avatar
Lysandre Debut committed
996
        unet = UNetUnconditionalModel.from_pretrained(model_id)
997
        scheduler = DDIMScheduler(tensor_format="pt")
Patrick von Platen's avatar
Patrick von Platen committed
998

999
        ddim = DDIMPipeline(unet=unet, scheduler=scheduler)
1000
1001

        generator = torch.manual_seed(0)
1002
        image = ddim(generator=generator, eta=0.0)["sample"]
Patrick von Platen's avatar
Patrick von Platen committed
1003
1004
1005
1006

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

        assert image.shape == (1, 3, 32, 32)
Patrick von Platen's avatar
Patrick von Platen committed
1007
        expected_slice = torch.tensor(
1008
            [-0.6553, -0.6765, -0.6799, -0.6749, -0.7006, -0.6974, -0.6991, -0.7116, -0.7094]
Patrick von Platen's avatar
Patrick von Platen committed
1009
        )
Patrick von Platen's avatar
Patrick von Platen committed
1010
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2
patil-suraj's avatar
patil-suraj committed
1011

Patrick von Platen's avatar
Patrick von Platen committed
1012
1013
    @slow
    def test_pndm_cifar10(self):
Lysandre Debut's avatar
Lysandre Debut committed
1014
        model_id = "google/ddpm-cifar10"
Patrick von Platen's avatar
Patrick von Platen committed
1015

1016
        unet = UNetUnconditionalModel.from_pretrained(model_id, ddpm=True)
1017
        scheduler = PNDMScheduler(tensor_format="pt")
Patrick von Platen's avatar
Patrick von Platen committed
1018

1019
        pndm = PNDMPipeline(unet=unet, scheduler=scheduler)
Patrick von Platen's avatar
Patrick von Platen committed
1020
        generator = torch.manual_seed(0)
Patrick von Platen's avatar
Patrick von Platen committed
1021
1022
1023
1024
1025
1026
        image = pndm(generator=generator)

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

        assert image.shape == (1, 3, 32, 32)
        expected_slice = torch.tensor(
Patrick von Platen's avatar
Patrick von Platen committed
1027
            [-0.6872, -0.7071, -0.7188, -0.7057, -0.7515, -0.7191, -0.7377, -0.7565, -0.7500]
Patrick von Platen's avatar
Patrick von Platen committed
1028
1029
1030
        )
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

patil-suraj's avatar
patil-suraj committed
1031
1032
    @slow
    def test_ldm_text2img(self):
Patrick von Platen's avatar
Patrick von Platen committed
1033
        ldm = LatentDiffusionPipeline.from_pretrained("/home/patrick/latent-diffusion-text2im-large")
patil-suraj's avatar
patil-suraj committed
1034
1035
1036
1037
1038
1039
1040
1041
1042

        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()

        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
1043
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2
1044

patil-suraj's avatar
patil-suraj committed
1045
1046
    @slow
    def test_ldm_text2img_fast(self):
Patrick von Platen's avatar
Patrick von Platen committed
1047
        ldm = LatentDiffusionPipeline.from_pretrained("/home/patrick/latent-diffusion-text2im-large")
patil-suraj's avatar
patil-suraj committed
1048
1049
1050

        prompt = "A painting of a squirrel eating a burger"
        generator = torch.manual_seed(0)
1051
        image = ldm([prompt], generator=generator, num_inference_steps=1)
patil-suraj's avatar
patil-suraj committed
1052
1053
1054
1055

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

        assert image.shape == (1, 3, 256, 256)
patil-suraj's avatar
patil-suraj committed
1056
        expected_slice = torch.tensor([0.3163, 0.8670, 0.6465, 0.1865, 0.6291, 0.5139, 0.2824, 0.3723, 0.4344])
patil-suraj's avatar
patil-suraj committed
1057
1058
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

anton-l's avatar
anton-l committed
1059
1060
1061
    @slow
    def test_glide_text2img(self):
        model_id = "fusing/glide-base"
Patrick von Platen's avatar
Patrick von Platen committed
1062
        glide = GlidePipeline.from_pretrained(model_id)
anton-l's avatar
anton-l committed
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073

        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

Patrick von Platen's avatar
Patrick von Platen committed
1074
1075
    @slow
    def test_score_sde_ve_pipeline(self):
1076
        model = UNetUnconditionalModel.from_pretrained("fusing/ffhq_ncsnpp", sde=True)
Patrick von Platen's avatar
Patrick von Platen committed
1077
        model = UNetUnconditionalModel.from_pretrained("google/ffhq_ncsnpp")
1078
1079
1080
1081
1082

        torch.manual_seed(0)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(0)

Patrick von Platen's avatar
Patrick von Platen committed
1083
1084
1085
1086
        scheduler = ScoreSdeVeScheduler.from_config("fusing/ffhq_ncsnpp")

        sde_ve = ScoreSdeVePipeline(model=model, scheduler=scheduler)

1087
        torch.manual_seed(0)
Patrick von Platen's avatar
Patrick von Platen committed
1088
1089
        image = sde_ve(num_inference_steps=2)

Patrick von Platen's avatar
Patrick von Platen committed
1090
        if model.device.type == "cpu":
Nathan Lambert's avatar
Nathan Lambert committed
1091
1092
1093
1094
1095
1096
1097
            # patrick's cpu
            expected_image_sum = 3384805888.0
            expected_image_mean = 1076.00085

            # m1 mbp
            # expected_image_sum = 3384805376.0
            # expected_image_mean = 1076.000610351562
Patrick von Platen's avatar
Patrick von Platen committed
1098
1099
        else:
            expected_image_sum = 3382849024.0
Nathan Lambert's avatar
Nathan Lambert committed
1100
            expected_image_mean = 1075.3788
Patrick von Platen's avatar
Patrick von Platen committed
1101
1102
1103
1104

        assert (image.abs().sum() - expected_image_sum).abs().cpu().item() < 1e-2
        assert (image.abs().mean() - expected_image_mean).abs().cpu().item() < 1e-4

Patrick von Platen's avatar
Patrick von Platen committed
1105
1106
    @slow
    def test_score_sde_vp_pipeline(self):
Patrick von Platen's avatar
Patrick von Platen committed
1107
1108
        model = NCSNpp.from_pretrained("fusing/cifar10-ddpmpp-vp")
        scheduler = ScoreSdeVpScheduler.from_config("fusing/cifar10-ddpmpp-vp")
Patrick von Platen's avatar
Patrick von Platen committed
1109
1110
1111
1112
1113
1114
1115
1116
1117

        sde_vp = ScoreSdeVpPipeline(model=model, scheduler=scheduler)

        torch.manual_seed(0)
        image = sde_vp(num_inference_steps=10)

        expected_image_sum = 4183.2012
        expected_image_mean = 1.3617

Nathan Lambert's avatar
Nathan Lambert committed
1118
1119
1120
1121
        # on m1 mbp
        # expected_image_sum = 4318.6729
        # expected_image_mean = 1.4058

Patrick von Platen's avatar
Patrick von Platen committed
1122
1123
1124
        assert (image.abs().sum() - expected_image_sum).abs().cpu().item() < 1e-2
        assert (image.abs().mean() - expected_image_mean).abs().cpu().item() < 1e-4

patil-suraj's avatar
patil-suraj committed
1125
1126
    @slow
    def test_ldm_uncond(self):
Patrick von Platen's avatar
Patrick von Platen committed
1127
        ldm = LatentDiffusionUncondPipeline.from_pretrained("CompVis/latent-diffusion-celeba-256")
patil-suraj's avatar
patil-suraj committed
1128
1129

        generator = torch.manual_seed(0)
1130
        image = ldm(generator=generator, num_inference_steps=5)["sample"]
patil-suraj's avatar
patil-suraj committed
1131
1132
1133
1134

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

        assert image.shape == (1, 3, 256, 256)
patil-suraj's avatar
patil-suraj committed
1135
1136
1137
        expected_slice = torch.tensor(
            [-0.1202, -0.1005, -0.0635, -0.0520, -0.1282, -0.0838, -0.0981, -0.1318, -0.1106]
        )
patil-suraj's avatar
patil-suraj committed
1138
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2