test_modeling_utils.py 35.7 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
19
20
import tempfile
import unittest

21
import numpy as np
22
23
import torch

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


Patrick von Platen's avatar
Patrick von Platen committed
52
torch.backends.cuda.matmul.allow_tf32 = False
53
54


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

        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
88
89
90
91
        # unfreeze configs
        config = dict(config)
        new_config = dict(new_config)

92
93
94
95
96
        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
97
class ModelTesterMixin:
98
    def test_from_pretrained_save_pretrained(self):
patil-suraj's avatar
patil-suraj committed
99
100
101
        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
102
        model.to(torch_device)
patil-suraj's avatar
patil-suraj committed
103
        model.eval()
104
105
106

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

patil-suraj's avatar
patil-suraj committed
110
111
        with torch.no_grad():
            image = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
112
113
114
            if isinstance(image, dict):
                image = image["sample"]

patil-suraj's avatar
patil-suraj committed
115
            new_image = new_model(**inputs_dict)
116

Patrick von Platen's avatar
Patrick von Platen committed
117
118
119
            if isinstance(new_image, dict):
                new_image = new_image["sample"]

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

patil-suraj's avatar
patil-suraj committed
123
    def test_determinism(self):
patil-suraj's avatar
patil-suraj committed
124
125
126
127
128
129
        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
130
131
132
            if isinstance(first, dict):
                first = first["sample"]

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

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

patil-suraj's avatar
patil-suraj committed
144
    def test_output(self):
patil-suraj's avatar
patil-suraj committed
145
146
147
148
149
150
151
        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)
152

Patrick von Platen's avatar
Patrick von Platen committed
153
154
155
            if isinstance(output, dict):
                output = output["sample"]

patil-suraj's avatar
patil-suraj committed
156
        self.assertIsNotNone(output)
157
        expected_shape = inputs_dict["sample"].shape
patil-suraj's avatar
patil-suraj committed
158
        self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
159

patil-suraj's avatar
patil-suraj committed
160
    def test_forward_signature(self):
patil-suraj's avatar
patil-suraj committed
161
162
163
164
165
166
167
        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()]

168
        expected_arg_names = ["sample", "timestep"]
patil-suraj's avatar
patil-suraj committed
169
        self.assertListEqual(arg_names[:2], expected_arg_names)
170

patil-suraj's avatar
patil-suraj committed
171
    def test_model_from_config(self):
patil-suraj's avatar
patil-suraj committed
172
173
174
175
176
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()

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

patil-suraj's avatar
patil-suraj committed
178
179
180
181
182
183
184
        # 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()
185

patil-suraj's avatar
patil-suraj committed
186
187
188
189
190
        # 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)
191

patil-suraj's avatar
patil-suraj committed
192
193
        with torch.no_grad():
            output_1 = model(**inputs_dict)
Patrick von Platen's avatar
Patrick von Platen committed
194
195
196
197

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

patil-suraj's avatar
patil-suraj committed
198
            output_2 = new_model(**inputs_dict)
199

Patrick von Platen's avatar
Patrick von Platen committed
200
201
202
            if isinstance(output_2, dict):
                output_2 = output_2["sample"]

patil-suraj's avatar
patil-suraj committed
203
        self.assertEqual(output_1.shape, output_2.shape)
patil-suraj's avatar
patil-suraj committed
204
205

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

patil-suraj's avatar
patil-suraj committed
208
209
210
211
        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
212
213
214
215

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

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

220
221
222
223
224
225
226
227
228
    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
229
230
231
232

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

233
        noise = torch.randn((inputs_dict["sample"].shape[0],) + self.output_shape).to(torch_device)
234
235
236
237
        loss = torch.nn.functional.mse_loss(output, noise)
        loss.backward()
        ema_model.step(model)

patil-suraj's avatar
patil-suraj committed
238
239

class UnetModelTests(ModelTesterMixin, unittest.TestCase):
240
    model_class = UNetUnconditionalModel
patil-suraj's avatar
patil-suraj committed
241
242
243
244
245
246
247
248
249
250

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

251
        return {"sample": noise, "timestep": time_step}
252

patil-suraj's avatar
patil-suraj committed
253
    @property
Patrick von Platen's avatar
Patrick von Platen committed
254
    def input_shape(self):
patil-suraj's avatar
patil-suraj committed
255
        return (3, 32, 32)
256

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

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "ch": 32,
            "ch_mult": (1, 2),
265
266
267
268
269
270
            "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
271
272
273
            "num_res_blocks": 2,
            "attn_resolutions": (16,),
            "resolution": 32,
274
            "image_size": 32,
patil-suraj's avatar
patil-suraj committed
275
276
277
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict
278

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

patil-suraj's avatar
patil-suraj committed
286
        model.to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
287
        image = model(**self.dummy_input)["sample"]
patil-suraj's avatar
patil-suraj committed
288
289

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

patil-suraj's avatar
patil-suraj committed
291
    def test_output_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
292
293
294
295
296
297
298
299
300
301
302
        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
303
            output = model(noise, time_step)["sample"]
Patrick von Platen's avatar
Patrick von Platen committed
304
305
306
307
308
309
310

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

311

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

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

326
        return {"sample": noise, "timestep": time_step, "low_res": low_res}
327

patil-suraj's avatar
patil-suraj committed
328
    @property
Patrick von Platen's avatar
Patrick von Platen committed
329
    def input_shape(self):
patil-suraj's avatar
patil-suraj committed
330
        return (3, 32, 32)
331

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

patil-suraj's avatar
patil-suraj committed
336
337
338
    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "attention_resolutions": (2,),
339
            "channel_mult": (1, 2),
patil-suraj's avatar
patil-suraj committed
340
341
342
343
344
345
346
347
            "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,
348
            "use_scale_shift_norm": True,
patil-suraj's avatar
patil-suraj committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
        }
        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)
363

patil-suraj's avatar
patil-suraj committed
364
        self.assertIsNotNone(output)
365
        expected_shape = inputs_dict["sample"].shape
patil-suraj's avatar
patil-suraj committed
366
        self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
367

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

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

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

patil-suraj's avatar
patil-suraj committed
380
    def test_output_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
381
        model = GlideSuperResUNetModel.from_pretrained("fusing/glide-super-res-dummy")
patil-suraj's avatar
patil-suraj committed
382
383
384
385

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

387
        noise = torch.randn(1, 3, 64, 64)
patil-suraj's avatar
patil-suraj committed
388
389
        low_res = torch.randn(1, 3, 4, 4)
        time_step = torch.tensor([42] * noise.shape[0])
390

patil-suraj's avatar
patil-suraj committed
391
392
        with torch.no_grad():
            output = model(noise, time_step, low_res)
393

patil-suraj's avatar
patil-suraj committed
394
395
396
        output, _ = torch.split(output, 3, dim=1)
        output_slice = output[0, -1, -3:, -3:].flatten()
        # fmt: off
397
        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
398
399
        # fmt: on
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
patil-suraj's avatar
patil-suraj committed
400

anton-l's avatar
anton-l committed
401

Patrick von Platen's avatar
Patrick von Platen committed
402
403
class GlideTextToImageUNetModelTests(ModelTesterMixin, unittest.TestCase):
    model_class = GlideTextToImageUNetModel
404
405
406
407
408
409
410
411
412
413
414
415
416

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

417
        return {"sample": noise, "timestep": time_step, "transformer_out": emb}
418
419

    @property
Patrick von Platen's avatar
Patrick von Platen committed
420
    def input_shape(self):
421
422
423
        return (3, 32, 32)

    @property
Patrick von Platen's avatar
Patrick von Platen committed
424
    def output_shape(self):
425
426
427
428
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
        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)
457
        expected_shape = inputs_dict["sample"].shape
458
459
460
        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
461
        model, loading_info = GlideTextToImageUNetModel.from_pretrained(
462
463
464
            "fusing/unet-glide-text2im-dummy", output_loading_info=True
        )
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
465
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
466
467
468
469
470
471
472

        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
473
        model = GlideTextToImageUNetModel.from_pretrained("fusing/unet-glide-text2im-dummy")
474
475
476
477
478
479
480
481
482
483
484

        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
485
        model.to(torch_device)
486
487
488
489
        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
490
        output_slice = output[0, -1, -3:, -3:].cpu().flatten()
491
        # fmt: off
Patrick von Platen's avatar
Patrick von Platen committed
492
        expected_output_slice = torch.tensor([2.7766, -10.3558, -14.9149, -0.9376, -14.9175, -17.7679, -5.5565, -12.9521, -12.9845])
493
494
495
496
        # fmt: on
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))


patil-suraj's avatar
patil-suraj committed
497
class UNetLDMModelTests(ModelTesterMixin, unittest.TestCase):
498
    model_class = UNetUnconditionalModel
patil-suraj's avatar
patil-suraj committed
499
500
501
502
503
504
505
506
507
508

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

509
        return {"sample": noise, "timestep": time_step}
patil-suraj's avatar
patil-suraj committed
510
511

    @property
Patrick von Platen's avatar
Patrick von Platen committed
512
    def input_shape(self):
patil-suraj's avatar
patil-suraj committed
513
514
515
        return (4, 32, 32)

    @property
Patrick von Platen's avatar
Patrick von Platen committed
516
    def output_shape(self):
patil-suraj's avatar
patil-suraj committed
517
518
519
520
521
522
523
524
525
        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
526
            "block_channels": (32, 64),
527
            "num_head_channels": 32,
patil-suraj's avatar
patil-suraj committed
528
            "conv_resample": True,
529
530
            "down_blocks": ("UNetResDownBlock2D", "UNetResDownBlock2D"),
            "up_blocks": ("UNetResUpBlock2D", "UNetResUpBlock2D"),
Patrick von Platen's avatar
Patrick von Platen committed
531
            "ldm": True,
patil-suraj's avatar
patil-suraj committed
532
533
534
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict
anton-l's avatar
anton-l committed
535

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

        model.to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
544
        image = model(**self.dummy_input)["sample"]
patil-suraj's avatar
patil-suraj committed
545
546
547
548

        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
549
        model = UNetUnconditionalModel.from_pretrained("fusing/unet-ldm-dummy", ldm=True)
patil-suraj's avatar
patil-suraj committed
550
551
552
553
554
555
556
557
558
559
        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
560
            output = model(noise, time_step)["sample"]
patil-suraj's avatar
patil-suraj committed
561
562
563
564
565
566
567
568

        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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
    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
591

592
593
594
595
596
597
598
599
600
601
602
603
class NCSNppModelTests(ModelTesterMixin, unittest.TestCase):
    model_class = NCSNpp

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

604
        return {"sample": noise, "timestep": time_step}
605
606

    @property
Patrick von Platen's avatar
Patrick von Platen committed
607
    def input_shape(self):
608
609
610
        return (3, 32, 32)

    @property
Patrick von Platen's avatar
Patrick von Platen committed
611
    def output_shape(self):
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "image_size": 32,
            "ch_mult": [1, 2, 2, 2],
            "nf": 32,
            "fir": True,
            "progressive": "output_skip",
            "progressive_combine": "sum",
            "progressive_input": "input_skip",
            "scale_by_sigma": True,
            "skip_rescale": True,
            "embedding_type": "fourier",
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

    def test_from_pretrained_hub(self):
        model, loading_info = NCSNpp.from_pretrained("fusing/cifar10-ncsnpp-ve", output_loading_info=True)
        self.assertIsNotNone(model)
Patrick von Platen's avatar
Patrick von Platen committed
633
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652

        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
653
654
        noise = torch.ones((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor(batch_size * [1e-4]).to(torch_device)
655
656
657
658
659
660

        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
661
        expected_output_slice = torch.tensor([0.1315, 0.0741, 0.0393, 0.0455, 0.0556, 0.0180, -0.0832, -0.0644, -0.0856])
662
663
        # fmt: on

Patrick von Platen's avatar
Patrick von Platen committed
664
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
665
666
667
668
669
670
671
672
673
674
675
676
677
678

    def test_output_pretrained_ve_large(self):
        model = NCSNpp.from_pretrained("fusing/ncsnpp-ffhq-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
679
680
        noise = torch.ones((batch_size, num_channels) + sizes).to(torch_device)
        time_step = torch.tensor(batch_size * [1e-4]).to(torch_device)
681
682
683
684
685
686

        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
687
        expected_output_slice = torch.tensor([-0.0325, -0.0900, -0.0869, -0.0332, -0.0725, -0.0270, -0.0101, 0.0227, 0.0256])
688
689
        # fmt: on

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

    def test_output_pretrained_vp(self):
Patrick von Platen's avatar
Patrick von Platen committed
693
        model = NCSNpp.from_pretrained("fusing/cifar10-ddpmpp-vp")
694
695
696
697
698
699
700
701
702
703
704
        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
705
        noise = torch.randn((batch_size, num_channels) + sizes).to(torch_device)
Patrick von Platen's avatar
Patrick von Platen committed
706
        time_step = torch.tensor(batch_size * [9.0]).to(torch_device)
707
708
709
710
711
712

        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
713
        expected_output_slice = torch.tensor([0.3303, -0.2275, -2.8872, -0.1309, -1.2861, 3.4567, -1.0083, 2.5325, -1.3866])
714
715
        # fmt: on

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


patil-suraj's avatar
patil-suraj committed
719
720
721
722
723
724
725
726
727
728
729
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)

730
        return {"sample": image}
patil-suraj's avatar
patil-suraj committed
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767

    @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
768
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

        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
789
        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
790
        # fmt: on
Patrick von Platen's avatar
up  
Patrick von Platen committed
791
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
patil-suraj's avatar
patil-suraj committed
792
793


patil-suraj's avatar
patil-suraj committed
794
795
796
797
798
799
800
801
802
803
804
class AutoEncoderKLTests(ModelTesterMixin, unittest.TestCase):
    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)

805
        return {"sample": image}
patil-suraj's avatar
patil-suraj committed
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824

    @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
825
            "attn_resolutions": [],
patil-suraj's avatar
patil-suraj committed
826
827
828
829
830
831
832
833
834
        }
        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
835

patil-suraj's avatar
patil-suraj committed
836
837
838
    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
839
        # self.assertEqual(len(loading_info["missing_keys"]), 0)
patil-suraj's avatar
patil-suraj committed
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859

        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
860
        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
861
        # fmt: on
Patrick von Platen's avatar
up  
Patrick von Platen committed
862
        self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-2))
patil-suraj's avatar
patil-suraj committed
863
864


865
866
867
class PipelineTesterMixin(unittest.TestCase):
    def test_from_pretrained_save_pretrained(self):
        # 1. Load models
868
        model = UNetUnconditionalModel(
Patrick von Platen's avatar
Patrick von Platen committed
869
870
871
872
873
874
875
876
877
            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"),
            ddpm=True,
878
        )
Patrick von Platen's avatar
Patrick von Platen committed
879
        schedular = DDPMScheduler(timesteps=10)
880

Patrick von Platen's avatar
Patrick von Platen committed
881
        ddpm = DDPMPipeline(model, schedular)
882
883
884

        with tempfile.TemporaryDirectory() as tmpdirname:
            ddpm.save_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
885
            new_ddpm = DDPMPipeline.from_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
886
887

        generator = torch.manual_seed(0)
888

patil-suraj's avatar
patil-suraj committed
889
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
890
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
891
        new_image = new_ddpm(generator=generator)
892
893
894
895
896
897
898

        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"

Patrick von Platen's avatar
Patrick von Platen committed
899
        ddpm = DDPMPipeline.from_pretrained(model_path)
900
901
        ddpm_from_hub = DiffusionPipeline.from_pretrained(model_path)

902
903
        ddpm.scheduler.num_timesteps = 10
        ddpm_from_hub.scheduler.num_timesteps = 10
904

Patrick von Platen's avatar
Patrick von Platen committed
905
        generator = torch.manual_seed(0)
906

patil-suraj's avatar
patil-suraj committed
907
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
908
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
909
        new_image = ddpm_from_hub(generator=generator)
910
911

        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
912
913
914
915
916

    @slow
    def test_ddpm_cifar10(self):
        model_id = "fusing/ddpm-cifar10"

917
        unet = UNetUnconditionalModel.from_pretrained(model_id, ddpm=True)
918
919
        scheduler = DDPMScheduler.from_config(model_id)
        scheduler = scheduler.set_format("pt")
Patrick von Platen's avatar
Patrick von Platen committed
920

921
        ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
Patrick von Platen's avatar
Patrick von Platen committed
922
923

        generator = torch.manual_seed(0)
Patrick von Platen's avatar
Patrick von Platen committed
924
925
926
927
928
        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
929
        expected_slice = torch.tensor(
930
931
932
933
934
935
936
937
938
            [-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):
        model_id = "fusing/ddpm-lsun-bedroom-ema"

        unet = UNetUnconditionalModel.from_pretrained(model_id, ddpm=True)
939
        scheduler = DDIMScheduler.from_config(model_id)
940

941
        ddpm = DDIMPipeline(unet=unet, scheduler=scheduler)
942
943

        generator = torch.manual_seed(0)
944
        image = ddpm(generator=generator)["sample"]
945
946
947
948
949
950

        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
951
        )
Patrick von Platen's avatar
Patrick von Platen committed
952
953
954
955
956
957
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

    @slow
    def test_ddim_cifar10(self):
        model_id = "fusing/ddpm-cifar10"

958
        unet = UNetUnconditionalModel.from_pretrained(model_id, ddpm=True)
959
        scheduler = DDIMScheduler(tensor_format="pt")
Patrick von Platen's avatar
Patrick von Platen committed
960

961
        ddim = DDIMPipeline(unet=unet, scheduler=scheduler)
962
963

        generator = torch.manual_seed(0)
964
        image = ddim(generator=generator, eta=0.0)["sample"]
Patrick von Platen's avatar
Patrick von Platen committed
965
966
967
968

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

        assert image.shape == (1, 3, 32, 32)
Patrick von Platen's avatar
Patrick von Platen committed
969
        expected_slice = torch.tensor(
970
            [-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
971
        )
Patrick von Platen's avatar
Patrick von Platen committed
972
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2
patil-suraj's avatar
patil-suraj committed
973

Patrick von Platen's avatar
Patrick von Platen committed
974
975
976
977
    @slow
    def test_pndm_cifar10(self):
        model_id = "fusing/ddpm-cifar10"

978
        unet = UNetUnconditionalModel.from_pretrained(model_id, ddpm=True)
979
        scheduler = PNDMScheduler(tensor_format="pt")
Patrick von Platen's avatar
Patrick von Platen committed
980

981
        pndm = PNDMPipeline(unet=unet, scheduler=scheduler)
Patrick von Platen's avatar
Patrick von Platen committed
982
        generator = torch.manual_seed(0)
Patrick von Platen's avatar
Patrick von Platen committed
983
984
985
986
987
988
        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
989
            [-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
990
991
992
        )
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

patil-suraj's avatar
patil-suraj committed
993
    @slow
patil-suraj's avatar
patil-suraj committed
994
    @unittest.skip("Skipping for now as it takes too long")
patil-suraj's avatar
patil-suraj committed
995
996
    def test_ldm_text2img(self):
        model_id = "fusing/latent-diffusion-text2im-large"
Patrick von Platen's avatar
Patrick von Platen committed
997
        ldm = LatentDiffusionPipeline.from_pretrained(model_id)
patil-suraj's avatar
patil-suraj committed
998
999
1000
1001
1002
1003
1004
1005
1006

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

patil-suraj's avatar
patil-suraj committed
1009
1010
1011
1012
1013
1014
1015
    @slow
    def test_ldm_text2img_fast(self):
        model_id = "fusing/latent-diffusion-text2im-large"
        ldm = LatentDiffusionPipeline.from_pretrained(model_id)

        prompt = "A painting of a squirrel eating a burger"
        generator = torch.manual_seed(0)
1016
        image = ldm([prompt], generator=generator, num_inference_steps=1)
patil-suraj's avatar
patil-suraj committed
1017
1018
1019
1020

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

        assert image.shape == (1, 3, 256, 256)
patil-suraj's avatar
patil-suraj committed
1021
        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
1022
1023
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2

anton-l's avatar
anton-l committed
1024
1025
1026
    @slow
    def test_glide_text2img(self):
        model_id = "fusing/glide-base"
Patrick von Platen's avatar
Patrick von Platen committed
1027
        glide = GlidePipeline.from_pretrained(model_id)
anton-l's avatar
anton-l committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038

        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
1039
1040
1041
1042
1043
1044
1045
    @slow
    def test_score_sde_ve_pipeline(self):
        model = NCSNpp.from_pretrained("fusing/ffhq_ncsnpp")
        scheduler = ScoreSdeVeScheduler.from_config("fusing/ffhq_ncsnpp")

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

1046
        torch.manual_seed(0)
Patrick von Platen's avatar
Patrick von Platen committed
1047
1048
        image = sde_ve(num_inference_steps=2)

1049
1050
        expected_image_sum = 3382849024.0
        expected_image_mean = 1075.3788
Patrick von Platen's avatar
Patrick von Platen committed
1051
1052
1053
1054

        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
1055
1056
    @slow
    def test_score_sde_vp_pipeline(self):
Patrick von Platen's avatar
Patrick von Platen committed
1057
1058
        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
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070

        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

        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
1071
1072
    @slow
    def test_ldm_uncond(self):
Patrick von Platen's avatar
Patrick von Platen committed
1073
1074
#        ldm = LatentDiffusionUncondPipeline.from_pretrained("fusing/latent-diffusion-celeba-256", ldm=True)
        ldm = LatentDiffusionUncondPipeline.from_pretrained("CompVis/latent-diffusion-celeba-256")
patil-suraj's avatar
patil-suraj committed
1075
1076

        generator = torch.manual_seed(0)
1077
        image = ldm(generator=generator, num_inference_steps=5)["sample"]
patil-suraj's avatar
patil-suraj committed
1078
1079
1080
1081

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

        assert image.shape == (1, 3, 256, 256)
patil-suraj's avatar
patil-suraj committed
1082
1083
1084
        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
1085
        assert (image_slice.flatten() - expected_slice).abs().max() < 1e-2