test_scheduler.py 29.1 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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
15
import tempfile
Patrick von Platen's avatar
Patrick von Platen committed
16
import unittest
Patrick von Platen's avatar
Patrick von Platen committed
17

Patrick von Platen's avatar
Patrick von Platen committed
18
19
20
import numpy as np
import torch

Nathan Lambert's avatar
Nathan Lambert committed
21
from diffusers import DDIMScheduler, DDPMScheduler, PNDMScheduler, ScoreSdeVeScheduler
Patrick von Platen's avatar
Patrick von Platen committed
22
23
24
25
26
27


torch.backends.cuda.matmul.allow_tf32 = False


class SchedulerCommonTest(unittest.TestCase):
Patrick von Platen's avatar
Patrick von Platen committed
28
29
    scheduler_classes = ()
    forward_default_kwargs = ()
Patrick von Platen's avatar
Patrick von Platen committed
30
31

    @property
32
    def dummy_sample(self):
Patrick von Platen's avatar
Patrick von Platen committed
33
34
35
36
37
        batch_size = 4
        num_channels = 3
        height = 8
        width = 8

38
        sample = torch.rand((batch_size, num_channels, height, width))
Patrick von Platen's avatar
Patrick von Platen committed
39

40
        return sample
Patrick von Platen's avatar
Patrick von Platen committed
41
42

    @property
43
    def dummy_sample_deter(self):
Patrick von Platen's avatar
Patrick von Platen committed
44
45
46
47
48
49
        batch_size = 4
        num_channels = 3
        height = 8
        width = 8

        num_elems = batch_size * num_channels * height * width
50
        sample = torch.arange(num_elems)
51
52
        sample = sample.reshape(num_channels, height, width, batch_size)
        sample = sample / num_elems
53
        sample = sample.permute(3, 0, 1, 2)
Patrick von Platen's avatar
Patrick von Platen committed
54

55
        return sample
Patrick von Platen's avatar
Patrick von Platen committed
56
57
58
59
60

    def get_scheduler_config(self):
        raise NotImplementedError

    def dummy_model(self):
61
62
        def model(sample, t, *args):
            return sample * t / (t + 1)
Patrick von Platen's avatar
Patrick von Platen committed
63
64
65

        return model

Patrick von Platen's avatar
Patrick von Platen committed
66
67
68
    def check_over_configs(self, time_step=0, **config):
        kwargs = dict(self.forward_default_kwargs)

69
70
        num_inference_steps = kwargs.pop("num_inference_steps", None)

Patrick von Platen's avatar
Patrick von Platen committed
71
        for scheduler_class in self.scheduler_classes:
72
73
            sample = self.dummy_sample
            residual = 0.1 * sample
Patrick von Platen's avatar
Patrick von Platen committed
74
75
76
77
78
79
80
81

            scheduler_config = self.get_scheduler_config(**config)
            scheduler = scheduler_class(**scheduler_config)

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)

82
83
84
85
86
87
88
89
            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
                new_scheduler.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

            output = scheduler.step(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step(residual, time_step, sample, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
90

91
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Patrick von Platen's avatar
Patrick von Platen committed
92
93
94
95
96

    def check_over_forward(self, time_step=0, **forward_kwargs):
        kwargs = dict(self.forward_default_kwargs)
        kwargs.update(forward_kwargs)

97
98
        num_inference_steps = kwargs.pop("num_inference_steps", None)

Patrick von Platen's avatar
Patrick von Platen committed
99
        for scheduler_class in self.scheduler_classes:
100
101
            sample = self.dummy_sample
            residual = 0.1 * sample
Patrick von Platen's avatar
Patrick von Platen committed
102
103
104
105
106
107
108
109

            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)

110
111
112
113
114
115
116
117
118
119
            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
                new_scheduler.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

            torch.manual_seed(0)
            output = scheduler.step(residual, time_step, sample, **kwargs)["prev_sample"]
            torch.manual_seed(0)
            new_output = new_scheduler.step(residual, time_step, sample, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
120

121
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Patrick von Platen's avatar
Patrick von Platen committed
122

Patrick von Platen's avatar
Patrick von Platen committed
123
    def test_from_pretrained_save_pretrained(self):
Patrick von Platen's avatar
Patrick von Platen committed
124
125
        kwargs = dict(self.forward_default_kwargs)

126
127
        num_inference_steps = kwargs.pop("num_inference_steps", None)

Patrick von Platen's avatar
Patrick von Platen committed
128
        for scheduler_class in self.scheduler_classes:
129
130
            sample = self.dummy_sample
            residual = 0.1 * sample
Patrick von Platen's avatar
Patrick von Platen committed
131
132
133
134
135
136
137
138

            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)

139
140
141
142
143
144
            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
                new_scheduler.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

145
            torch.manual_seed(0)
146
            output = scheduler.step(residual, 1, sample, **kwargs)["prev_sample"]
147
            torch.manual_seed(0)
148
            new_output = new_scheduler.step(residual, 1, sample, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
149

150
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Patrick von Platen's avatar
Patrick von Platen committed
151
152
153
154

    def test_step_shape(self):
        kwargs = dict(self.forward_default_kwargs)

155
156
        num_inference_steps = kwargs.pop("num_inference_steps", None)

Patrick von Platen's avatar
Patrick von Platen committed
157
158
159
160
        for scheduler_class in self.scheduler_classes:
            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

161
162
            sample = self.dummy_sample
            residual = 0.1 * sample
Patrick von Platen's avatar
Patrick von Platen committed
163

164
165
166
167
168
169
170
            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

            output_0 = scheduler.step(residual, 0, sample, **kwargs)["prev_sample"]
            output_1 = scheduler.step(residual, 1, sample, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
171

172
            self.assertEqual(output_0.shape, sample.shape)
Patrick von Platen's avatar
Patrick von Platen committed
173
174
            self.assertEqual(output_0.shape, output_1.shape)

Patrick von Platen's avatar
Patrick von Platen committed
175
176
177
    def test_pytorch_equal_numpy(self):
        kwargs = dict(self.forward_default_kwargs)

178
179
        num_inference_steps = kwargs.pop("num_inference_steps", None)

Patrick von Platen's avatar
Patrick von Platen committed
180
        for scheduler_class in self.scheduler_classes:
181
            sample_pt = self.dummy_sample
182
            residual_pt = 0.1 * sample_pt
Patrick von Platen's avatar
Patrick von Platen committed
183

184
185
186
            sample = sample_pt.numpy()
            residual = 0.1 * sample

Patrick von Platen's avatar
Patrick von Platen committed
187
            scheduler_config = self.get_scheduler_config()
188
            scheduler = scheduler_class(tensor_format="np", **scheduler_config)
Patrick von Platen's avatar
Patrick von Platen committed
189
190
191

            scheduler_pt = scheduler_class(tensor_format="pt", **scheduler_config)

192
193
194
195
196
197
198
199
            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
                scheduler_pt.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

            output = scheduler.step(residual, 1, sample, **kwargs)["prev_sample"]
            output_pt = scheduler_pt.step(residual_pt, 1, sample_pt, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
200

Patrick von Platen's avatar
Patrick von Platen committed
201
            assert np.sum(np.abs(output - output_pt.numpy())) < 1e-4, "Scheduler outputs are not identical"
Patrick von Platen's avatar
Patrick von Platen committed
202

Patrick von Platen's avatar
Patrick von Platen committed
203
204

class DDPMSchedulerTest(SchedulerCommonTest):
Patrick von Platen's avatar
Patrick von Platen committed
205
    scheduler_classes = (DDPMScheduler,)
Patrick von Platen's avatar
Patrick von Platen committed
206
207
208

    def get_scheduler_config(self, **kwargs):
        config = {
Nathan Lambert's avatar
Nathan Lambert committed
209
            "num_train_timesteps": 1000,
Patrick von Platen's avatar
Patrick von Platen committed
210
211
212
213
            "beta_start": 0.0001,
            "beta_end": 0.02,
            "beta_schedule": "linear",
            "variance_type": "fixed_small",
Patrick von Platen's avatar
Patrick von Platen committed
214
            "clip_sample": True,
215
            "tensor_format": "pt",
Patrick von Platen's avatar
Patrick von Platen committed
216
217
218
219
        }

        config.update(**kwargs)
        return config
Patrick von Platen's avatar
update  
Patrick von Platen committed
220

Patrick von Platen's avatar
Patrick von Platen committed
221
222
    def test_timesteps(self):
        for timesteps in [1, 5, 100, 1000]:
Nathan Lambert's avatar
Nathan Lambert committed
223
            self.check_over_configs(num_train_timesteps=timesteps)
Patrick von Platen's avatar
Patrick von Platen committed
224
225
226
227
228
229
230
231
232
233
234
235
236

    def test_betas(self):
        for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1], [0.002, 0.02, 0.2, 2]):
            self.check_over_configs(beta_start=beta_start, beta_end=beta_end)

    def test_schedules(self):
        for schedule in ["linear", "squaredcos_cap_v2"]:
            self.check_over_configs(beta_schedule=schedule)

    def test_variance_type(self):
        for variance in ["fixed_small", "fixed_large", "other"]:
            self.check_over_configs(variance_type=variance)

237
    def test_clip_sample(self):
Patrick von Platen's avatar
Patrick von Platen committed
238
239
        for clip_sample in [True, False]:
            self.check_over_configs(clip_sample=clip_sample)
Patrick von Platen's avatar
Patrick von Platen committed
240
241
242
243
244
245
246
247
248
249

    def test_time_indices(self):
        for t in [0, 500, 999]:
            self.check_over_forward(time_step=t)

    def test_variance(self):
        scheduler_class = self.scheduler_classes[0]
        scheduler_config = self.get_scheduler_config()
        scheduler = scheduler_class(**scheduler_config)

250
251
252
253
254
255
256
        assert torch.sum(torch.abs(scheduler._get_variance(0) - 0.0)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(487) - 0.00979)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(999) - 0.02)) < 1e-5

    # TODO Make DDPM Numpy compatible
    def test_pytorch_equal_numpy(self):
        pass
Patrick von Platen's avatar
Patrick von Platen committed
257
258
259

    def test_full_loop_no_noise(self):
        scheduler_class = self.scheduler_classes[0]
Patrick von Platen's avatar
Patrick von Platen committed
260
        scheduler_config = self.get_scheduler_config()
Patrick von Platen's avatar
Patrick von Platen committed
261
262
263
264
265
        scheduler = scheduler_class(**scheduler_config)

        num_trained_timesteps = len(scheduler)

        model = self.dummy_model()
266
        sample = self.dummy_sample_deter
Patrick von Platen's avatar
Patrick von Platen committed
267
268
269

        for t in reversed(range(num_trained_timesteps)):
            # 1. predict noise residual
270
            residual = model(sample, t)
Patrick von Platen's avatar
Patrick von Platen committed
271

272
            # 2. predict previous mean of sample x_t-1
273
            pred_prev_sample = scheduler.step(residual, t, sample)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
274

275
276
277
278
279
280
            # if t > 0:
            #     noise = self.dummy_sample_deter
            #     variance = scheduler.get_variance(t) ** (0.5) * noise
            #
            # sample = pred_prev_sample + variance
            sample = pred_prev_sample
Patrick von Platen's avatar
Patrick von Platen committed
281

282
283
        result_sum = torch.sum(torch.abs(sample))
        result_mean = torch.mean(torch.abs(sample))
Patrick von Platen's avatar
Patrick von Platen committed
284

285
286
        assert abs(result_sum.item() - 259.0883) < 1e-2
        assert abs(result_mean.item() - 0.3374) < 1e-3
Patrick von Platen's avatar
Patrick von Platen committed
287

Patrick von Platen's avatar
update  
Patrick von Platen committed
288

Patrick von Platen's avatar
Patrick von Platen committed
289
290
class DDIMSchedulerTest(SchedulerCommonTest):
    scheduler_classes = (DDIMScheduler,)
291
    forward_default_kwargs = (("eta", 0.0), ("num_inference_steps", 50))
Patrick von Platen's avatar
update  
Patrick von Platen committed
292

Patrick von Platen's avatar
Patrick von Platen committed
293
294
    def get_scheduler_config(self, **kwargs):
        config = {
Nathan Lambert's avatar
Nathan Lambert committed
295
            "num_train_timesteps": 1000,
Patrick von Platen's avatar
Patrick von Platen committed
296
297
298
            "beta_start": 0.0001,
            "beta_end": 0.02,
            "beta_schedule": "linear",
Patrick von Platen's avatar
Patrick von Platen committed
299
            "clip_sample": True,
Patrick von Platen's avatar
Patrick von Platen committed
300
        }
Patrick von Platen's avatar
Patrick von Platen committed
301

Patrick von Platen's avatar
Patrick von Platen committed
302
303
304
305
        config.update(**kwargs)
        return config

    def test_timesteps(self):
306
        for timesteps in [100, 500, 1000]:
Nathan Lambert's avatar
Nathan Lambert committed
307
            self.check_over_configs(num_train_timesteps=timesteps)
Patrick von Platen's avatar
Patrick von Platen committed
308
309
310
311
312
313
314
315
316

    def test_betas(self):
        for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1], [0.002, 0.02, 0.2, 2]):
            self.check_over_configs(beta_start=beta_start, beta_end=beta_end)

    def test_schedules(self):
        for schedule in ["linear", "squaredcos_cap_v2"]:
            self.check_over_configs(beta_schedule=schedule)

317
    def test_clip_sample(self):
Patrick von Platen's avatar
Patrick von Platen committed
318
319
        for clip_sample in [True, False]:
            self.check_over_configs(clip_sample=clip_sample)
Patrick von Platen's avatar
Patrick von Platen committed
320
321
322
323
324
325
326

    def test_time_indices(self):
        for t in [1, 10, 49]:
            self.check_over_forward(time_step=t)

    def test_inference_steps(self):
        for t, num_inference_steps in zip([1, 10, 50], [10, 50, 500]):
327
            self.check_over_forward(num_inference_steps=num_inference_steps)
Patrick von Platen's avatar
Patrick von Platen committed
328
329
330
331
332
333
334

    def test_eta(self):
        for t, eta in zip([1, 10, 49], [0.0, 0.5, 1.0]):
            self.check_over_forward(time_step=t, eta=eta)

    def test_variance(self):
        scheduler_class = self.scheduler_classes[0]
Patrick von Platen's avatar
Patrick von Platen committed
335
        scheduler_config = self.get_scheduler_config()
Patrick von Platen's avatar
Patrick von Platen committed
336
337
        scheduler = scheduler_class(**scheduler_config)

338
339
340
341
342
343
        assert torch.sum(torch.abs(scheduler._get_variance(0, 0) - 0.0)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(420, 400) - 0.14771)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(980, 960) - 0.32460)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(0, 0) - 0.0)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(487, 486) - 0.00979)) < 1e-5
        assert torch.sum(torch.abs(scheduler._get_variance(999, 998) - 0.02)) < 1e-5
Patrick von Platen's avatar
Patrick von Platen committed
344
345
346
347
348
349

    def test_full_loop_no_noise(self):
        scheduler_class = self.scheduler_classes[0]
        scheduler_config = self.get_scheduler_config()
        scheduler = scheduler_class(**scheduler_config)

350
        num_inference_steps, eta = 10, 0.0
Patrick von Platen's avatar
Patrick von Platen committed
351
352

        model = self.dummy_model()
353
        sample = self.dummy_sample_deter
Patrick von Platen's avatar
Patrick von Platen committed
354

355
356
357
        scheduler.set_timesteps(num_inference_steps)
        for t in scheduler.timesteps:
            residual = model(sample, t)
Patrick von Platen's avatar
Patrick von Platen committed
358

359
            sample = scheduler.step(residual, t, sample, eta)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
360

361
362
        result_sum = torch.sum(torch.abs(sample))
        result_mean = torch.mean(torch.abs(sample))
Patrick von Platen's avatar
Patrick von Platen committed
363

364
365
        assert abs(result_sum.item() - 172.0067) < 1e-2
        assert abs(result_mean.item() - 0.223967) < 1e-3
Patrick von Platen's avatar
Patrick von Platen committed
366
367
368
369
370
371
372
373


class PNDMSchedulerTest(SchedulerCommonTest):
    scheduler_classes = (PNDMScheduler,)
    forward_default_kwargs = (("num_inference_steps", 50),)

    def get_scheduler_config(self, **kwargs):
        config = {
Nathan Lambert's avatar
Nathan Lambert committed
374
            "num_train_timesteps": 1000,
Patrick von Platen's avatar
Patrick von Platen committed
375
376
377
378
379
380
381
382
            "beta_start": 0.0001,
            "beta_end": 0.02,
            "beta_schedule": "linear",
        }

        config.update(**kwargs)
        return config

383
    def check_over_configs(self, time_step=0, **config):
Patrick von Platen's avatar
Patrick von Platen committed
384
        kwargs = dict(self.forward_default_kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
385
        num_inference_steps = kwargs.pop("num_inference_steps", None)
386
387
        sample = self.dummy_sample
        residual = 0.1 * sample
Patrick von Platen's avatar
Patrick von Platen committed
388
389
390
391
392
        dummy_past_residuals = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

        for scheduler_class in self.scheduler_classes:
            scheduler_config = self.get_scheduler_config(**config)
            scheduler = scheduler_class(**scheduler_config)
Patrick von Platen's avatar
Patrick von Platen committed
393
            scheduler.set_timesteps(num_inference_steps)
Patrick von Platen's avatar
Patrick von Platen committed
394
395
396
397
398
399
            # copy over dummy past residuals
            scheduler.ets = dummy_past_residuals[:]

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
400
                new_scheduler.set_timesteps(num_inference_steps)
Patrick von Platen's avatar
Patrick von Platen committed
401
402
403
                # copy over dummy past residuals
                new_scheduler.ets = dummy_past_residuals[:]

404
405
            output = scheduler.step_prk(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_prk(residual, time_step, sample, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
406

407
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Patrick von Platen's avatar
Patrick von Platen committed
408

409
410
411
            output = scheduler.step_plms(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_plms(residual, time_step, sample, **kwargs)["prev_sample"]

412
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
413
414
415
416
417

    def test_from_pretrained_save_pretrained(self):
        pass

    def check_over_forward(self, time_step=0, **forward_kwargs):
Patrick von Platen's avatar
Patrick von Platen committed
418
        kwargs = dict(self.forward_default_kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
419
        num_inference_steps = kwargs.pop("num_inference_steps", None)
420
421
        sample = self.dummy_sample
        residual = 0.1 * sample
Patrick von Platen's avatar
Patrick von Platen committed
422
423
424
425
426
        dummy_past_residuals = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

        for scheduler_class in self.scheduler_classes:
            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)
Patrick von Platen's avatar
Patrick von Platen committed
427
            scheduler.set_timesteps(num_inference_steps)
428

Patrick von Platen's avatar
Patrick von Platen committed
429
430
431
432
433
434
435
436
            # copy over dummy past residuals
            scheduler.ets = dummy_past_residuals[:]

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)
                # copy over dummy past residuals
                new_scheduler.ets = dummy_past_residuals[:]
Patrick von Platen's avatar
Patrick von Platen committed
437
                new_scheduler.set_timesteps(num_inference_steps)
Patrick von Platen's avatar
Patrick von Platen committed
438

439
440
441
            output = scheduler.step_prk(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_prk(residual, time_step, sample, **kwargs)["prev_sample"]

442
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
443
444
445

            output = scheduler.step_plms(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_plms(residual, time_step, sample, **kwargs)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
446

447
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Patrick von Platen's avatar
Patrick von Platen committed
448

449
450
451
452
453
    def test_pytorch_equal_numpy(self):
        kwargs = dict(self.forward_default_kwargs)
        num_inference_steps = kwargs.pop("num_inference_steps", None)

        for scheduler_class in self.scheduler_classes:
454
            sample_pt = self.dummy_sample
455
456
457
            residual_pt = 0.1 * sample_pt
            dummy_past_residuals_pt = [residual_pt + 0.2, residual_pt + 0.15, residual_pt + 0.1, residual_pt + 0.05]

458
459
460
461
            sample = sample_pt.numpy()
            residual = 0.1 * sample
            dummy_past_residuals = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

462
            scheduler_config = self.get_scheduler_config()
463
            scheduler = scheduler_class(tensor_format="np", **scheduler_config)
464
465
466
467
468
469
470
471
472
473
474
475
476
            # copy over dummy past residuals
            scheduler.ets = dummy_past_residuals[:]

            scheduler_pt = scheduler_class(tensor_format="pt", **scheduler_config)
            # copy over dummy past residuals
            scheduler_pt.ets = dummy_past_residuals_pt[:]

            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
                scheduler_pt.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

Patrick von Platen's avatar
Patrick von Platen committed
477
478
            output = scheduler.step_prk(residual, 1, sample, **kwargs)["prev_sample"]
            output_pt = scheduler_pt.step_prk(residual_pt, 1, sample_pt, **kwargs)["prev_sample"]
479
480
            assert np.sum(np.abs(output - output_pt.numpy())) < 1e-4, "Scheduler outputs are not identical"

Patrick von Platen's avatar
Patrick von Platen committed
481
482
            output = scheduler.step_plms(residual, 1, sample, **kwargs)["prev_sample"]
            output_pt = scheduler_pt.step_plms(residual_pt, 1, sample_pt, **kwargs)["prev_sample"]
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

            assert np.sum(np.abs(output - output_pt.numpy())) < 1e-4, "Scheduler outputs are not identical"

    def test_step_shape(self):
        kwargs = dict(self.forward_default_kwargs)

        num_inference_steps = kwargs.pop("num_inference_steps", None)

        for scheduler_class in self.scheduler_classes:
            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

            sample = self.dummy_sample
            residual = 0.1 * sample
            # copy over dummy past residuals
            dummy_past_residuals = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
            scheduler.ets = dummy_past_residuals[:]

            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

Patrick von Platen's avatar
Patrick von Platen committed
506
507
            output_0 = scheduler.step_prk(residual, 0, sample, **kwargs)["prev_sample"]
            output_1 = scheduler.step_prk(residual, 1, sample, **kwargs)["prev_sample"]
508
509
510
511

            self.assertEqual(output_0.shape, sample.shape)
            self.assertEqual(output_0.shape, output_1.shape)

Patrick von Platen's avatar
Patrick von Platen committed
512
513
            output_0 = scheduler.step_plms(residual, 0, sample, **kwargs)["prev_sample"]
            output_1 = scheduler.step_plms(residual, 1, sample, **kwargs)["prev_sample"]
514
515
516
517

            self.assertEqual(output_0.shape, sample.shape)
            self.assertEqual(output_0.shape, output_1.shape)

Patrick von Platen's avatar
Patrick von Platen committed
518
519
    def test_timesteps(self):
        for timesteps in [100, 1000]:
Nathan Lambert's avatar
Nathan Lambert committed
520
            self.check_over_configs(num_train_timesteps=timesteps)
Patrick von Platen's avatar
Patrick von Platen committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537

    def test_betas(self):
        for beta_start, beta_end in zip([0.0001, 0.001, 0.01], [0.002, 0.02, 0.2]):
            self.check_over_configs(beta_start=beta_start, beta_end=beta_end)

    def test_schedules(self):
        for schedule in ["linear", "squaredcos_cap_v2"]:
            self.check_over_configs(beta_schedule=schedule)

    def test_time_indices(self):
        for t in [1, 5, 10]:
            self.check_over_forward(time_step=t)

    def test_inference_steps(self):
        for t, num_inference_steps in zip([1, 5, 10], [10, 50, 100]):
            self.check_over_forward(time_step=t, num_inference_steps=num_inference_steps)

538
    def test_inference_plms_no_past_residuals(self):
Patrick von Platen's avatar
Patrick von Platen committed
539
540
541
542
543
        with self.assertRaises(ValueError):
            scheduler_class = self.scheduler_classes[0]
            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

Patrick von Platen's avatar
Patrick von Platen committed
544
            scheduler.step_plms(self.dummy_sample, 1, self.dummy_sample)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
545
546
547
548
549
550
551
552

    def test_full_loop_no_noise(self):
        scheduler_class = self.scheduler_classes[0]
        scheduler_config = self.get_scheduler_config()
        scheduler = scheduler_class(**scheduler_config)

        num_inference_steps = 10
        model = self.dummy_model()
553
        sample = self.dummy_sample_deter
554
        scheduler.set_timesteps(num_inference_steps)
Patrick von Platen's avatar
Patrick von Platen committed
555

556
557
        for i, t in enumerate(scheduler.prk_timesteps):
            residual = model(sample, t)
Patrick von Platen's avatar
Patrick von Platen committed
558
            sample = scheduler.step_prk(residual, i, sample)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
559

560
561
        for i, t in enumerate(scheduler.plms_timesteps):
            residual = model(sample, t)
Patrick von Platen's avatar
Patrick von Platen committed
562
            sample = scheduler.step_plms(residual, i, sample)["prev_sample"]
Patrick von Platen's avatar
Patrick von Platen committed
563

564
565
        result_sum = torch.sum(torch.abs(sample))
        result_mean = torch.mean(torch.abs(sample))
Patrick von Platen's avatar
Patrick von Platen committed
566
567
568

        assert abs(result_sum.item() - 199.1169) < 1e-2
        assert abs(result_mean.item() - 0.2593) < 1e-3
Nathan Lambert's avatar
Nathan Lambert committed
569
570


571
572
class ScoreSdeVeSchedulerTest(unittest.TestCase):
    # TODO adapt with class SchedulerCommonTest (scheduler needs Numpy Integration)
Nathan Lambert's avatar
Nathan Lambert committed
573
    scheduler_classes = (ScoreSdeVeScheduler,)
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    forward_default_kwargs = (("seed", 0),)

    @property
    def dummy_sample(self):
        batch_size = 4
        num_channels = 3
        height = 8
        width = 8

        sample = torch.rand((batch_size, num_channels, height, width))

        return sample

    @property
    def dummy_sample_deter(self):
        batch_size = 4
        num_channels = 3
        height = 8
        width = 8

        num_elems = batch_size * num_channels * height * width
        sample = torch.arange(num_elems)
        sample = sample.reshape(num_channels, height, width, batch_size)
        sample = sample / num_elems
        sample = sample.permute(3, 0, 1, 2)

        return sample

    def dummy_model(self):
        def model(sample, t, *args):
            return sample * t / (t + 1)

        return model
Nathan Lambert's avatar
Nathan Lambert committed
607
608
609
610
611
612
613
614

    def get_scheduler_config(self, **kwargs):
        config = {
            "num_train_timesteps": 2000,
            "snr": 0.15,
            "sigma_min": 0.01,
            "sigma_max": 1348,
            "sampling_eps": 1e-5,
615
            "tensor_format": "pt",  # TODO add test for tensor formats
Nathan Lambert's avatar
Nathan Lambert committed
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
        }

        config.update(**kwargs)
        return config

    def check_over_configs(self, time_step=0, **config):
        kwargs = dict(self.forward_default_kwargs)

        for scheduler_class in self.scheduler_classes:
            sample = self.dummy_sample
            residual = 0.1 * sample

            scheduler_config = self.get_scheduler_config(**config)
            scheduler = scheduler_class(**scheduler_config)

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)

635
636
            output = scheduler.step_pred(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_pred(residual, time_step, sample, **kwargs)["prev_sample"]
Nathan Lambert's avatar
Nathan Lambert committed
637

638
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Nathan Lambert's avatar
Nathan Lambert committed
639

640
641
            output = scheduler.step_correct(residual, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_correct(residual, sample, **kwargs)["prev_sample"]
Nathan Lambert's avatar
Nathan Lambert committed
642

643
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler correction are not identical"
Nathan Lambert's avatar
Nathan Lambert committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659

    def check_over_forward(self, time_step=0, **forward_kwargs):
        kwargs = dict(self.forward_default_kwargs)
        kwargs.update(forward_kwargs)

        for scheduler_class in self.scheduler_classes:
            sample = self.dummy_sample
            residual = 0.1 * sample

            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

            with tempfile.TemporaryDirectory() as tmpdirname:
                scheduler.save_config(tmpdirname)
                new_scheduler = scheduler_class.from_config(tmpdirname)

660
661
            output = scheduler.step_pred(residual, time_step, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_pred(residual, time_step, sample, **kwargs)["prev_sample"]
Nathan Lambert's avatar
Nathan Lambert committed
662

663
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
Nathan Lambert's avatar
Nathan Lambert committed
664

665
666
            output = scheduler.step_correct(residual, sample, **kwargs)["prev_sample"]
            new_output = new_scheduler.step_correct(residual, sample, **kwargs)["prev_sample"]
Nathan Lambert's avatar
Nathan Lambert committed
667

668
            assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler correction are not identical"
Nathan Lambert's avatar
Nathan Lambert committed
669
670
671
672
673
674
675
676
677
678

    def test_timesteps(self):
        for timesteps in [10, 100, 1000]:
            self.check_over_configs(num_train_timesteps=timesteps)

    def test_sigmas(self):
        for sigma_min, sigma_max in zip([0.0001, 0.001, 0.01], [1, 100, 1000]):
            self.check_over_configs(sigma_min=sigma_min, sigma_max=sigma_max)

    def test_time_indices(self):
679
        for t in [0.1, 0.5, 0.75]:
Nathan Lambert's avatar
Nathan Lambert committed
680
681
682
            self.check_over_forward(time_step=t)

    def test_full_loop_no_noise(self):
683
684
        kwargs = dict(self.forward_default_kwargs)

Nathan Lambert's avatar
Nathan Lambert committed
685
686
687
688
689
690
691
692
693
694
        scheduler_class = self.scheduler_classes[0]
        scheduler_config = self.get_scheduler_config()
        scheduler = scheduler_class(**scheduler_config)

        num_inference_steps = 3

        model = self.dummy_model()
        sample = self.dummy_sample_deter

        scheduler.set_sigmas(num_inference_steps)
695
        scheduler.set_timesteps(num_inference_steps)
Nathan Lambert's avatar
Nathan Lambert committed
696
697
698
699
700
701

        for i, t in enumerate(scheduler.timesteps):
            sigma_t = scheduler.sigmas[i]

            for _ in range(scheduler.correct_steps):
                with torch.no_grad():
702
703
                    model_output = model(sample, sigma_t)
                sample = scheduler.step_correct(model_output, sample, **kwargs)["prev_sample"]
Nathan Lambert's avatar
Nathan Lambert committed
704
705

            with torch.no_grad():
706
                model_output = model(sample, sigma_t)
Patrick von Platen's avatar
Patrick von Platen committed
707

708
            output = scheduler.step_pred(model_output, t, sample, **kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
709
            sample, _ = output["prev_sample"], output["prev_sample_mean"]
Patrick von Platen's avatar
Patrick von Platen committed
710

711
712
        result_sum = torch.sum(torch.abs(sample))
        result_mean = torch.mean(torch.abs(sample))
Patrick von Platen's avatar
Patrick von Platen committed
713

714
715
        assert abs(result_sum.item() - 14379591680.0) < 1e-2
        assert abs(result_mean.item() - 18723426.0) < 1e-3
Patrick von Platen's avatar
Patrick von Platen committed
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738

    def test_step_shape(self):
        kwargs = dict(self.forward_default_kwargs)

        num_inference_steps = kwargs.pop("num_inference_steps", None)

        for scheduler_class in self.scheduler_classes:
            scheduler_config = self.get_scheduler_config()
            scheduler = scheduler_class(**scheduler_config)

            sample = self.dummy_sample
            residual = 0.1 * sample

            if num_inference_steps is not None and hasattr(scheduler, "set_timesteps"):
                scheduler.set_timesteps(num_inference_steps)
            elif num_inference_steps is not None and not hasattr(scheduler, "set_timesteps"):
                kwargs["num_inference_steps"] = num_inference_steps

            output_0 = scheduler.step_pred(residual, 0, sample, **kwargs)["prev_sample"]
            output_1 = scheduler.step_pred(residual, 1, sample, **kwargs)["prev_sample"]

            self.assertEqual(output_0.shape, sample.shape)
            self.assertEqual(output_0.shape, output_1.shape)