-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsolvers.py
821 lines (740 loc) · 39 KB
/
solvers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# Implementation of various ODE solvers for diffusion models.
import torch
from solver_utils import *
#----------------------------------------------------------------------------
# Get the denoised output from the pre-trained diffusion models.
def get_denoised(net, x, t, class_labels=None, condition=None, unconditional_condition=None):
if hasattr(net, 'guidance_type'): # models from LDM and Stable Diffusion
denoised = net(x, t, condition=condition, unconditional_condition=unconditional_condition)
else:
denoised = net(x, t, class_labels=class_labels)
return denoised
#----------------------------------------------------------------------------
@torch.no_grad()
def euler_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
t_steps=None,
**kwargs
):
"""
Euler sampler (equivalent to the DDIM sampler: https://arxiv.org/abs/2010.02502).
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
Returns:
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
"""
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
# Euler step.
use_afs = (afs and i == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
x_next = x_cur + (t_next - t_cur) * d_cur
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def heun_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
t_steps=None,
**kwargs
):
"""
Heun's second sampler. Introduced in EDM: https://arxiv.org/abs/2206.00364.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
Returns:
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
"""
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
# Euler step.
use_afs = (afs and i == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
x_next = x_cur + (t_next - t_cur) * d_cur
# Apply 2nd order correction.
denoised = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_prime = (x_next - denoised) / t_next
x_next = x_cur + (t_next - t_cur) * (0.5 * d_cur + 0.5 * d_prime)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def dpm_2_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
r=0.5,
t_steps=None,
**kwargs
):
"""
DPM-Solver-2 sampler: https://arxiv.org/abs/2206.00927.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
r: A `float`. The hyperparameter controlling the location of the intermediate time step. r=0.5 recovers the original DPM-Solver-2.
Returns:
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
"""
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
# Euler step.
use_afs = (afs and i == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
t_mid = (t_next ** r) * (t_cur ** (1 - r))
x_next = x_cur + (t_mid - t_cur) * d_cur
# Apply 2nd order correction.
denoised = get_denoised(net, x_next, t_mid, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_prime = (x_next - denoised) / t_mid
x_next = x_cur + (t_next - t_cur) * ((1 / (2*r)) * d_prime + (1 - 1 / (2*r)) * d_cur)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def ipndm_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
max_order=4,
t_steps=None,
**kwargs
):
"""
Improved PNDM sampler: https://arxiv.org/abs/2204.13902.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 4
Returns:
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
"""
assert max_order >= 1 and max_order <= 4
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
buffer_model = []
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
use_afs = (afs and i == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
order = min(max_order, i+1)
if order == 1: # First Euler step.
x_next = x_cur + (t_next - t_cur) * d_cur
elif order == 2: # Use one history point.
x_next = x_cur + (t_next - t_cur) * (3 * d_cur - buffer_model[-1]) / 2
elif order == 3: # Use two history points.
x_next = x_cur + (t_next - t_cur) * (23 * d_cur - 16 * buffer_model[-1] + 5 * buffer_model[-2]) / 12
elif order == 4: # Use three history points.
x_next = x_cur + (t_next - t_cur) * (55 * d_cur - 59 * buffer_model[-1] + 37 * buffer_model[-2] - 9 * buffer_model[-3]) / 24
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if len(buffer_model) == max_order - 1:
for k in range(max_order - 2):
buffer_model[k] = buffer_model[k+1]
buffer_model[-1] = d_cur
else:
buffer_model.append(d_cur)
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def ipndm_v_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
max_order=4,
t_steps=None,
**kwargs
):
"""
The variable-step version of the Adams-Bashforth methods.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 4
Returns:
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
"""
assert max_order >= 1 and max_order <= 4
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
buffer_model = []
root_d = (latents.shape[1] * latents.shape[-1] ** 2) ** (0.5)
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
x_cur = x_next
# afs
use_afs = (afs and len(buffer_model) == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
order = min(max_order, i+1)
if order == 1: # First Euler step.
x_next = x_cur + (t_next - t_cur) * d_cur
elif order == 2: # Use one history point.
h_n = (t_next - t_cur)
h_n_1 = (t_cur - t_steps[i-1])
coeff1 = (2 + (h_n / h_n_1)) / 2
coeff2 = -(h_n / h_n_1) / 2
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1])
elif order == 3: # Use two history points.
h_n = (t_next - t_cur)
h_n_1 = (t_cur - t_steps[i-1])
h_n_2 = (t_steps[i-1] - t_steps[i-2])
temp = (1 - h_n / (3 * (h_n + h_n_1)) * (h_n * (h_n + h_n_1)) / (h_n_1 * (h_n_1 + h_n_2))) / 2
coeff1 = (2 + (h_n / h_n_1)) / 2 + temp
coeff2 = -(h_n / h_n_1) / 2 - (1 + h_n_1 / h_n_2) * temp
coeff3 = temp * h_n_1 / h_n_2
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2])
elif order == 4: # Use three history points.
h_n = (t_next - t_cur)
h_n_1 = (t_cur - t_steps[i-1])
h_n_2 = (t_steps[i-1] - t_steps[i-2])
h_n_3 = (t_steps[i-2] - t_steps[i-3])
temp1 = (1 - h_n / (3 * (h_n + h_n_1)) * (h_n * (h_n + h_n_1)) / (h_n_1 * (h_n_1 + h_n_2))) / 2
temp2 = ((1 - h_n / (3 * (h_n + h_n_1))) / 2 + (1 - h_n / (2 * (h_n + h_n_1))) * h_n / (6 * (h_n + h_n_1 + h_n_2))) \
* (h_n * (h_n + h_n_1) * (h_n + h_n_1 + h_n_2)) / (h_n_1 * (h_n_1 + h_n_2) * (h_n_1 + h_n_2 + h_n_3))
coeff1 = (2 + (h_n / h_n_1)) / 2 + temp1 + temp2
coeff2 = -(h_n / h_n_1) / 2 - (1 + h_n_1 / h_n_2) * temp1 - (1 + (h_n_1 / h_n_2) + (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3)))) * temp2
coeff3 = temp1 * h_n_1 / h_n_2 + ((h_n_1 / h_n_2) + (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3))) * (1 + h_n_2 / h_n_3)) * temp2
coeff4 = -temp2 * (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3))) * h_n_1 / h_n_2
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2] + coeff4 * buffer_model[-3])
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if len(buffer_model) == max_order - 1:
for k in range(max_order - 2):
buffer_model[k] = buffer_model[k+1]
buffer_model[-1] = d_cur.detach()
else:
buffer_model.append(d_cur.detach())
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def deis_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
max_order=4,
coeff_list=None,
t_steps=None,
**kwargs
):
"""
A pytorch implementation of DEIS: https://arxiv.org/abs/2204.13902.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 4
coeff_list: A `list`. The pre-calculated coefficients for DEIS sampling.
Returns:
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
"""
assert max_order >= 1 and max_order <= 4
assert coeff_list is not None
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
buffer_model = []
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
use_afs = (afs and len(buffer_model) == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
order = min(max_order, i+1)
if order == 1: # First Euler step.
x_next = x_cur + (t_next - t_cur) * d_cur
elif order == 2: # Use one history point.
coeff_cur, coeff_prev1 = coeff_list[i]
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1]
elif order == 3: # Use two history points.
coeff_cur, coeff_prev1, coeff_prev2 = coeff_list[i]
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1] + coeff_prev2 * buffer_model[-2]
elif order == 4: # Use three history points.
coeff_cur, coeff_prev1, coeff_prev2, coeff_prev3 = coeff_list[i]
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1] + coeff_prev2 * buffer_model[-2] + coeff_prev3 * buffer_model[-3]
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if len(buffer_model) == max_order - 1:
for k in range(max_order - 2):
buffer_model[k] = buffer_model[k+1]
buffer_model[-1] = d_cur.detach()
else:
buffer_model.append(d_cur.detach())
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def dpm_pp_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
max_order=3,
predict_x0=True,
lower_order_final=True,
t_steps=None,
**kwargs
):
"""
Multistep DPM-Solver++ sampler: https://arxiv.org/abs/2211.01095.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
return_eps: A `bool`. Whether to save intermediate d_cur, i.e. the gradient.
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 3
predict_x0: A `bool`. Whether to use the data prediction formulation.
lower_order_final: A `bool`. Whether to lower the order at the final stages of sampling.
Returns:
A pytorch tensor. The sample at time `sigma_min` or the whole sampling trajectory if return_inters=True.
"""
assert max_order >= 1 and max_order <= 3
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
inters_eps = []
buffer_model = []
buffer_t = []
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
use_afs = (afs and i == 0)
if use_afs:
d_cur = x_cur / ((1 + t_cur**2).sqrt())
denoised = x_cur - t_cur * d_cur
else:
denoised = get_denoised(net, x_cur, t_cur, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_cur = (x_cur - denoised) / t_cur
buffer_model.append(dynamic_thresholding_fn(denoised)) if predict_x0 else buffer_model.append(d_cur)
buffer_t.append(t_cur)
if lower_order_final:
order = i + 1 if i + 1 < max_order else min(max_order, num_steps - (i + 1))
else:
order = min(max_order, i + 1)
x_next = dpm_pp_update(x_cur, buffer_model, buffer_t, t_next, order, predict_x0=predict_x0)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_eps:
inters_eps.append(d_cur.unsqueeze(0))
if len(buffer_model) >= 3:
buffer_model = [a.detach() for a in buffer_model[-3:]]
buffer_t = [a.detach() for a in buffer_t[-3:]]
else:
buffer_model = [a.detach() for a in buffer_model]
buffer_t = [a.detach() for a in buffer_t]
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
if return_eps:
return torch.cat(inters, dim=0).to(latents.device), torch.cat(inters_eps, dim=0).to(latents.device)
return torch.cat(inters, dim=0).to(latents.device)
return x_next
#----------------------------------------------------------------------------
@torch.no_grad()
def unipc_sampler(
net,
latents,
class_labels=None,
condition=None,
unconditional_condition=None,
num_steps=None,
sigma_min=0.002,
sigma_max=80,
schedule_type='polynomial',
schedule_rho=7,
afs=False,
denoise_to_zero=False,
return_inters=False,
return_eps=False,
max_order=3,
predict_x0=True,
lower_order_final=True,
variant='bh2',
t_steps=None,
**kwargs
):
"""
UniPC sampler: https://arxiv.org/abs/2302.04867.
Args:
net: A wrapped diffusion model.
latents: A pytorch tensor. Input sample at time `sigma_max`.
class_labels: A pytorch tensor. The condition for conditional sampling or guided sampling.
condition: A pytorch tensor. The condition to the model used in LDM and Stable Diffusion
unconditional_condition: A pytorch tensor. The unconditional condition to the model used in LDM and Stable Diffusion
num_steps: A `int`. The total number of the time steps with `num_steps-1` spacings.
sigma_min: A `float`. The ending sigma during samping.
sigma_max: A `float`. The starting sigma during sampling.
schedule_type: A `str`. The type of time schedule. We support three types:
- 'polynomial': polynomial time schedule. (Recommended in EDM.)
- 'logsnr': uniform logSNR time schedule. (Recommended in DPM-Solver for small-resolution datasets.)
- 'time_uniform': uniform time schedule. (Recommended in DPM-Solver for high-resolution datasets.)
- 'discrete': time schedule used in LDM. (Recommended when using pre-trained diffusion models from the LDM and Stable Diffusion codebases.)
schedule_rho: A `float`. Time step exponent. Need to be specified when schedule_type in ['polynomial', 'time_uniform'].
afs: A `bool`. Whether to use analytical first step (AFS) at the beginning of sampling.
denoise_to_zero: A `bool`. Whether to denoise the sample to from `sigma_min` to `0` at the end of sampling.
return_inters: A `bool`. Whether to save intermediate results, i.e. the whole sampling trajectory.
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 3
predict_x0: A `bool`. Whether to use the data prediction formulation.
lower_order_final: A `bool`. Whether to lower the order at the final stages of sampling.
variant: A `str`. Select between 'bh1' and 'bh2'. Type of the UniPC sampler.
Returns:
A pytorch tensor. The sample at time `sigma_min` or the whole sampling trajectory if return_inters=True.
"""
assert max_order > 0 and max_order < 4
max_order = max_order
if t_steps is None:
# Time step discretization.
t_steps = get_schedule(num_steps, sigma_min, sigma_max, device=latents.device, schedule_type=schedule_type, schedule_rho=schedule_rho, net=net)
# Main sampling loop.
x_next = latents * t_steps[0]
inters = [x_next.unsqueeze(0)]
if afs:
d_next = x_next / ((1 + t_steps[0]**2).sqrt())
denoised = x_next - t_steps[0] * d_next
else:
denoised = get_denoised(net, x_next, t_steps[0], class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
d_next = (x_next - denoised) / t_steps[0]
buffer_model = [dynamic_thresholding_fn(denoised)] if predict_x0 else [d_next]
buffer_t = [t_steps[0]]
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
x_cur = x_next
if i + 1 < max_order:
order = i + 1
use_corrector = True
x_next, model_out = unipc_update(x_cur, buffer_model, buffer_t, t_next, order, \
net=net, class_labels=class_labels, use_corrector=use_corrector, \
predict_x0=predict_x0, variant=variant)
buffer_model.append(model_out)
buffer_t.append(t_next)
else:
order = min(max_order, num_steps - i - 1) if lower_order_final else max_order
use_corrector = False if i == num_steps - 2 else True
x_next, model_out = unipc_update(x_cur, buffer_model, buffer_t, t_next, order, \
net=net, class_labels=class_labels, use_corrector=use_corrector, \
predict_x0=predict_x0, variant=variant)
for k in range(max_order - 1):
buffer_model[k] = buffer_model[k + 1]
buffer_t[k] = buffer_t[k + 1]
buffer_t[-1] = t_next
if i < num_steps - 2:
buffer_model[-1] = model_out
if return_inters:
inters.append(x_next.unsqueeze(0))
if denoise_to_zero:
x_next = get_denoised(net, x_next, t_next, class_labels=class_labels, condition=condition, unconditional_condition=unconditional_condition)
if return_inters:
inters.append(x_next.unsqueeze(0))
if return_inters:
return torch.cat(inters, dim=0).to(latents.device)
return x_next