lunarring commited on
Commit
1d2444d
1 Parent(s): 4e9849e

copied dependencies

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. configs/v1-inference.yaml +70 -0
  2. configs/v2-inference-v.yaml +68 -0
  3. configs/v2-inference.yaml +67 -0
  4. configs/v2-inpainting-inference.yaml +158 -0
  5. configs/v2-midas-inference.yaml +74 -0
  6. configs/x4-upscaling.yaml +76 -0
  7. latent_blending.py +1250 -0
  8. ldm/__pycache__/util.cpython-310.pyc +0 -0
  9. ldm/__pycache__/util.cpython-38.pyc +0 -0
  10. ldm/__pycache__/util.cpython-39.pyc +0 -0
  11. ldm/data/__init__.py +0 -0
  12. ldm/data/util.py +24 -0
  13. ldm/ldm +1 -0
  14. ldm/models/__pycache__/autoencoder.cpython-310.pyc +0 -0
  15. ldm/models/__pycache__/autoencoder.cpython-38.pyc +0 -0
  16. ldm/models/__pycache__/autoencoder.cpython-39.pyc +0 -0
  17. ldm/models/autoencoder.py +219 -0
  18. ldm/models/diffusion/__init__.py +0 -0
  19. ldm/models/diffusion/__pycache__/__init__.cpython-310.pyc +0 -0
  20. ldm/models/diffusion/__pycache__/__init__.cpython-38.pyc +0 -0
  21. ldm/models/diffusion/__pycache__/__init__.cpython-39.pyc +0 -0
  22. ldm/models/diffusion/__pycache__/ddim.cpython-310.pyc +0 -0
  23. ldm/models/diffusion/__pycache__/ddim.cpython-38.pyc +0 -0
  24. ldm/models/diffusion/__pycache__/ddim.cpython-39.pyc +0 -0
  25. ldm/models/diffusion/__pycache__/ddpm.cpython-310.pyc +0 -0
  26. ldm/models/diffusion/__pycache__/ddpm.cpython-38.pyc +0 -0
  27. ldm/models/diffusion/__pycache__/ddpm.cpython-39.pyc +0 -0
  28. ldm/models/diffusion/__pycache__/plms.cpython-39.pyc +0 -0
  29. ldm/models/diffusion/__pycache__/sampling_util.cpython-39.pyc +0 -0
  30. ldm/models/diffusion/ddim.py +336 -0
  31. ldm/models/diffusion/ddpm.py +1795 -0
  32. ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  33. ldm/models/diffusion/dpm_solver/__pycache__/__init__.cpython-39.pyc +0 -0
  34. ldm/models/diffusion/dpm_solver/__pycache__/dpm_solver.cpython-39.pyc +0 -0
  35. ldm/models/diffusion/dpm_solver/__pycache__/sampler.cpython-39.pyc +0 -0
  36. ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
  37. ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  38. ldm/models/diffusion/plms.py +244 -0
  39. ldm/models/diffusion/sampling_util.py +22 -0
  40. ldm/modules/__pycache__/attention.cpython-310.pyc +0 -0
  41. ldm/modules/__pycache__/attention.cpython-38.pyc +0 -0
  42. ldm/modules/__pycache__/attention.cpython-39.pyc +0 -0
  43. ldm/modules/__pycache__/ema.cpython-310.pyc +0 -0
  44. ldm/modules/__pycache__/ema.cpython-38.pyc +0 -0
  45. ldm/modules/__pycache__/ema.cpython-39.pyc +0 -0
  46. ldm/modules/attention.py +341 -0
  47. ldm/modules/diffusionmodules/__init__.py +0 -0
  48. ldm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pyc +0 -0
  49. ldm/modules/diffusionmodules/__pycache__/__init__.cpython-38.pyc +0 -0
  50. ldm/modules/diffusionmodules/__pycache__/__init__.cpython-39.pyc +0 -0
configs/v1-inference.yaml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32 # unused
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 320
36
+ attention_resolutions: [ 4, 2, 1 ]
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1, 2, 4, 4 ]
39
+ num_heads: 8
40
+ use_spatial_transformer: True
41
+ transformer_depth: 1
42
+ context_dim: 768
43
+ use_checkpoint: True
44
+ legacy: False
45
+
46
+ first_stage_config:
47
+ target: ldm.models.autoencoder.AutoencoderKL
48
+ params:
49
+ embed_dim: 4
50
+ monitor: val/rec_loss
51
+ ddconfig:
52
+ double_z: true
53
+ z_channels: 4
54
+ resolution: 256
55
+ in_channels: 3
56
+ out_ch: 3
57
+ ch: 128
58
+ ch_mult:
59
+ - 1
60
+ - 2
61
+ - 4
62
+ - 4
63
+ num_res_blocks: 2
64
+ attn_resolutions: []
65
+ dropout: 0.0
66
+ lossconfig:
67
+ target: torch.nn.Identity
68
+
69
+ cond_stage_config:
70
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
configs/v2-inference-v.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-4
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ parameterization: "v"
6
+ linear_start: 0.00085
7
+ linear_end: 0.0120
8
+ num_timesteps_cond: 1
9
+ log_every_t: 200
10
+ timesteps: 1000
11
+ first_stage_key: "jpg"
12
+ cond_stage_key: "txt"
13
+ image_size: 64
14
+ channels: 4
15
+ cond_stage_trainable: false
16
+ conditioning_key: crossattn
17
+ monitor: val/loss_simple_ema
18
+ scale_factor: 0.18215
19
+ use_ema: False # we set this to false because this is an inference only config
20
+
21
+ unet_config:
22
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
23
+ params:
24
+ use_checkpoint: True
25
+ use_fp16: True
26
+ image_size: 32 # unused
27
+ in_channels: 4
28
+ out_channels: 4
29
+ model_channels: 320
30
+ attention_resolutions: [ 4, 2, 1 ]
31
+ num_res_blocks: 2
32
+ channel_mult: [ 1, 2, 4, 4 ]
33
+ num_head_channels: 64 # need to fix for flash-attn
34
+ use_spatial_transformer: True
35
+ use_linear_in_transformer: True
36
+ transformer_depth: 1
37
+ context_dim: 1024
38
+ legacy: False
39
+
40
+ first_stage_config:
41
+ target: ldm.models.autoencoder.AutoencoderKL
42
+ params:
43
+ embed_dim: 4
44
+ monitor: val/rec_loss
45
+ ddconfig:
46
+ #attn_type: "vanilla-xformers"
47
+ double_z: true
48
+ z_channels: 4
49
+ resolution: 256
50
+ in_channels: 3
51
+ out_ch: 3
52
+ ch: 128
53
+ ch_mult:
54
+ - 1
55
+ - 2
56
+ - 4
57
+ - 4
58
+ num_res_blocks: 2
59
+ attn_resolutions: []
60
+ dropout: 0.0
61
+ lossconfig:
62
+ target: torch.nn.Identity
63
+
64
+ cond_stage_config:
65
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
66
+ params:
67
+ freeze: True
68
+ layer: "penultimate"
configs/v2-inference.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-4
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False # we set this to false because this is an inference only config
19
+
20
+ unet_config:
21
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
22
+ params:
23
+ use_checkpoint: True
24
+ use_fp16: True
25
+ image_size: 32 # unused
26
+ in_channels: 4
27
+ out_channels: 4
28
+ model_channels: 320
29
+ attention_resolutions: [ 4, 2, 1 ]
30
+ num_res_blocks: 2
31
+ channel_mult: [ 1, 2, 4, 4 ]
32
+ num_head_channels: 64 # need to fix for flash-attn
33
+ use_spatial_transformer: True
34
+ use_linear_in_transformer: True
35
+ transformer_depth: 1
36
+ context_dim: 1024
37
+ legacy: False
38
+
39
+ first_stage_config:
40
+ target: ldm.models.autoencoder.AutoencoderKL
41
+ params:
42
+ embed_dim: 4
43
+ monitor: val/rec_loss
44
+ ddconfig:
45
+ #attn_type: "vanilla-xformers"
46
+ double_z: true
47
+ z_channels: 4
48
+ resolution: 256
49
+ in_channels: 3
50
+ out_ch: 3
51
+ ch: 128
52
+ ch_mult:
53
+ - 1
54
+ - 2
55
+ - 4
56
+ - 4
57
+ num_res_blocks: 2
58
+ attn_resolutions: []
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config:
64
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
65
+ params:
66
+ freeze: True
67
+ layer: "penultimate"
configs/v2-inpainting-inference.yaml ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 5.0e-05
3
+ target: ldm.models.diffusion.ddpm.LatentInpaintDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: hybrid
16
+ scale_factor: 0.18215
17
+ monitor: val/loss_simple_ema
18
+ finetune_keys: null
19
+ use_ema: False
20
+
21
+ unet_config:
22
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
23
+ params:
24
+ use_checkpoint: True
25
+ image_size: 32 # unused
26
+ in_channels: 9
27
+ out_channels: 4
28
+ model_channels: 320
29
+ attention_resolutions: [ 4, 2, 1 ]
30
+ num_res_blocks: 2
31
+ channel_mult: [ 1, 2, 4, 4 ]
32
+ num_head_channels: 64 # need to fix for flash-attn
33
+ use_spatial_transformer: True
34
+ use_linear_in_transformer: True
35
+ transformer_depth: 1
36
+ context_dim: 1024
37
+ legacy: False
38
+
39
+ first_stage_config:
40
+ target: ldm.models.autoencoder.AutoencoderKL
41
+ params:
42
+ embed_dim: 4
43
+ monitor: val/rec_loss
44
+ ddconfig:
45
+ #attn_type: "vanilla-xformers"
46
+ double_z: true
47
+ z_channels: 4
48
+ resolution: 256
49
+ in_channels: 3
50
+ out_ch: 3
51
+ ch: 128
52
+ ch_mult:
53
+ - 1
54
+ - 2
55
+ - 4
56
+ - 4
57
+ num_res_blocks: 2
58
+ attn_resolutions: [ ]
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config:
64
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
65
+ params:
66
+ freeze: True
67
+ layer: "penultimate"
68
+
69
+
70
+ data:
71
+ target: ldm.data.laion.WebDataModuleFromConfig
72
+ params:
73
+ tar_base: null # for concat as in LAION-A
74
+ p_unsafe_threshold: 0.1
75
+ filter_word_list: "data/filters.yaml"
76
+ max_pwatermark: 0.45
77
+ batch_size: 8
78
+ num_workers: 6
79
+ multinode: True
80
+ min_size: 512
81
+ train:
82
+ shards:
83
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-0/{00000..18699}.tar -"
84
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-1/{00000..18699}.tar -"
85
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-2/{00000..18699}.tar -"
86
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-3/{00000..18699}.tar -"
87
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-4/{00000..18699}.tar -" #{00000-94333}.tar"
88
+ shuffle: 10000
89
+ image_key: jpg
90
+ image_transforms:
91
+ - target: torchvision.transforms.Resize
92
+ params:
93
+ size: 512
94
+ interpolation: 3
95
+ - target: torchvision.transforms.RandomCrop
96
+ params:
97
+ size: 512
98
+ postprocess:
99
+ target: ldm.data.laion.AddMask
100
+ params:
101
+ mode: "512train-large"
102
+ p_drop: 0.25
103
+ # NOTE use enough shards to avoid empty validation loops in workers
104
+ validation:
105
+ shards:
106
+ - "pipe:aws s3 cp s3://deep-floyd-s3/datasets/laion_cleaned-part5/{93001..94333}.tar - "
107
+ shuffle: 0
108
+ image_key: jpg
109
+ image_transforms:
110
+ - target: torchvision.transforms.Resize
111
+ params:
112
+ size: 512
113
+ interpolation: 3
114
+ - target: torchvision.transforms.CenterCrop
115
+ params:
116
+ size: 512
117
+ postprocess:
118
+ target: ldm.data.laion.AddMask
119
+ params:
120
+ mode: "512train-large"
121
+ p_drop: 0.25
122
+
123
+ lightning:
124
+ find_unused_parameters: True
125
+ modelcheckpoint:
126
+ params:
127
+ every_n_train_steps: 5000
128
+
129
+ callbacks:
130
+ metrics_over_trainsteps_checkpoint:
131
+ params:
132
+ every_n_train_steps: 10000
133
+
134
+ image_logger:
135
+ target: main.ImageLogger
136
+ params:
137
+ enable_autocast: False
138
+ disabled: False
139
+ batch_frequency: 1000
140
+ max_images: 4
141
+ increase_log_steps: False
142
+ log_first_step: False
143
+ log_images_kwargs:
144
+ use_ema_scope: False
145
+ inpaint: False
146
+ plot_progressive_rows: False
147
+ plot_diffusion_rows: False
148
+ N: 4
149
+ unconditional_guidance_scale: 5.0
150
+ unconditional_guidance_label: [""]
151
+ ddim_steps: 50 # todo check these out for depth2img,
152
+ ddim_eta: 0.0 # todo check these out for depth2img,
153
+
154
+ trainer:
155
+ benchmark: True
156
+ val_check_interval: 5000000
157
+ num_sanity_val_steps: 0
158
+ accumulate_grad_batches: 1
configs/v2-midas-inference.yaml ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 5.0e-07
3
+ target: ldm.models.diffusion.ddpm.LatentDepth2ImageDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: hybrid
16
+ scale_factor: 0.18215
17
+ monitor: val/loss_simple_ema
18
+ finetune_keys: null
19
+ use_ema: False
20
+
21
+ depth_stage_config:
22
+ target: ldm.modules.midas.api.MiDaSInference
23
+ params:
24
+ model_type: "dpt_hybrid"
25
+
26
+ unet_config:
27
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
28
+ params:
29
+ use_checkpoint: True
30
+ image_size: 32 # unused
31
+ in_channels: 5
32
+ out_channels: 4
33
+ model_channels: 320
34
+ attention_resolutions: [ 4, 2, 1 ]
35
+ num_res_blocks: 2
36
+ channel_mult: [ 1, 2, 4, 4 ]
37
+ num_head_channels: 64 # need to fix for flash-attn
38
+ use_spatial_transformer: True
39
+ use_linear_in_transformer: True
40
+ transformer_depth: 1
41
+ context_dim: 1024
42
+ legacy: False
43
+
44
+ first_stage_config:
45
+ target: ldm.models.autoencoder.AutoencoderKL
46
+ params:
47
+ embed_dim: 4
48
+ monitor: val/rec_loss
49
+ ddconfig:
50
+ #attn_type: "vanilla-xformers"
51
+ double_z: true
52
+ z_channels: 4
53
+ resolution: 256
54
+ in_channels: 3
55
+ out_ch: 3
56
+ ch: 128
57
+ ch_mult:
58
+ - 1
59
+ - 2
60
+ - 4
61
+ - 4
62
+ num_res_blocks: 2
63
+ attn_resolutions: [ ]
64
+ dropout: 0.0
65
+ lossconfig:
66
+ target: torch.nn.Identity
67
+
68
+ cond_stage_config:
69
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
70
+ params:
71
+ freeze: True
72
+ layer: "penultimate"
73
+
74
+
configs/x4-upscaling.yaml ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentUpscaleDiffusion
4
+ params:
5
+ parameterization: "v"
6
+ low_scale_key: "lr"
7
+ linear_start: 0.0001
8
+ linear_end: 0.02
9
+ num_timesteps_cond: 1
10
+ log_every_t: 200
11
+ timesteps: 1000
12
+ first_stage_key: "jpg"
13
+ cond_stage_key: "txt"
14
+ image_size: 128
15
+ channels: 4
16
+ cond_stage_trainable: false
17
+ conditioning_key: "hybrid-adm"
18
+ monitor: val/loss_simple_ema
19
+ scale_factor: 0.08333
20
+ use_ema: False
21
+
22
+ low_scale_config:
23
+ target: ldm.modules.diffusionmodules.upscaling.ImageConcatWithNoiseAugmentation
24
+ params:
25
+ noise_schedule_config: # image space
26
+ linear_start: 0.0001
27
+ linear_end: 0.02
28
+ max_noise_level: 350
29
+
30
+ unet_config:
31
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
32
+ params:
33
+ use_checkpoint: True
34
+ num_classes: 1000 # timesteps for noise conditioning (here constant, just need one)
35
+ image_size: 128
36
+ in_channels: 7
37
+ out_channels: 4
38
+ model_channels: 256
39
+ attention_resolutions: [ 2,4,8]
40
+ num_res_blocks: 2
41
+ channel_mult: [ 1, 2, 2, 4]
42
+ disable_self_attentions: [True, True, True, False]
43
+ disable_middle_self_attn: False
44
+ num_heads: 8
45
+ use_spatial_transformer: True
46
+ transformer_depth: 1
47
+ context_dim: 1024
48
+ legacy: False
49
+ use_linear_in_transformer: True
50
+
51
+ first_stage_config:
52
+ target: ldm.models.autoencoder.AutoencoderKL
53
+ params:
54
+ embed_dim: 4
55
+ ddconfig:
56
+ # attn_type: "vanilla-xformers" this model needs efficient attention to be feasible on HR data, also the decoder seems to break in half precision (UNet is fine though)
57
+ double_z: True
58
+ z_channels: 4
59
+ resolution: 256
60
+ in_channels: 3
61
+ out_ch: 3
62
+ ch: 128
63
+ ch_mult: [ 1,2,4 ] # num_down = len(ch_mult)-1
64
+ num_res_blocks: 2
65
+ attn_resolutions: [ ]
66
+ dropout: 0.0
67
+
68
+ lossconfig:
69
+ target: torch.nn.Identity
70
+
71
+ cond_stage_config:
72
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
73
+ params:
74
+ freeze: True
75
+ layer: "penultimate"
76
+
latent_blending.py ADDED
@@ -0,0 +1,1250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Lunar Ring. All rights reserved.
2
+ # Written by Johannes Stelzer, email stelzer@lunar-ring.ai twitter @j_stelzer
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os, sys
17
+ dp_git = "/home/lugo/git/"
18
+ sys.path.append('util')
19
+ # sys.path.append('../stablediffusion/ldm')
20
+ import torch
21
+ torch.backends.cudnn.benchmark = False
22
+ import numpy as np
23
+ import warnings
24
+ warnings.filterwarnings('ignore')
25
+ import time
26
+ import subprocess
27
+ import warnings
28
+ import torch
29
+ from tqdm.auto import tqdm
30
+ from PIL import Image
31
+ # import matplotlib.pyplot as plt
32
+ import torch
33
+ from movie_util import MovieSaver
34
+ import datetime
35
+ from typing import Callable, List, Optional, Union
36
+ import inspect
37
+ from threading import Thread
38
+ torch.set_grad_enabled(False)
39
+ from omegaconf import OmegaConf
40
+ from torch import autocast
41
+ from contextlib import nullcontext
42
+
43
+ from ldm.models.diffusion.ddim import DDIMSampler
44
+ from ldm.util import instantiate_from_config
45
+ from ldm.models.diffusion.ddpm import LatentUpscaleDiffusion, LatentInpaintDiffusion
46
+ from stable_diffusion_holder import StableDiffusionHolder
47
+ import yaml
48
+ import lpips
49
+ #%%
50
+ class LatentBlending():
51
+ def __init__(
52
+ self,
53
+ sdh: None,
54
+ guidance_scale: float = 4,
55
+ guidance_scale_mid_damper: float = 0.5,
56
+ mid_compression_scaler: float = 1.2,
57
+ ):
58
+ r"""
59
+ Initializes the latent blending class.
60
+ Args:
61
+ guidance_scale: float
62
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
63
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
64
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
65
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
66
+ usually at the expense of lower image quality.
67
+ guidance_scale_mid_damper: float = 0.5
68
+ Reduces the guidance scale towards the middle of the transition.
69
+ A value of 0.5 would decrease the guidance_scale towards the middle linearly by 0.5.
70
+ mid_compression_scaler: float = 2.0
71
+ Increases the sampling density in the middle (where most changes happen). Higher value
72
+ imply more values in the middle. However the inflection point can occur outside the middle,
73
+ thus high values can give rough transitions. Values around 2 should be fine.
74
+
75
+ """
76
+ assert guidance_scale_mid_damper>0 and guidance_scale_mid_damper<=1.0, f"guidance_scale_mid_damper neees to be in interval (0,1], you provided {guidance_scale_mid_damper}"
77
+
78
+ self.sdh = sdh
79
+ self.device = self.sdh.device
80
+ self.width = self.sdh.width
81
+ self.height = self.sdh.height
82
+ self.guidance_scale_mid_damper = guidance_scale_mid_damper
83
+ self.mid_compression_scaler = mid_compression_scaler
84
+ self.seed1 = 0
85
+ self.seed2 = 0
86
+
87
+ # Initialize vars
88
+ self.prompt1 = ""
89
+ self.prompt2 = ""
90
+ self.negative_prompt = ""
91
+
92
+ self.tree_latents = [None, None]
93
+ self.tree_fracts = None
94
+ self.idx_injection = []
95
+ self.tree_status = None
96
+ self.tree_final_imgs = []
97
+
98
+ self.list_nmb_branches_prev = []
99
+ self.list_injection_idx_prev = []
100
+ self.text_embedding1 = None
101
+ self.text_embedding2 = None
102
+ self.image1_lowres = None
103
+ self.image2_lowres = None
104
+ self.negative_prompt = None
105
+ self.num_inference_steps = self.sdh.num_inference_steps
106
+ self.noise_level_upscaling = 20
107
+ self.list_injection_idx = None
108
+ self.list_nmb_branches = None
109
+
110
+ # Mixing parameters
111
+ self.branch1_crossfeed_power = 0.1
112
+ self.branch1_crossfeed_range = 0.6
113
+ self.branch1_crossfeed_decay = 0.8
114
+
115
+ self.parental_crossfeed_power = 0.1
116
+ self.parental_crossfeed_range = 0.8
117
+ self.parental_crossfeed_power_decay = 0.8
118
+
119
+ self.set_guidance_scale(guidance_scale)
120
+ self.init_mode()
121
+ self.multi_transition_img_first = None
122
+ self.multi_transition_img_last = None
123
+ self.dt_per_diff = 0
124
+ self.spatial_mask = None
125
+
126
+ self.lpips = lpips.LPIPS(net='alex').cuda(self.device)
127
+
128
+
129
+ def init_mode(self):
130
+ r"""
131
+ Sets the operational mode. Currently supported are standard, inpainting and x4 upscaling.
132
+ """
133
+ if isinstance(self.sdh.model, LatentUpscaleDiffusion):
134
+ self.mode = 'upscale'
135
+ elif isinstance(self.sdh.model, LatentInpaintDiffusion):
136
+ self.sdh.image_source = None
137
+ self.sdh.mask_image = None
138
+ self.mode = 'inpaint'
139
+ else:
140
+ self.mode = 'standard'
141
+
142
+ def set_guidance_scale(self, guidance_scale):
143
+ r"""
144
+ sets the guidance scale.
145
+ """
146
+ self.guidance_scale_base = guidance_scale
147
+ self.guidance_scale = guidance_scale
148
+ self.sdh.guidance_scale = guidance_scale
149
+
150
+ def set_negative_prompt(self, negative_prompt):
151
+ r"""Set the negative prompt. Currenty only one negative prompt is supported
152
+ """
153
+ self.negative_prompt = negative_prompt
154
+ self.sdh.set_negative_prompt(negative_prompt)
155
+
156
+ def set_guidance_mid_dampening(self, fract_mixing):
157
+ r"""
158
+ Tunes the guidance scale down as a linear function of fract_mixing,
159
+ towards 0.5 the minimum will be reached.
160
+ """
161
+ mid_factor = 1 - np.abs(fract_mixing - 0.5)/ 0.5
162
+ max_guidance_reduction = self.guidance_scale_base * (1-self.guidance_scale_mid_damper) - 1
163
+ guidance_scale_effective = self.guidance_scale_base - max_guidance_reduction*mid_factor
164
+ self.guidance_scale = guidance_scale_effective
165
+ self.sdh.guidance_scale = guidance_scale_effective
166
+
167
+
168
+ def set_branch1_crossfeed(self, crossfeed_power, crossfeed_range, crossfeed_decay):
169
+ r"""
170
+ Sets the crossfeed parameters for the first branch to the last branch.
171
+ Args:
172
+ crossfeed_power: float [0,1]
173
+ Controls the level of cross-feeding between the first and last image branch.
174
+ crossfeed_range: float [0,1]
175
+ Sets the duration of active crossfeed during development.
176
+ crossfeed_decay: float [0,1]
177
+ Sets decay for branch1_crossfeed_power. Lower values make the decay stronger across the range.
178
+ """
179
+ self.branch1_crossfeed_power = np.clip(crossfeed_power, 0, 1)
180
+ self.branch1_crossfeed_range = np.clip(crossfeed_range, 0, 1)
181
+ self.branch1_crossfeed_decay = np.clip(crossfeed_decay, 0, 1)
182
+
183
+
184
+ def set_parental_crossfeed(self, crossfeed_power, crossfeed_range, crossfeed_decay):
185
+ r"""
186
+ Sets the crossfeed parameters for all transition images (within the first and last branch).
187
+ Args:
188
+ crossfeed_power: float [0,1]
189
+ Controls the level of cross-feeding from the parental branches
190
+ crossfeed_range: float [0,1]
191
+ Sets the duration of active crossfeed during development.
192
+ crossfeed_decay: float [0,1]
193
+ Sets decay for branch1_crossfeed_power. Lower values make the decay stronger across the range.
194
+ """
195
+ self.parental_crossfeed_power = np.clip(crossfeed_power, 0, 1)
196
+ self.parental_crossfeed_range = np.clip(crossfeed_range, 0, 1)
197
+ self.parental_crossfeed_power_decay = np.clip(crossfeed_decay, 0, 1)
198
+
199
+
200
+ def set_prompt1(self, prompt: str):
201
+ r"""
202
+ Sets the first prompt (for the first keyframe) including text embeddings.
203
+ Args:
204
+ prompt: str
205
+ ABC trending on artstation painted by Greg Rutkowski
206
+ """
207
+ prompt = prompt.replace("_", " ")
208
+ self.prompt1 = prompt
209
+ self.text_embedding1 = self.get_text_embeddings(self.prompt1)
210
+
211
+
212
+ def set_prompt2(self, prompt: str):
213
+ r"""
214
+ Sets the second prompt (for the second keyframe) including text embeddings.
215
+ Args:
216
+ prompt: str
217
+ XYZ trending on artstation painted by Greg Rutkowski
218
+ """
219
+ prompt = prompt.replace("_", " ")
220
+ self.prompt2 = prompt
221
+ self.text_embedding2 = self.get_text_embeddings(self.prompt2)
222
+
223
+ def set_image1(self, image: Image):
224
+ r"""
225
+ Sets the first image (keyframe), relevant for the upscaling model transitions.
226
+ Args:
227
+ image: Image
228
+ """
229
+ self.image1_lowres = image
230
+
231
+ def set_image2(self, image: Image):
232
+ r"""
233
+ Sets the second image (keyframe), relevant for the upscaling model transitions.
234
+ Args:
235
+ image: Image
236
+ """
237
+ self.image2_lowres = image
238
+
239
+ def run_transition(
240
+ self,
241
+ recycle_img1: Optional[bool] = False,
242
+ recycle_img2: Optional[bool] = False,
243
+ num_inference_steps: Optional[int] = 30,
244
+ depth_strength: Optional[float] = 0.3,
245
+ t_compute_max_allowed: Optional[float] = None,
246
+ nmb_max_branches: Optional[int] = None,
247
+ fixed_seeds: Optional[List[int]] = None,
248
+ ):
249
+ r"""
250
+ Function for computing transitions.
251
+ Returns a list of transition images using spherical latent blending.
252
+ Args:
253
+ recycle_img1: Optional[bool]:
254
+ Don't recompute the latents for the first keyframe (purely prompt1). Saves compute.
255
+ recycle_img2: Optional[bool]:
256
+ Don't recompute the latents for the second keyframe (purely prompt2). Saves compute.
257
+ num_inference_steps:
258
+ Number of diffusion steps. Higher values will take more compute time.
259
+ depth_strength:
260
+ Determines how deep the first injection will happen.
261
+ Deeper injections will cause (unwanted) formation of new structures,
262
+ more shallow values will go into alpha-blendy land.
263
+ t_compute_max_allowed:
264
+ Either provide t_compute_max_allowed or nmb_max_branches.
265
+ The maximum time allowed for computation. Higher values give better results but take longer.
266
+ nmb_max_branches: int
267
+ Either provide t_compute_max_allowed or nmb_max_branches. The maximum number of branches to be computed. Higher values give better
268
+ results. Use this if you want to have controllable results independent
269
+ of your computer.
270
+ fixed_seeds: Optional[List[int)]:
271
+ You can supply two seeds that are used for the first and second keyframe (prompt1 and prompt2).
272
+ Otherwise random seeds will be taken.
273
+
274
+ """
275
+
276
+ # Sanity checks first
277
+ assert self.text_embedding1 is not None, 'Set the first text embedding with .set_prompt1(...) before'
278
+ assert self.text_embedding2 is not None, 'Set the second text embedding with .set_prompt2(...) before'
279
+
280
+ # Random seeds
281
+ if fixed_seeds is not None:
282
+ if fixed_seeds == 'randomize':
283
+ fixed_seeds = list(np.random.randint(0, 1000000, 2).astype(np.int32))
284
+ else:
285
+ assert len(fixed_seeds)==2, "Supply a list with len = 2"
286
+
287
+ self.seed1 = fixed_seeds[0]
288
+ self.seed2 = fixed_seeds[1]
289
+
290
+ # Ensure correct num_inference_steps in holder
291
+ self.num_inference_steps = num_inference_steps
292
+ self.sdh.num_inference_steps = num_inference_steps
293
+
294
+ # Compute / Recycle first image
295
+ if not recycle_img1 or len(self.tree_latents[0]) != self.num_inference_steps:
296
+ list_latents1 = self.compute_latents1()
297
+ else:
298
+ list_latents1 = self.tree_latents[0]
299
+
300
+ # Compute / Recycle first image
301
+ if not recycle_img2 or len(self.tree_latents[-1]) != self.num_inference_steps:
302
+ list_latents2 = self.compute_latents2()
303
+ else:
304
+ list_latents2 = self.tree_latents[-1]
305
+
306
+ # Reset the tree, injecting the edge latents1/2 we just generated/recycled
307
+ self.tree_latents = [list_latents1, list_latents2]
308
+ self.tree_fracts = [0.0, 1.0]
309
+ self.tree_final_imgs = [self.sdh.latent2image((self.tree_latents[0][-1])), self.sdh.latent2image((self.tree_latents[-1][-1]))]
310
+ self.tree_idx_injection = [0, 0]
311
+
312
+ # Hard-fix. Apply spatial mask only for list_latents2 but not for transition. WIP...
313
+ self.spatial_mask = None
314
+
315
+ # Set up branching scheme (dependent on provided compute time)
316
+ list_idx_injection, list_nmb_stems = self.get_time_based_branching(depth_strength, t_compute_max_allowed, nmb_max_branches)
317
+
318
+ # Run iteratively, starting with the longest trajectory.
319
+ # Always inserting new branches where they are needed most according to image similarity
320
+ for s_idx in tqdm(range(len(list_idx_injection))):
321
+ nmb_stems = list_nmb_stems[s_idx]
322
+ idx_injection = list_idx_injection[s_idx]
323
+
324
+ for i in range(nmb_stems):
325
+ fract_mixing, b_parent1, b_parent2 = self.get_mixing_parameters(idx_injection)
326
+ self.set_guidance_mid_dampening(fract_mixing)
327
+ list_latents = self.compute_latents_mix(fract_mixing, b_parent1, b_parent2, idx_injection)
328
+ self.insert_into_tree(fract_mixing, idx_injection, list_latents)
329
+ # print(f"fract_mixing: {fract_mixing} idx_injection {idx_injection}")
330
+
331
+ return self.tree_final_imgs
332
+
333
+
334
+ def compute_latents1(self, return_image=False):
335
+ r"""
336
+ Runs a diffusion trajectory for the first image
337
+ Args:
338
+ return_image: bool
339
+ whether to return an image or the list of latents
340
+ """
341
+ print("starting compute_latents1")
342
+ list_conditionings = self.get_mixed_conditioning(0)
343
+ t0 = time.time()
344
+ latents_start = self.get_noise(self.seed1)
345
+ list_latents1 = self.run_diffusion(
346
+ list_conditionings,
347
+ latents_start = latents_start,
348
+ idx_start = 0
349
+ )
350
+ t1 = time.time()
351
+ self.dt_per_diff = (t1-t0) / self.num_inference_steps
352
+ self.tree_latents[0] = list_latents1
353
+ if return_image:
354
+ return self.sdh.latent2image(list_latents1[-1])
355
+ else:
356
+ return list_latents1
357
+
358
+ def compute_latents2(self, return_image=False):
359
+ r"""
360
+ Runs a diffusion trajectory for the last image, which may be affected by the first image's trajectory.
361
+ Args:
362
+ return_image: bool
363
+ whether to return an image or the list of latents
364
+ """
365
+ print("starting compute_latents2")
366
+ list_conditionings = self.get_mixed_conditioning(1)
367
+ latents_start = self.get_noise(self.seed2)
368
+ # Influence from branch1
369
+ if self.branch1_crossfeed_power > 0.0:
370
+ # Set up the mixing_coeffs
371
+ idx_mixing_stop = int(round(self.num_inference_steps*self.branch1_crossfeed_range))
372
+ mixing_coeffs = list(np.linspace(self.branch1_crossfeed_power, self.branch1_crossfeed_power*self.branch1_crossfeed_decay, idx_mixing_stop))
373
+ mixing_coeffs.extend((self.num_inference_steps-idx_mixing_stop)*[0])
374
+ list_latents_mixing = self.tree_latents[0]
375
+ list_latents2 = self.run_diffusion(
376
+ list_conditionings,
377
+ latents_start = latents_start,
378
+ idx_start = 0,
379
+ list_latents_mixing = list_latents_mixing,
380
+ mixing_coeffs = mixing_coeffs
381
+ )
382
+ else:
383
+ list_latents2 = self.run_diffusion(list_conditionings, latents_start)
384
+ self.tree_latents[-1] = list_latents2
385
+
386
+ if return_image:
387
+ return self.sdh.latent2image(list_latents2[-1])
388
+ else:
389
+ return list_latents2
390
+
391
+
392
+ def compute_latents_mix(self, fract_mixing, b_parent1, b_parent2, idx_injection):
393
+ r"""
394
+ Runs a diffusion trajectory, using the latents from the respective parents
395
+ Args:
396
+ fract_mixing: float
397
+ the fraction along the transition axis [0, 1]
398
+ b_parent1: int
399
+ index of parent1 to be used
400
+ b_parent2: int
401
+ index of parent2 to be used
402
+ idx_injection: int
403
+ the index in terms of diffusion steps, where the next insertion will start.
404
+ """
405
+ list_conditionings = self.get_mixed_conditioning(fract_mixing)
406
+ fract_mixing_parental = (fract_mixing - self.tree_fracts[b_parent1]) / (self.tree_fracts[b_parent2] - self.tree_fracts[b_parent1])
407
+ # idx_reversed = self.num_inference_steps - idx_injection
408
+
409
+ list_latents_parental_mix = []
410
+ for i in range(self.num_inference_steps):
411
+ latents_p1 = self.tree_latents[b_parent1][i]
412
+ latents_p2 = self.tree_latents[b_parent2][i]
413
+ if latents_p1 is None or latents_p2 is None:
414
+ latents_parental = None
415
+ else:
416
+ latents_parental = interpolate_spherical(latents_p1, latents_p2, fract_mixing_parental)
417
+ list_latents_parental_mix.append(latents_parental)
418
+
419
+ idx_mixing_stop = int(round(self.num_inference_steps*self.parental_crossfeed_range))
420
+ mixing_coeffs = idx_injection*[self.parental_crossfeed_power]
421
+ nmb_mixing = idx_mixing_stop - idx_injection
422
+ if nmb_mixing > 0:
423
+ mixing_coeffs.extend(list(np.linspace(self.parental_crossfeed_power, self.parental_crossfeed_power*self.parental_crossfeed_power_decay, nmb_mixing)))
424
+ mixing_coeffs.extend((self.num_inference_steps-len(mixing_coeffs))*[0])
425
+
426
+ latents_start = list_latents_parental_mix[idx_injection-1]
427
+ list_latents = self.run_diffusion(
428
+ list_conditionings,
429
+ latents_start = latents_start,
430
+ idx_start = idx_injection,
431
+ list_latents_mixing = list_latents_parental_mix,
432
+ mixing_coeffs = mixing_coeffs
433
+ )
434
+
435
+ return list_latents
436
+
437
+ def get_time_based_branching(self, depth_strength, t_compute_max_allowed=None, nmb_max_branches=None):
438
+ r"""
439
+ Sets up the branching scheme dependent on the time that is granted for compute.
440
+ The scheme uses an estimation derived from the first image's computation speed.
441
+ Either provide t_compute_max_allowed or nmb_max_branches
442
+ Args:
443
+ depth_strength:
444
+ Determines how deep the first injection will happen.
445
+ Deeper injections will cause (unwanted) formation of new structures,
446
+ more shallow values will go into alpha-blendy land.
447
+ t_compute_max_allowed: float
448
+ The maximum time allowed for computation. Higher values give better results
449
+ but take longer. Use this if you want to fix your waiting time for the results.
450
+ nmb_max_branches: int
451
+ The maximum number of branches to be computed. Higher values give better
452
+ results. Use this if you want to have controllable results independent
453
+ of your computer.
454
+ """
455
+ idx_injection_base = int(round(self.num_inference_steps*depth_strength))
456
+ list_idx_injection = np.arange(idx_injection_base, self.num_inference_steps-1, 3)
457
+ list_nmb_stems = np.ones(len(list_idx_injection), dtype=np.int32)
458
+ t_compute = 0
459
+
460
+ if nmb_max_branches is None:
461
+ assert t_compute_max_allowed is not None, "Either specify t_compute_max_allowed or nmb_max_branches"
462
+ stop_criterion = "t_compute_max_allowed"
463
+ elif t_compute_max_allowed is None:
464
+ assert nmb_max_branches is not None, "Either specify t_compute_max_allowed or nmb_max_branches"
465
+ stop_criterion = "nmb_max_branches"
466
+ nmb_max_branches -= 2 # discounting the outer frames
467
+ else:
468
+ raise ValueError("Either specify t_compute_max_allowed or nmb_max_branches")
469
+
470
+ stop_criterion_reached = False
471
+ is_first_iteration = True
472
+
473
+ while not stop_criterion_reached:
474
+ list_compute_steps = self.num_inference_steps - list_idx_injection
475
+ list_compute_steps *= list_nmb_stems
476
+ t_compute = np.sum(list_compute_steps) * self.dt_per_diff + 0.15*np.sum(list_nmb_stems)
477
+ increase_done = False
478
+ for s_idx in range(len(list_nmb_stems)-1):
479
+ if list_nmb_stems[s_idx+1] / list_nmb_stems[s_idx] >= 2:
480
+ list_nmb_stems[s_idx] += 1
481
+ increase_done = True
482
+ break
483
+ if not increase_done:
484
+ list_nmb_stems[-1] += 1
485
+
486
+ if stop_criterion == "t_compute_max_allowed" and t_compute > t_compute_max_allowed:
487
+ stop_criterion_reached = True
488
+ elif stop_criterion == "nmb_max_branches" and np.sum(list_nmb_stems) >= nmb_max_branches:
489
+ stop_criterion_reached = True
490
+ if is_first_iteration:
491
+ # Need to undersample.
492
+ list_idx_injection = np.linspace(list_idx_injection[0], list_idx_injection[-1], nmb_max_branches).astype(np.int32)
493
+ list_nmb_stems = np.ones(len(list_idx_injection), dtype=np.int32)
494
+ else:
495
+ is_first_iteration = False
496
+
497
+ # print(f"t_compute {t_compute} list_nmb_stems {list_nmb_stems}")
498
+ return list_idx_injection, list_nmb_stems
499
+
500
+ def get_mixing_parameters(self, idx_injection):
501
+ r"""
502
+ Computes which parental latents should be mixed together to achieve a smooth blend.
503
+ As metric, we are using lpips image similarity. The insertion takes place
504
+ where the metric is maximal.
505
+ Args:
506
+ idx_injection: int
507
+ the index in terms of diffusion steps, where the next insertion will start.
508
+ """
509
+ # get_lpips_similarity
510
+ similarities = []
511
+ for i in range(len(self.tree_final_imgs)-1):
512
+ similarities.append(self.get_lpips_similarity(self.tree_final_imgs[i], self.tree_final_imgs[i+1]))
513
+ b_closest1 = np.argmax(similarities)
514
+ b_closest2 = b_closest1+1
515
+ fract_closest1 = self.tree_fracts[b_closest1]
516
+ fract_closest2 = self.tree_fracts[b_closest2]
517
+
518
+ # Ensure that the parents are indeed older!
519
+ b_parent1 = b_closest1
520
+ while True:
521
+ if self.tree_idx_injection[b_parent1] < idx_injection:
522
+ break
523
+ else:
524
+ b_parent1 -= 1
525
+
526
+ b_parent2 = b_closest2
527
+ while True:
528
+ if self.tree_idx_injection[b_parent2] < idx_injection:
529
+ break
530
+ else:
531
+ b_parent2 += 1
532
+
533
+ # print(f"\n\nb_closest: {b_closest1} {b_closest2} fract_closest1 {fract_closest1} fract_closest2 {fract_closest2}")
534
+ # print(f"b_parent: {b_parent1} {b_parent2}")
535
+ # print(f"similarities {similarities}")
536
+ # print(f"idx_injection {idx_injection} tree_idx_injection {self.tree_idx_injection}")
537
+
538
+ fract_mixing = (fract_closest1 + fract_closest2) /2
539
+ return fract_mixing, b_parent1, b_parent2
540
+
541
+
542
+ def insert_into_tree(self, fract_mixing, idx_injection, list_latents):
543
+ r"""
544
+ Inserts all necessary parameters into the trajectory tree.
545
+ Args:
546
+ fract_mixing: float
547
+ the fraction along the transition axis [0, 1]
548
+ idx_injection: int
549
+ the index in terms of diffusion steps, where the next insertion will start.
550
+ list_latents: list
551
+ list of the latents to be inserted
552
+ """
553
+ b_parent1, b_parent2 = get_closest_idx(fract_mixing, self.tree_fracts)
554
+ self.tree_latents.insert(b_parent1+1, list_latents)
555
+ self.tree_final_imgs.insert(b_parent1+1, self.sdh.latent2image(list_latents[-1]))
556
+ self.tree_fracts.insert(b_parent1+1, fract_mixing)
557
+ self.tree_idx_injection.insert(b_parent1+1, idx_injection)
558
+
559
+
560
+ def get_spatial_mask_template(self):
561
+ r"""
562
+ Experimental helper function to get a spatial mask template.
563
+ """
564
+ shape_latents = [self.sdh.C, self.sdh.height // self.sdh.f, self.sdh.width // self.sdh.f]
565
+ C, H, W = shape_latents
566
+ return np.ones((H, W))
567
+
568
+ def set_spatial_mask(self, img_mask):
569
+ r"""
570
+ Experimental helper function to set a spatial mask.
571
+ The mask forces latents to be overwritten.
572
+ Args:
573
+ img_mask:
574
+ mask image [0,1]. You can get a template using get_spatial_mask_template
575
+
576
+ """
577
+
578
+ shape_latents = [self.sdh.C, self.sdh.height // self.sdh.f, self.sdh.width // self.sdh.f]
579
+ C, H, W = shape_latents
580
+ img_mask = np.asarray(img_mask)
581
+ assert len(img_mask.shape) == 2, "Currently, only 2D images are supported as mask"
582
+ img_mask = np.clip(img_mask, 0, 1)
583
+ assert img_mask.shape[0] == H, f"Your mask needs to be of dimension {H} x {W}"
584
+ assert img_mask.shape[1] == W, f"Your mask needs to be of dimension {H} x {W}"
585
+ spatial_mask = torch.from_numpy(img_mask).to(device=self.device)
586
+ spatial_mask = torch.unsqueeze(spatial_mask, 0)
587
+ spatial_mask = spatial_mask.repeat((C,1,1))
588
+ spatial_mask = torch.unsqueeze(spatial_mask, 0)
589
+
590
+ self.spatial_mask = spatial_mask
591
+
592
+
593
+ def get_noise(self, seed):
594
+ r"""
595
+ Helper function to get noise given seed.
596
+ Args:
597
+ seed: int
598
+
599
+ """
600
+ generator = torch.Generator(device=self.sdh.device).manual_seed(int(seed))
601
+ if self.mode == 'standard':
602
+ shape_latents = [self.sdh.C, self.sdh.height // self.sdh.f, self.sdh.width // self.sdh.f]
603
+ C, H, W = shape_latents
604
+ elif self.mode == 'upscale':
605
+ w = self.image1_lowres.size[0]
606
+ h = self.image1_lowres.size[1]
607
+ shape_latents = [self.sdh.model.channels, h, w]
608
+ C, H, W = shape_latents
609
+
610
+ return torch.randn((1, C, H, W), generator=generator, device=self.sdh.device)
611
+
612
+
613
+ @torch.no_grad()
614
+ def run_diffusion(
615
+ self,
616
+ list_conditionings,
617
+ latents_start: torch.FloatTensor = None,
618
+ idx_start: int = 0,
619
+ list_latents_mixing = None,
620
+ mixing_coeffs = 0.0,
621
+ return_image: Optional[bool] = False
622
+ ):
623
+
624
+ r"""
625
+ Wrapper function for diffusion runners.
626
+ Depending on the mode, the correct one will be executed.
627
+
628
+ Args:
629
+ list_conditionings: list
630
+ List of all conditionings for the diffusion model.
631
+ latents_start: torch.FloatTensor
632
+ Latents that are used for injection
633
+ idx_start: int
634
+ Index of the diffusion process start and where the latents_for_injection are injected
635
+ list_latents_mixing: torch.FloatTensor
636
+ List of latents (latent trajectories) that are used for mixing
637
+ mixing_coeffs: float or list
638
+ Coefficients, how strong each element of list_latents_mixing will be mixed in.
639
+ return_image: Optional[bool]
640
+ Optionally return image directly
641
+ """
642
+
643
+ # Ensure correct num_inference_steps in Holder
644
+ self.sdh.num_inference_steps = self.num_inference_steps
645
+ assert type(list_conditionings) is list, "list_conditionings need to be a list"
646
+
647
+ if self.mode == 'standard':
648
+ text_embeddings = list_conditionings[0]
649
+ return self.sdh.run_diffusion_standard(
650
+ text_embeddings = text_embeddings,
651
+ latents_start = latents_start,
652
+ idx_start = idx_start,
653
+ list_latents_mixing = list_latents_mixing,
654
+ mixing_coeffs = mixing_coeffs,
655
+ spatial_mask = self.spatial_mask,
656
+ return_image = return_image,
657
+ )
658
+
659
+ elif self.mode == 'upscale':
660
+ cond = list_conditionings[0]
661
+ uc_full = list_conditionings[1]
662
+ return self.sdh.run_diffusion_upscaling(
663
+ cond,
664
+ uc_full,
665
+ latents_start=latents_start,
666
+ idx_start=idx_start,
667
+ list_latents_mixing = list_latents_mixing,
668
+ mixing_coeffs = mixing_coeffs,
669
+ return_image=return_image)
670
+
671
+
672
+ def run_upscaling(
673
+ self,
674
+ dp_img: str,
675
+ depth_strength: float = 0.65,
676
+ num_inference_steps: int = 100,
677
+ nmb_max_branches_highres: int = 5,
678
+ nmb_max_branches_lowres: int = 6,
679
+ duration_single_segment = 3,
680
+ fixed_seeds: Optional[List[int]] = None,
681
+ ):
682
+ r"""
683
+ Runs upscaling with the x4 model. Requires that you run a transition before with a low-res model and save the results using write_imgs_transition.
684
+
685
+ Args:
686
+ dp_img: str
687
+ Path to the low-res transition path (as saved in write_imgs_transition)
688
+ depth_strength:
689
+ Determines how deep the first injection will happen.
690
+ Deeper injections will cause (unwanted) formation of new structures,
691
+ more shallow values will go into alpha-blendy land.
692
+ num_inference_steps:
693
+ Number of diffusion steps. Higher values will take more compute time.
694
+ nmb_max_branches_highres: int
695
+ Number of final branches of the upscaling transition pass. Note this is the number
696
+ of branches between each pair of low-res images.
697
+ nmb_max_branches_lowres: int
698
+ Number of input low-res images, subsampling all transition images written in the low-res pass.
699
+ Setting this number lower (e.g. 6) will decrease the compute time but not affect the results too much.
700
+ duration_single_segment: float
701
+ The duration of each high-res movie segment. You will have nmb_max_branches_lowres-1 segments in total.
702
+ fixed_seeds: Optional[List[int)]:
703
+ You can supply two seeds that are used for the first and second keyframe (prompt1 and prompt2).
704
+ Otherwise random seeds will be taken.
705
+ """
706
+ fp_yml = os.path.join(dp_img, "lowres.yaml")
707
+ fp_movie = os.path.join(dp_img, "movie_highres.mp4")
708
+ fps = 24
709
+ ms = MovieSaver(fp_movie, fps=fps)
710
+ assert os.path.isfile(fp_yml), "lowres.yaml does not exist. did you forget run_upscaling_step1?"
711
+ dict_stuff = yml_load(fp_yml)
712
+
713
+ # load lowres images
714
+ nmb_images_lowres = dict_stuff['nmb_images']
715
+ prompt1 = dict_stuff['prompt1']
716
+ prompt2 = dict_stuff['prompt2']
717
+ idx_img_lowres = np.round(np.linspace(0, nmb_images_lowres-1, nmb_max_branches_lowres)).astype(np.int32)
718
+ imgs_lowres = []
719
+ for i in idx_img_lowres:
720
+ fp_img_lowres = os.path.join(dp_img, f"lowres_img_{str(i).zfill(4)}.jpg")
721
+ assert os.path.isfile(fp_img_lowres), f"{fp_img_lowres} does not exist. did you forget run_upscaling_step1?"
722
+ imgs_lowres.append(Image.open(fp_img_lowres))
723
+
724
+
725
+ # set up upscaling
726
+ text_embeddingA = self.sdh.get_text_embedding(prompt1)
727
+ text_embeddingB = self.sdh.get_text_embedding(prompt2)
728
+
729
+ list_fract_mixing = np.linspace(0, 1, nmb_max_branches_lowres-1)
730
+
731
+ for i in range(nmb_max_branches_lowres-1):
732
+ print(f"Starting movie segment {i+1}/{nmb_max_branches_lowres-1}")
733
+
734
+ self.text_embedding1 = interpolate_linear(text_embeddingA, text_embeddingB, list_fract_mixing[i])
735
+ self.text_embedding2 = interpolate_linear(text_embeddingA, text_embeddingB, 1-list_fract_mixing[i])
736
+
737
+ if i==0:
738
+ recycle_img1 = False
739
+ else:
740
+ self.swap_forward()
741
+ recycle_img1 = True
742
+
743
+ self.set_image1(imgs_lowres[i])
744
+ self.set_image2(imgs_lowres[i+1])
745
+
746
+ list_imgs = self.run_transition(
747
+ recycle_img1 = recycle_img1,
748
+ recycle_img2 = False,
749
+ num_inference_steps = num_inference_steps,
750
+ depth_strength = depth_strength,
751
+ nmb_max_branches = nmb_max_branches_highres,
752
+ )
753
+
754
+ list_imgs_interp = add_frames_linear_interp(list_imgs, fps, duration_single_segment)
755
+
756
+ # Save movie frame
757
+ for img in list_imgs_interp:
758
+ ms.write_frame(img)
759
+
760
+ ms.finalize()
761
+
762
+
763
+
764
+ @torch.no_grad()
765
+ def get_mixed_conditioning(self, fract_mixing):
766
+ if self.mode == 'standard':
767
+ text_embeddings_mix = interpolate_linear(self.text_embedding1, self.text_embedding2, fract_mixing)
768
+ list_conditionings = [text_embeddings_mix]
769
+ elif self.mode == 'inpaint':
770
+ text_embeddings_mix = interpolate_linear(self.text_embedding1, self.text_embedding2, fract_mixing)
771
+ list_conditionings = [text_embeddings_mix]
772
+ elif self.mode == 'upscale':
773
+ text_embeddings_mix = interpolate_linear(self.text_embedding1, self.text_embedding2, fract_mixing)
774
+ cond, uc_full = self.sdh.get_cond_upscaling(self.image1_lowres, text_embeddings_mix, self.noise_level_upscaling)
775
+ condB, uc_fullB = self.sdh.get_cond_upscaling(self.image2_lowres, text_embeddings_mix, self.noise_level_upscaling)
776
+ cond['c_concat'][0] = interpolate_spherical(cond['c_concat'][0], condB['c_concat'][0], fract_mixing)
777
+ uc_full['c_concat'][0] = interpolate_spherical(uc_full['c_concat'][0], uc_fullB['c_concat'][0], fract_mixing)
778
+ list_conditionings = [cond, uc_full]
779
+ else:
780
+ raise ValueError(f"mix_conditioning: unknown mode {self.mode}")
781
+ return list_conditionings
782
+
783
+ @torch.no_grad()
784
+ def get_text_embeddings(
785
+ self,
786
+ prompt: str
787
+ ):
788
+ r"""
789
+ Computes the text embeddings provided a string with a prompts.
790
+ Adapted from stable diffusion repo
791
+ Args:
792
+ prompt: str
793
+ ABC trending on artstation painted by Old Greg.
794
+ """
795
+
796
+ return self.sdh.get_text_embedding(prompt)
797
+
798
+
799
+ def write_imgs_transition(self, dp_img):
800
+ r"""
801
+ Writes the transition images into the folder dp_img.
802
+ Requires run_transition to be completed.
803
+ Args:
804
+ dp_img: str
805
+ Directory, into which the transition images, yaml file and latents are written.
806
+ """
807
+ imgs_transition = self.tree_final_imgs
808
+ os.makedirs(dp_img, exist_ok=True)
809
+ for i, img in enumerate(imgs_transition):
810
+ img_leaf = Image.fromarray(img)
811
+ img_leaf.save(os.path.join(dp_img, f"lowres_img_{str(i).zfill(4)}.jpg"))
812
+
813
+ fp_yml = os.path.join(dp_img, "lowres.yaml")
814
+ self.save_statedict(fp_yml)
815
+
816
+ def write_movie_transition(self, fp_movie, duration_transition, fps=30):
817
+ r"""
818
+ Writes the transition movie to fp_movie, using the given duration and fps..
819
+ The missing frames are linearly interpolated.
820
+ Args:
821
+ fp_movie: str
822
+ file pointer to the final movie.
823
+ duration_transition: float
824
+ duration of the movie in seonds
825
+ fps: int
826
+ fps of the movie
827
+
828
+ """
829
+
830
+ # Let's get more cheap frames via linear interpolation (duration_transition*fps frames)
831
+ imgs_transition_ext = add_frames_linear_interp(self.tree_final_imgs, duration_transition, fps)
832
+
833
+ # Save as MP4
834
+ if os.path.isfile(fp_movie):
835
+ os.remove(fp_movie)
836
+ ms = MovieSaver(fp_movie, fps=fps, shape_hw=[self.sdh.height, self.sdh.width])
837
+ for img in tqdm(imgs_transition_ext):
838
+ ms.write_frame(img)
839
+ ms.finalize()
840
+
841
+
842
+
843
+ def save_statedict(self, fp_yml):
844
+ # Dump everything relevant into yaml
845
+ imgs_transition = self.tree_final_imgs
846
+ state_dict = self.get_state_dict()
847
+ state_dict['nmb_images'] = len(imgs_transition)
848
+ yml_save(fp_yml, state_dict)
849
+
850
+ def get_state_dict(self):
851
+ state_dict = {}
852
+ grab_vars = ['prompt1', 'prompt2', 'seed1', 'seed2', 'height', 'width',
853
+ 'num_inference_steps', 'depth_strength', 'guidance_scale',
854
+ 'guidance_scale_mid_damper', 'mid_compression_scaler', 'negative_prompt',
855
+ 'branch1_crossfeed_power', 'branch1_crossfeed_range', 'branch1_crossfeed_decay'
856
+ 'parental_crossfeed_power', 'parental_crossfeed_range', 'parental_crossfeed_power_decay']
857
+ for v in grab_vars:
858
+ if hasattr(self, v):
859
+ if v == 'seed1' or v == 'seed2':
860
+ state_dict[v] = int(getattr(self, v))
861
+ elif v == 'guidance_scale':
862
+ state_dict[v] = float(getattr(self, v))
863
+
864
+ else:
865
+ try:
866
+ state_dict[v] = getattr(self, v)
867
+ except Exception as e:
868
+ pass
869
+
870
+ return state_dict
871
+
872
+ def randomize_seed(self):
873
+ r"""
874
+ Set a random seed for a fresh start.
875
+ """
876
+ seed = np.random.randint(999999999)
877
+ self.set_seed(seed)
878
+
879
+ def set_seed(self, seed: int):
880
+ r"""
881
+ Set a the seed for a fresh start.
882
+ """
883
+ self.seed = seed
884
+ self.sdh.seed = seed
885
+
886
+ def set_width(self, width):
887
+ r"""
888
+ Set the width of the resulting image.
889
+ """
890
+ assert np.mod(width, 64) == 0, "set_width: value needs to be divisible by 64"
891
+ self.width = width
892
+ self.sdh.width = width
893
+
894
+ def set_height(self, height):
895
+ r"""
896
+ Set the height of the resulting image.
897
+ """
898
+ assert np.mod(height, 64) == 0, "set_height: value needs to be divisible by 64"
899
+ self.height = height
900
+ self.sdh.height = height
901
+
902
+
903
+ def swap_forward(self):
904
+ r"""
905
+ Moves over keyframe two -> keyframe one. Useful for making a sequence of transitions
906
+ as in run_multi_transition()
907
+ """
908
+ # Move over all latents
909
+ self.tree_latents[0] = self.tree_latents[-1]
910
+
911
+ # Move over prompts and text embeddings
912
+ self.prompt1 = self.prompt2
913
+ self.text_embedding1 = self.text_embedding2
914
+
915
+ # Final cleanup for extra sanity
916
+ self.tree_final_imgs = []
917
+
918
+
919
+ def get_lpips_similarity(self, imgA, imgB):
920
+ r"""
921
+ Computes the image similarity between two images imgA and imgB.
922
+ Used to determine the optimal point of insertion to create smooth transitions.
923
+ High values indicate low similarity.
924
+ """
925
+ tensorA = torch.from_numpy(imgA).float().cuda(self.device)
926
+ tensorA = 2*tensorA/255.0 - 1
927
+ tensorA = tensorA.permute([2,0,1]).unsqueeze(0)
928
+
929
+ tensorB = torch.from_numpy(imgB).float().cuda(self.device)
930
+ tensorB = 2*tensorB/255.0 - 1
931
+ tensorB = tensorB.permute([2,0,1]).unsqueeze(0)
932
+ lploss = self.lpips(tensorA, tensorB)
933
+ lploss = float(lploss[0][0][0][0])
934
+
935
+ return lploss
936
+
937
+
938
+ # Auxiliary functions
939
+ def get_closest_idx(
940
+ fract_mixing: float,
941
+ list_fract_mixing_prev: List[float],
942
+ ):
943
+ r"""
944
+ Helper function to retrieve the parents for any given mixing.
945
+ Example: fract_mixing = 0.4 and list_fract_mixing_prev = [0, 0.3, 0.6, 1.0]
946
+ Will return the two closest values from list_fract_mixing_prev, i.e. [1, 2]
947
+ """
948
+
949
+ pdist = fract_mixing - np.asarray(list_fract_mixing_prev)
950
+ pdist_pos = pdist.copy()
951
+ pdist_pos[pdist_pos<0] = np.inf
952
+ b_parent1 = np.argmin(pdist_pos)
953
+ pdist_neg = -pdist.copy()
954
+ pdist_neg[pdist_neg<=0] = np.inf
955
+ b_parent2= np.argmin(pdist_neg)
956
+
957
+ if b_parent1 > b_parent2:
958
+ tmp = b_parent2
959
+ b_parent2 = b_parent1
960
+ b_parent1 = tmp
961
+
962
+ return b_parent1, b_parent2
963
+
964
+ @torch.no_grad()
965
+ def interpolate_spherical(p0, p1, fract_mixing: float):
966
+ r"""
967
+ Helper function to correctly mix two random variables using spherical interpolation.
968
+ See https://en.wikipedia.org/wiki/Slerp
969
+ The function will always cast up to float64 for sake of extra 4.
970
+ Args:
971
+ p0:
972
+ First tensor for interpolation
973
+ p1:
974
+ Second tensor for interpolation
975
+ fract_mixing: float
976
+ Mixing coefficient of interval [0, 1].
977
+ 0 will return in p0
978
+ 1 will return in p1
979
+ 0.x will return a mix between both preserving angular velocity.
980
+ """
981
+
982
+ if p0.dtype == torch.float16:
983
+ recast_to = 'fp16'
984
+ else:
985
+ recast_to = 'fp32'
986
+
987
+ p0 = p0.double()
988
+ p1 = p1.double()
989
+ norm = torch.linalg.norm(p0) * torch.linalg.norm(p1)
990
+ epsilon = 1e-7
991
+ dot = torch.sum(p0 * p1) / norm
992
+ dot = dot.clamp(-1+epsilon, 1-epsilon)
993
+
994
+ theta_0 = torch.arccos(dot)
995
+ sin_theta_0 = torch.sin(theta_0)
996
+ theta_t = theta_0 * fract_mixing
997
+ s0 = torch.sin(theta_0 - theta_t) / sin_theta_0
998
+ s1 = torch.sin(theta_t) / sin_theta_0
999
+ interp = p0*s0 + p1*s1
1000
+
1001
+ if recast_to == 'fp16':
1002
+ interp = interp.half()
1003
+ elif recast_to == 'fp32':
1004
+ interp = interp.float()
1005
+
1006
+ return interp
1007
+
1008
+
1009
+ def interpolate_linear(p0, p1, fract_mixing):
1010
+ r"""
1011
+ Helper function to mix two variables using standard linear interpolation.
1012
+ Args:
1013
+ p0:
1014
+ First tensor / np.ndarray for interpolation
1015
+ p1:
1016
+ Second tensor / np.ndarray for interpolation
1017
+ fract_mixing: float
1018
+ Mixing coefficient of interval [0, 1].
1019
+ 0 will return in p0
1020
+ 1 will return in p1
1021
+ 0.x will return a linear mix between both.
1022
+ """
1023
+ reconvert_uint8 = False
1024
+ if type(p0) is np.ndarray and p0.dtype == 'uint8':
1025
+ reconvert_uint8 = True
1026
+ p0 = p0.astype(np.float64)
1027
+
1028
+ if type(p1) is np.ndarray and p1.dtype == 'uint8':
1029
+ reconvert_uint8 = True
1030
+ p1 = p1.astype(np.float64)
1031
+
1032
+ interp = (1-fract_mixing) * p0 + fract_mixing * p1
1033
+
1034
+ if reconvert_uint8:
1035
+ interp = np.clip(interp, 0, 255).astype(np.uint8)
1036
+
1037
+ return interp
1038
+
1039
+
1040
+ def add_frames_linear_interp(
1041
+ list_imgs: List[np.ndarray],
1042
+ fps_target: Union[float, int] = None,
1043
+ duration_target: Union[float, int] = None,
1044
+ nmb_frames_target: int=None,
1045
+ ):
1046
+ r"""
1047
+ Helper function to cheaply increase the number of frames given a list of images,
1048
+ by virtue of standard linear interpolation.
1049
+ The number of inserted frames will be automatically adjusted so that the total of number
1050
+ of frames can be fixed precisely, using a random shuffling technique.
1051
+ The function allows 1:1 comparisons between transitions as videos.
1052
+
1053
+ Args:
1054
+ list_imgs: List[np.ndarray)
1055
+ List of images, between each image new frames will be inserted via linear interpolation.
1056
+ fps_target:
1057
+ OptionA: specify here the desired frames per second.
1058
+ duration_target:
1059
+ OptionA: specify here the desired duration of the transition in seconds.
1060
+ nmb_frames_target:
1061
+ OptionB: directly fix the total number of frames of the output.
1062
+ """
1063
+
1064
+ # Sanity
1065
+ if nmb_frames_target is not None and fps_target is not None:
1066
+ raise ValueError("You cannot specify both fps_target and nmb_frames_target")
1067
+ if fps_target is None:
1068
+ assert nmb_frames_target is not None, "Either specify nmb_frames_target or nmb_frames_target"
1069
+ if nmb_frames_target is None:
1070
+ assert fps_target is not None, "Either specify duration_target and fps_target OR nmb_frames_target"
1071
+ assert duration_target is not None, "Either specify duration_target and fps_target OR nmb_frames_target"
1072
+ nmb_frames_target = fps_target*duration_target
1073
+
1074
+ # Get number of frames that are missing
1075
+ nmb_frames_diff = len(list_imgs)-1
1076
+ nmb_frames_missing = nmb_frames_target - nmb_frames_diff - 1
1077
+
1078
+ if nmb_frames_missing < 1:
1079
+ return list_imgs
1080
+
1081
+ list_imgs_float = [img.astype(np.float32) for img in list_imgs]
1082
+ # Distribute missing frames, append nmb_frames_to_insert(i) frames for each frame
1083
+ mean_nmb_frames_insert = nmb_frames_missing/nmb_frames_diff
1084
+ constfact = np.floor(mean_nmb_frames_insert)
1085
+ remainder_x = 1-(mean_nmb_frames_insert - constfact)
1086
+
1087
+ nmb_iter = 0
1088
+ while True:
1089
+ nmb_frames_to_insert = np.random.rand(nmb_frames_diff)
1090
+ nmb_frames_to_insert[nmb_frames_to_insert<=remainder_x] = 0
1091
+ nmb_frames_to_insert[nmb_frames_to_insert>remainder_x] = 1
1092
+ nmb_frames_to_insert += constfact
1093
+ if np.sum(nmb_frames_to_insert) == nmb_frames_missing:
1094
+ break
1095
+ nmb_iter += 1
1096
+ if nmb_iter > 100000:
1097
+ print("add_frames_linear_interp: issue with inserting the right number of frames")
1098
+ break
1099
+
1100
+ nmb_frames_to_insert = nmb_frames_to_insert.astype(np.int32)
1101
+ list_imgs_interp = []
1102
+ for i in range(len(list_imgs_float)-1):#, desc="STAGE linear interp"):
1103
+ img0 = list_imgs_float[i]
1104
+ img1 = list_imgs_float[i+1]
1105
+ list_imgs_interp.append(img0.astype(np.uint8))
1106
+ list_fracts_linblend = np.linspace(0, 1, nmb_frames_to_insert[i]+2)[1:-1]
1107
+ for fract_linblend in list_fracts_linblend:
1108
+ img_blend = interpolate_linear(img0, img1, fract_linblend).astype(np.uint8)
1109
+ list_imgs_interp.append(img_blend.astype(np.uint8))
1110
+
1111
+ if i==len(list_imgs_float)-2:
1112
+ list_imgs_interp.append(img1.astype(np.uint8))
1113
+
1114
+ return list_imgs_interp
1115
+
1116
+
1117
+ def get_spacing(nmb_points: int, scaling: float):
1118
+ """
1119
+ Helper function for getting nonlinear spacing between 0 and 1, symmetric around 0.5
1120
+ Args:
1121
+ nmb_points: int
1122
+ Number of points between [0, 1]
1123
+ scaling: float
1124
+ Higher values will return higher sampling density around 0.5
1125
+
1126
+ """
1127
+ if scaling < 1.7:
1128
+ return np.linspace(0, 1, nmb_points)
1129
+ nmb_points_per_side = nmb_points//2 + 1
1130
+ if np.mod(nmb_points, 2) != 0: # uneven case
1131
+ left_side = np.abs(np.linspace(1, 0, nmb_points_per_side)**scaling / 2 - 0.5)
1132
+ right_side = 1-left_side[::-1][1:]
1133
+ else:
1134
+ left_side = np.abs(np.linspace(1, 0, nmb_points_per_side)**scaling / 2 - 0.5)[0:-1]
1135
+ right_side = 1-left_side[::-1]
1136
+ all_fracts = np.hstack([left_side, right_side])
1137
+ return all_fracts
1138
+
1139
+
1140
+ def get_time(resolution=None):
1141
+ """
1142
+ Helper function returning an nicely formatted time string, e.g. 221117_1620
1143
+ """
1144
+ if resolution==None:
1145
+ resolution="second"
1146
+ if resolution == "day":
1147
+ t = time.strftime('%y%m%d', time.localtime())
1148
+ elif resolution == "minute":
1149
+ t = time.strftime('%y%m%d_%H%M', time.localtime())
1150
+ elif resolution == "second":
1151
+ t = time.strftime('%y%m%d_%H%M%S', time.localtime())
1152
+ elif resolution == "millisecond":
1153
+ t = time.strftime('%y%m%d_%H%M%S', time.localtime())
1154
+ t += "_"
1155
+ t += str("{:03d}".format(int(int(datetime.utcnow().strftime('%f'))/1000)))
1156
+ else:
1157
+ raise ValueError("bad resolution provided: %s" %resolution)
1158
+ return t
1159
+
1160
+ def compare_dicts(a, b):
1161
+ """
1162
+ Compares two dictionaries a and b and returns a dictionary c, with all
1163
+ keys,values that have shared keys in a and b but same values in a and b.
1164
+ The values of a and b are stacked together in the output.
1165
+ Example:
1166
+ a = {}; a['bobo'] = 4
1167
+ b = {}; b['bobo'] = 5
1168
+ c = dict_compare(a,b)
1169
+ c = {"bobo",[4,5]}
1170
+ """
1171
+ c = {}
1172
+ for key in a.keys():
1173
+ if key in b.keys():
1174
+ val_a = a[key]
1175
+ val_b = b[key]
1176
+ if val_a != val_b:
1177
+ c[key] = [val_a, val_b]
1178
+ return c
1179
+
1180
+ def yml_load(fp_yml, print_fields=False):
1181
+ """
1182
+ Helper function for loading yaml files
1183
+ """
1184
+ with open(fp_yml) as f:
1185
+ data = yaml.load(f, Loader=yaml.loader.SafeLoader)
1186
+ dict_data = dict(data)
1187
+ print("load: loaded {}".format(fp_yml))
1188
+ return dict_data
1189
+
1190
+ def yml_save(fp_yml, dict_stuff):
1191
+ """
1192
+ Helper function for saving yaml files
1193
+ """
1194
+ with open(fp_yml, 'w') as f:
1195
+ data = yaml.dump(dict_stuff, f, sort_keys=False, default_flow_style=False)
1196
+ print("yml_save: saved {}".format(fp_yml))
1197
+
1198
+
1199
+ #%% le main
1200
+ if __name__ == "__main__":
1201
+ # xxxx
1202
+
1203
+ #%% First let us spawn a stable diffusion holder
1204
+ device = "cuda"
1205
+ fp_ckpt = "../stable_diffusion_models/ckpt/v2-1_512-ema-pruned.ckpt"
1206
+
1207
+ sdh = StableDiffusionHolder(fp_ckpt)
1208
+
1209
+ xxx
1210
+
1211
+
1212
+ #%% Next let's set up all parameters
1213
+ depth_strength = 0.3 # Specifies how deep (in terms of diffusion iterations the first branching happens)
1214
+ fixed_seeds = [697164, 430214]
1215
+
1216
+ prompt1 = "photo of a desert and a sky"
1217
+ prompt2 = "photo of a tree with a lake"
1218
+
1219
+ duration_transition = 12 # In seconds
1220
+ fps = 30
1221
+
1222
+ # Spawn latent blending
1223
+ self = LatentBlending(sdh)
1224
+
1225
+ self.set_prompt1(prompt1)
1226
+ self.set_prompt2(prompt2)
1227
+
1228
+ # Run latent blending
1229
+ self.branch1_crossfeed_power = 0.3
1230
+ self.branch1_crossfeed_range = 0.4
1231
+ # self.run_transition(depth_strength=depth_strength, fixed_seeds=fixed_seeds)
1232
+ self.seed1=21312
1233
+ img1 =self.compute_latents1(True)
1234
+ #%
1235
+ self.seed2=1234121
1236
+ self.branch1_crossfeed_power = 0.7
1237
+ self.branch1_crossfeed_range = 0.3
1238
+ self.branch1_crossfeed_decay = 0.3
1239
+ img2 =self.compute_latents2(True)
1240
+ # Image.fromarray(np.concatenate((img1, img2), axis=1))
1241
+
1242
+ #%%
1243
+ t0 = time.time()
1244
+ self.t_compute_max_allowed = 30
1245
+ self.parental_crossfeed_range = 1.0
1246
+ self.parental_crossfeed_power = 0.0
1247
+ self.parental_crossfeed_power_decay = 1.0
1248
+ imgs_transition = self.run_transition(recycle_img1=True, recycle_img2=True)
1249
+ t1 = time.time()
1250
+ print(f"took: {t1-t0}s")
ldm/__pycache__/util.cpython-310.pyc ADDED
Binary file (6.18 kB). View file
ldm/__pycache__/util.cpython-38.pyc ADDED
Binary file (6.15 kB). View file
ldm/__pycache__/util.cpython-39.pyc ADDED
Binary file (6.16 kB). View file
ldm/data/__init__.py ADDED
File without changes
ldm/data/util.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from ldm.modules.midas.api import load_midas_transform
4
+
5
+
6
+ class AddMiDaS(object):
7
+ def __init__(self, model_type):
8
+ super().__init__()
9
+ self.transform = load_midas_transform(model_type)
10
+
11
+ def pt2np(self, x):
12
+ x = ((x + 1.0) * .5).detach().cpu().numpy()
13
+ return x
14
+
15
+ def np2pt(self, x):
16
+ x = torch.from_numpy(x) * 2 - 1.
17
+ return x
18
+
19
+ def __call__(self, sample):
20
+ # sample['jpg'] is tensor hwc in [-1, 1] at this point
21
+ x = self.pt2np(sample['jpg'])
22
+ x = self.transform({"image": x})["image"]
23
+ sample['midas_in'] = x
24
+ return sample
ldm/ldm ADDED
@@ -0,0 +1 @@
 
1
+ ldm
ldm/models/__pycache__/autoencoder.cpython-310.pyc ADDED
Binary file (7.72 kB). View file
ldm/models/__pycache__/autoencoder.cpython-38.pyc ADDED
Binary file (7.61 kB). View file
ldm/models/__pycache__/autoencoder.cpython-39.pyc ADDED
Binary file (7.68 kB). View file
ldm/models/autoencoder.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pytorch_lightning as pl
3
+ import torch.nn.functional as F
4
+ from contextlib import contextmanager
5
+
6
+ from ldm.modules.diffusionmodules.model import Encoder, Decoder
7
+ from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
8
+
9
+ from ldm.util import instantiate_from_config
10
+ from ldm.modules.ema import LitEma
11
+
12
+
13
+ class AutoencoderKL(pl.LightningModule):
14
+ def __init__(self,
15
+ ddconfig,
16
+ lossconfig,
17
+ embed_dim,
18
+ ckpt_path=None,
19
+ ignore_keys=[],
20
+ image_key="image",
21
+ colorize_nlabels=None,
22
+ monitor=None,
23
+ ema_decay=None,
24
+ learn_logvar=False
25
+ ):
26
+ super().__init__()
27
+ self.learn_logvar = learn_logvar
28
+ self.image_key = image_key
29
+ self.encoder = Encoder(**ddconfig)
30
+ self.decoder = Decoder(**ddconfig)
31
+ self.loss = instantiate_from_config(lossconfig)
32
+ assert ddconfig["double_z"]
33
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
34
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
35
+ self.embed_dim = embed_dim
36
+ if colorize_nlabels is not None:
37
+ assert type(colorize_nlabels)==int
38
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
39
+ if monitor is not None:
40
+ self.monitor = monitor
41
+
42
+ self.use_ema = ema_decay is not None
43
+ if self.use_ema:
44
+ self.ema_decay = ema_decay
45
+ assert 0. < ema_decay < 1.
46
+ self.model_ema = LitEma(self, decay=ema_decay)
47
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
48
+
49
+ if ckpt_path is not None:
50
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
51
+
52
+ def init_from_ckpt(self, path, ignore_keys=list()):
53
+ sd = torch.load(path, map_location="cpu")["state_dict"]
54
+ keys = list(sd.keys())
55
+ for k in keys:
56
+ for ik in ignore_keys:
57
+ if k.startswith(ik):
58
+ print("Deleting key {} from state_dict.".format(k))
59
+ del sd[k]
60
+ self.load_state_dict(sd, strict=False)
61
+ print(f"Restored from {path}")
62
+
63
+ @contextmanager
64
+ def ema_scope(self, context=None):
65
+ if self.use_ema:
66
+ self.model_ema.store(self.parameters())
67
+ self.model_ema.copy_to(self)
68
+ if context is not None:
69
+ print(f"{context}: Switched to EMA weights")
70
+ try:
71
+ yield None
72
+ finally:
73
+ if self.use_ema:
74
+ self.model_ema.restore(self.parameters())
75
+ if context is not None:
76
+ print(f"{context}: Restored training weights")
77
+
78
+ def on_train_batch_end(self, *args, **kwargs):
79
+ if self.use_ema:
80
+ self.model_ema(self)
81
+
82
+ def encode(self, x):
83
+ h = self.encoder(x)
84
+ moments = self.quant_conv(h)
85
+ posterior = DiagonalGaussianDistribution(moments)
86
+ return posterior
87
+
88
+ def decode(self, z):
89
+ z = self.post_quant_conv(z)
90
+ dec = self.decoder(z)
91
+ return dec
92
+
93
+ def forward(self, input, sample_posterior=True):
94
+ posterior = self.encode(input)
95
+ if sample_posterior:
96
+ z = posterior.sample()
97
+ else:
98
+ z = posterior.mode()
99
+ dec = self.decode(z)
100
+ return dec, posterior
101
+
102
+ def get_input(self, batch, k):
103
+ x = batch[k]
104
+ if len(x.shape) == 3:
105
+ x = x[..., None]
106
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
107
+ return x
108
+
109
+ def training_step(self, batch, batch_idx, optimizer_idx):
110
+ inputs = self.get_input(batch, self.image_key)
111
+ reconstructions, posterior = self(inputs)
112
+
113
+ if optimizer_idx == 0:
114
+ # train encoder+decoder+logvar
115
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
116
+ last_layer=self.get_last_layer(), split="train")
117
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
118
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
119
+ return aeloss
120
+
121
+ if optimizer_idx == 1:
122
+ # train the discriminator
123
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
124
+ last_layer=self.get_last_layer(), split="train")
125
+
126
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
127
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
128
+ return discloss
129
+
130
+ def validation_step(self, batch, batch_idx):
131
+ log_dict = self._validation_step(batch, batch_idx)
132
+ with self.ema_scope():
133
+ log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema")
134
+ return log_dict
135
+
136
+ def _validation_step(self, batch, batch_idx, postfix=""):
137
+ inputs = self.get_input(batch, self.image_key)
138
+ reconstructions, posterior = self(inputs)
139
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
140
+ last_layer=self.get_last_layer(), split="val"+postfix)
141
+
142
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
143
+ last_layer=self.get_last_layer(), split="val"+postfix)
144
+
145
+ self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"])
146
+ self.log_dict(log_dict_ae)
147
+ self.log_dict(log_dict_disc)
148
+ return self.log_dict
149
+
150
+ def configure_optimizers(self):
151
+ lr = self.learning_rate
152
+ ae_params_list = list(self.encoder.parameters()) + list(self.decoder.parameters()) + list(
153
+ self.quant_conv.parameters()) + list(self.post_quant_conv.parameters())
154
+ if self.learn_logvar:
155
+ print(f"{self.__class__.__name__}: Learning logvar")
156
+ ae_params_list.append(self.loss.logvar)
157
+ opt_ae = torch.optim.Adam(ae_params_list,
158
+ lr=lr, betas=(0.5, 0.9))
159
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
160
+ lr=lr, betas=(0.5, 0.9))
161
+ return [opt_ae, opt_disc], []
162
+
163
+ def get_last_layer(self):
164
+ return self.decoder.conv_out.weight
165
+
166
+ @torch.no_grad()
167
+ def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs):
168
+ log = dict()
169
+ x = self.get_input(batch, self.image_key)
170
+ x = x.to(self.device)
171
+ if not only_inputs:
172
+ xrec, posterior = self(x)
173
+ if x.shape[1] > 3:
174
+ # colorize with random projection
175
+ assert xrec.shape[1] > 3
176
+ x = self.to_rgb(x)
177
+ xrec = self.to_rgb(xrec)
178
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
179
+ log["reconstructions"] = xrec
180
+ if log_ema or self.use_ema:
181
+ with self.ema_scope():
182
+ xrec_ema, posterior_ema = self(x)
183
+ if x.shape[1] > 3:
184
+ # colorize with random projection
185
+ assert xrec_ema.shape[1] > 3
186
+ xrec_ema = self.to_rgb(xrec_ema)
187
+ log["samples_ema"] = self.decode(torch.randn_like(posterior_ema.sample()))
188
+ log["reconstructions_ema"] = xrec_ema
189
+ log["inputs"] = x
190
+ return log
191
+
192
+ def to_rgb(self, x):
193
+ assert self.image_key == "segmentation"
194
+ if not hasattr(self, "colorize"):
195
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
196
+ x = F.conv2d(x, weight=self.colorize)
197
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
198
+ return x
199
+
200
+
201
+ class IdentityFirstStage(torch.nn.Module):
202
+ def __init__(self, *args, vq_interface=False, **kwargs):
203
+ self.vq_interface = vq_interface
204
+ super().__init__()
205
+
206
+ def encode(self, x, *args, **kwargs):
207
+ return x
208
+
209
+ def decode(self, x, *args, **kwargs):
210
+ return x
211
+
212
+ def quantize(self, x, *args, **kwargs):
213
+ if self.vq_interface:
214
+ return x, None, [None, None, None]
215
+ return x
216
+
217
+ def forward(self, x, *args, **kwargs):
218
+ return x
219
+
ldm/models/diffusion/__init__.py ADDED
File without changes
ldm/models/diffusion/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (155 Bytes). View file
ldm/models/diffusion/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (153 Bytes). View file
ldm/models/diffusion/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (153 Bytes). View file
ldm/models/diffusion/__pycache__/ddim.cpython-310.pyc ADDED
Binary file (9.33 kB). View file
ldm/models/diffusion/__pycache__/ddim.cpython-38.pyc ADDED
Binary file (9.27 kB). View file
ldm/models/diffusion/__pycache__/ddim.cpython-39.pyc ADDED
Binary file (9.19 kB). View file
ldm/models/diffusion/__pycache__/ddpm.cpython-310.pyc ADDED
Binary file (52.8 kB). View file
ldm/models/diffusion/__pycache__/ddpm.cpython-38.pyc ADDED
Binary file (53 kB). View file
ldm/models/diffusion/__pycache__/ddpm.cpython-39.pyc ADDED
Binary file (53 kB). View file
ldm/models/diffusion/__pycache__/plms.cpython-39.pyc ADDED
Binary file (7.46 kB). View file
ldm/models/diffusion/__pycache__/sampling_util.cpython-39.pyc ADDED
Binary file (1.07 kB). View file
ldm/models/diffusion/ddim.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+
7
+ from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
8
+
9
+
10
+ class DDIMSampler(object):
11
+ def __init__(self, model, schedule="linear", **kwargs):
12
+ super().__init__()
13
+ self.model = model
14
+ self.ddpm_num_timesteps = model.num_timesteps
15
+ self.schedule = schedule
16
+
17
+ def register_buffer(self, name, attr):
18
+ if type(attr) == torch.Tensor:
19
+ if attr.device != torch.device("cuda"):
20
+ attr = attr.to(torch.device("cuda"))
21
+ setattr(self, name, attr)
22
+
23
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
24
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
25
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
26
+ alphas_cumprod = self.model.alphas_cumprod
27
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
28
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
29
+
30
+ self.register_buffer('betas', to_torch(self.model.betas))
31
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
32
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
33
+
34
+ # calculations for diffusion q(x_t | x_{t-1}) and others
35
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
36
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
37
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
38
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
39
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
40
+
41
+ # ddim sampling parameters
42
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
43
+ ddim_timesteps=self.ddim_timesteps,
44
+ eta=ddim_eta,verbose=verbose)
45
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
46
+ self.register_buffer('ddim_alphas', ddim_alphas)
47
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
48
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
49
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
50
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
51
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
52
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
53
+
54
+ @torch.no_grad()
55
+ def sample(self,
56
+ S,
57
+ batch_size,
58
+ shape,
59
+ conditioning=None,
60
+ callback=None,
61
+ normals_sequence=None,
62
+ img_callback=None,
63
+ quantize_x0=False,
64
+ eta=0.,
65
+ mask=None,
66
+ x0=None,
67
+ temperature=1.,
68
+ noise_dropout=0.,
69
+ score_corrector=None,
70
+ corrector_kwargs=None,
71
+ verbose=True,
72
+ x_T=None,
73
+ log_every_t=100,
74
+ unconditional_guidance_scale=1.,
75
+ unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
76
+ dynamic_threshold=None,
77
+ ucg_schedule=None,
78
+ **kwargs
79
+ ):
80
+ if conditioning is not None:
81
+ if isinstance(conditioning, dict):
82
+ ctmp = conditioning[list(conditioning.keys())[0]]
83
+ while isinstance(ctmp, list): ctmp = ctmp[0]
84
+ cbs = ctmp.shape[0]
85
+ if cbs != batch_size:
86
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
87
+
88
+ elif isinstance(conditioning, list):
89
+ for ctmp in conditioning:
90
+ if ctmp.shape[0] != batch_size:
91
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
92
+
93
+ else:
94
+ if conditioning.shape[0] != batch_size:
95
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
96
+
97
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
98
+ # sampling
99
+ C, H, W = shape
100
+ size = (batch_size, C, H, W)
101
+ print(f'Data shape for DDIM sampling is {size}, eta {eta}')
102
+
103
+ samples, intermediates = self.ddim_sampling(conditioning, size,
104
+ callback=callback,
105
+ img_callback=img_callback,
106
+ quantize_denoised=quantize_x0,
107
+ mask=mask, x0=x0,
108
+ ddim_use_original_steps=False,
109
+ noise_dropout=noise_dropout,
110
+ temperature=temperature,
111
+ score_corrector=score_corrector,
112
+ corrector_kwargs=corrector_kwargs,
113
+ x_T=x_T,
114
+ log_every_t=log_every_t,
115
+ unconditional_guidance_scale=unconditional_guidance_scale,
116
+ unconditional_conditioning=unconditional_conditioning,
117
+ dynamic_threshold=dynamic_threshold,
118
+ ucg_schedule=ucg_schedule
119
+ )
120
+ return samples, intermediates
121
+
122
+ @torch.no_grad()
123
+ def ddim_sampling(self, cond, shape,
124
+ x_T=None, ddim_use_original_steps=False,
125
+ callback=None, timesteps=None, quantize_denoised=False,
126
+ mask=None, x0=None, img_callback=None, log_every_t=100,
127
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
128
+ unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
129
+ ucg_schedule=None):
130
+ device = self.model.betas.device
131
+ b = shape[0]
132
+ if x_T is None:
133
+ img = torch.randn(shape, device=device)
134
+ else:
135
+ img = x_T
136
+
137
+ if timesteps is None:
138
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
139
+ elif timesteps is not None and not ddim_use_original_steps:
140
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
141
+ timesteps = self.ddim_timesteps[:subset_end]
142
+
143
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
144
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
145
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
146
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
147
+
148
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
149
+
150
+ for i, step in enumerate(iterator):
151
+ index = total_steps - i - 1
152
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
153
+
154
+ if mask is not None:
155
+ assert x0 is not None
156
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
157
+ img = img_orig * mask + (1. - mask) * img
158
+
159
+ if ucg_schedule is not None:
160
+ assert len(ucg_schedule) == len(time_range)
161
+ unconditional_guidance_scale = ucg_schedule[i]
162
+
163
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
164
+ quantize_denoised=quantize_denoised, temperature=temperature,
165
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
166
+ corrector_kwargs=corrector_kwargs,
167
+ unconditional_guidance_scale=unconditional_guidance_scale,
168
+ unconditional_conditioning=unconditional_conditioning,
169
+ dynamic_threshold=dynamic_threshold)
170
+ img, pred_x0 = outs
171
+ if callback: callback(i)
172
+ if img_callback: img_callback(pred_x0, i)
173
+
174
+ if index % log_every_t == 0 or index == total_steps - 1:
175
+ intermediates['x_inter'].append(img)
176
+ intermediates['pred_x0'].append(pred_x0)
177
+
178
+ return img, intermediates
179
+
180
+ @torch.no_grad()
181
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
182
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
183
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
184
+ dynamic_threshold=None):
185
+ b, *_, device = *x.shape, x.device
186
+
187
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
188
+ model_output = self.model.apply_model(x, t, c)
189
+ else:
190
+ x_in = torch.cat([x] * 2)
191
+ t_in = torch.cat([t] * 2)
192
+ if isinstance(c, dict):
193
+ assert isinstance(unconditional_conditioning, dict)
194
+ c_in = dict()
195
+ for k in c:
196
+ if isinstance(c[k], list):
197
+ c_in[k] = [torch.cat([
198
+ unconditional_conditioning[k][i],
199
+ c[k][i]]) for i in range(len(c[k]))]
200
+ else:
201
+ c_in[k] = torch.cat([
202
+ unconditional_conditioning[k],
203
+ c[k]])
204
+ elif isinstance(c, list):
205
+ c_in = list()
206
+ assert isinstance(unconditional_conditioning, list)
207
+ for i in range(len(c)):
208
+ c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))
209
+ else:
210
+ c_in = torch.cat([unconditional_conditioning, c])
211
+ model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
212
+ model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
213
+
214
+ if self.model.parameterization == "v":
215
+ e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
216
+ else:
217
+ e_t = model_output
218
+
219
+ if score_corrector is not None:
220
+ assert self.model.parameterization == "eps", 'not implemented'
221
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
222
+
223
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
224
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
225
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
226
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
227
+ # select parameters corresponding to the currently considered timestep
228
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
229
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
230
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
231
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
232
+
233
+ # current prediction for x_0
234
+ if self.model.parameterization != "v":
235
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
236
+ else:
237
+ pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
238
+
239
+ if quantize_denoised:
240
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
241
+
242
+ if dynamic_threshold is not None:
243
+ raise NotImplementedError()
244
+
245
+ # direction pointing to x_t
246
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
247
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
248
+ if noise_dropout > 0.:
249
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
250
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
251
+ return x_prev, pred_x0
252
+
253
+ @torch.no_grad()
254
+ def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
255
+ unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
256
+ num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]
257
+
258
+ assert t_enc <= num_reference_steps
259
+ num_steps = t_enc
260
+
261
+ if use_original_steps:
262
+ alphas_next = self.alphas_cumprod[:num_steps]
263
+ alphas = self.alphas_cumprod_prev[:num_steps]
264
+ else:
265
+ alphas_next = self.ddim_alphas[:num_steps]
266
+ alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
267
+
268
+ x_next = x0
269
+ intermediates = []
270
+ inter_steps = []
271
+ for i in tqdm(range(num_steps), desc='Encoding Image'):
272
+ t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)
273
+ if unconditional_guidance_scale == 1.:
274
+ noise_pred = self.model.apply_model(x_next, t, c)
275
+ else:
276
+ assert unconditional_conditioning is not None
277
+ e_t_uncond, noise_pred = torch.chunk(
278
+ self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
279
+ torch.cat((unconditional_conditioning, c))), 2)
280
+ noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
281
+
282
+ xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
283
+ weighted_noise_pred = alphas_next[i].sqrt() * (
284
+ (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
285
+ x_next = xt_weighted + weighted_noise_pred
286
+ if return_intermediates and i % (
287
+ num_steps // return_intermediates) == 0 and i < num_steps - 1:
288
+ intermediates.append(x_next)
289
+ inter_steps.append(i)
290
+ elif return_intermediates and i >= num_steps - 2:
291
+ intermediates.append(x_next)
292
+ inter_steps.append(i)
293
+ if callback: callback(i)
294
+
295
+ out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
296
+ if return_intermediates:
297
+ out.update({'intermediates': intermediates})
298
+ return x_next, out
299
+
300
+ @torch.no_grad()
301
+ def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
302
+ # fast, but does not allow for exact reconstruction
303
+ # t serves as an index to gather the correct alphas
304
+ if use_original_steps:
305
+ sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
306
+ sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
307
+ else:
308
+ sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
309
+ sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
310
+
311
+ if noise is None:
312
+ noise = torch.randn_like(x0)
313
+ return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
314
+ extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
315
+
316
+ @torch.no_grad()
317
+ def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
318
+ use_original_steps=False, callback=None):
319
+
320
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
321
+ timesteps = timesteps[:t_start]
322
+
323
+ time_range = np.flip(timesteps)
324
+ total_steps = timesteps.shape[0]
325
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
326
+
327
+ iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
328
+ x_dec = x_latent
329
+ for i, step in enumerate(iterator):
330
+ index = total_steps - i - 1
331
+ ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
332
+ x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
333
+ unconditional_guidance_scale=unconditional_guidance_scale,
334
+ unconditional_conditioning=unconditional_conditioning)
335
+ if callback: callback(i)
336
+ return x_dec
ldm/models/diffusion/ddpm.py ADDED
@@ -0,0 +1,1795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ wild mixture of
3
+ https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
4
+ https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
5
+ https://github.com/CompVis/taming-transformers
6
+ -- merci
7
+ """
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import numpy as np
12
+ import pytorch_lightning as pl
13
+ from torch.optim.lr_scheduler import LambdaLR
14
+ from einops import rearrange, repeat
15
+ from contextlib import contextmanager, nullcontext
16
+ from functools import partial
17
+ import itertools
18
+ from tqdm import tqdm
19
+ from torchvision.utils import make_grid
20
+ from pytorch_lightning.utilities.distributed import rank_zero_only
21
+ from omegaconf import ListConfig
22
+
23
+ from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
24
+ from ldm.modules.ema import LitEma
25
+ from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
26
+ from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL
27
+ from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
28
+ from ldm.models.diffusion.ddim import DDIMSampler
29
+
30
+
31
+ __conditioning_keys__ = {'concat': 'c_concat',
32
+ 'crossattn': 'c_crossattn',
33
+ 'adm': 'y'}
34
+
35
+
36
+ def disabled_train(self, mode=True):
37
+ """Overwrite model.train with this function to make sure train/eval mode
38
+ does not change anymore."""
39
+ return self
40
+
41
+
42
+ def uniform_on_device(r1, r2, shape, device):
43
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
44
+
45
+
46
+ class DDPM(pl.LightningModule):
47
+ # classic DDPM with Gaussian diffusion, in image space
48
+ def __init__(self,
49
+ unet_config,
50
+ timesteps=1000,
51
+ beta_schedule="linear",
52
+ loss_type="l2",
53
+ ckpt_path=None,
54
+ ignore_keys=[],
55
+ load_only_unet=False,
56
+ monitor="val/loss",
57
+ use_ema=True,
58
+ first_stage_key="image",
59
+ image_size=256,
60
+ channels=3,
61
+ log_every_t=100,
62
+ clip_denoised=True,
63
+ linear_start=1e-4,
64
+ linear_end=2e-2,
65
+ cosine_s=8e-3,
66
+ given_betas=None,
67
+ original_elbo_weight=0.,
68
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
69
+ l_simple_weight=1.,
70
+ conditioning_key=None,
71
+ parameterization="eps", # all assuming fixed variance schedules
72
+ scheduler_config=None,
73
+ use_positional_encodings=False,
74
+ learn_logvar=False,
75
+ logvar_init=0.,
76
+ make_it_fit=False,
77
+ ucg_training=None,
78
+ reset_ema=False,
79
+ reset_num_ema_updates=False,
80
+ ):
81
+ super().__init__()
82
+ assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"'
83
+ self.parameterization = parameterization
84
+ print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
85
+ self.cond_stage_model = None
86
+ self.clip_denoised = clip_denoised
87
+ self.log_every_t = log_every_t
88
+ self.first_stage_key = first_stage_key
89
+ self.image_size = image_size # try conv?
90
+ self.channels = channels
91
+ self.use_positional_encodings = use_positional_encodings
92
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
93
+ count_params(self.model, verbose=True)
94
+ self.use_ema = use_ema
95
+ if self.use_ema:
96
+ self.model_ema = LitEma(self.model)
97
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
98
+
99
+ self.use_scheduler = scheduler_config is not None
100
+ if self.use_scheduler:
101
+ self.scheduler_config = scheduler_config
102
+
103
+ self.v_posterior = v_posterior
104
+ self.original_elbo_weight = original_elbo_weight
105
+ self.l_simple_weight = l_simple_weight
106
+
107
+ if monitor is not None:
108
+ self.monitor = monitor
109
+ self.make_it_fit = make_it_fit
110
+ if reset_ema: assert exists(ckpt_path)
111
+ if ckpt_path is not None:
112
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
113
+ if reset_ema:
114
+ assert self.use_ema
115
+ print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
116
+ self.model_ema = LitEma(self.model)
117
+ if reset_num_ema_updates:
118
+ print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
119
+ assert self.use_ema
120
+ self.model_ema.reset_num_updates()
121
+
122
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
123
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
124
+
125
+ self.loss_type = loss_type
126
+
127
+ self.learn_logvar = learn_logvar
128
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
129
+ if self.learn_logvar:
130
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
131
+
132
+ self.ucg_training = ucg_training or dict()
133
+ if self.ucg_training:
134
+ self.ucg_prng = np.random.RandomState()
135
+
136
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
137
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
138
+ if exists(given_betas):
139
+ betas = given_betas
140
+ else:
141
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
142
+ cosine_s=cosine_s)
143
+ alphas = 1. - betas
144
+ alphas_cumprod = np.cumprod(alphas, axis=0)
145
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
146
+
147
+ timesteps, = betas.shape
148
+ self.num_timesteps = int(timesteps)
149
+ self.linear_start = linear_start
150
+ self.linear_end = linear_end
151
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
152
+
153
+ to_torch = partial(torch.tensor, dtype=torch.float32)
154
+
155
+ self.register_buffer('betas', to_torch(betas))
156
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
157
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
158
+
159
+ # calculations for diffusion q(x_t | x_{t-1}) and others
160
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
161
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
162
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
163
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
164
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
165
+
166
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
167
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
168
+ 1. - alphas_cumprod) + self.v_posterior * betas
169
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
170
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
171
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
172
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
173
+ self.register_buffer('posterior_mean_coef1', to_torch(
174
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
175
+ self.register_buffer('posterior_mean_coef2', to_torch(
176
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
177
+
178
+ if self.parameterization == "eps":
179
+ lvlb_weights = self.betas ** 2 / (
180
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
181
+ elif self.parameterization == "x0":
182
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
183
+ elif self.parameterization == "v":
184
+ lvlb_weights = torch.ones_like(self.betas ** 2 / (
185
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)))
186
+ else:
187
+ raise NotImplementedError("mu not supported")
188
+ lvlb_weights[0] = lvlb_weights[1]
189
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
190
+ assert not torch.isnan(self.lvlb_weights).all()
191
+
192
+ @contextmanager
193
+ def ema_scope(self, context=None):
194
+ if self.use_ema:
195
+ self.model_ema.store(self.model.parameters())
196
+ self.model_ema.copy_to(self.model)
197
+ if context is not None:
198
+ print(f"{context}: Switched to EMA weights")
199
+ try:
200
+ yield None
201
+ finally:
202
+ if self.use_ema:
203
+ self.model_ema.restore(self.model.parameters())
204
+ if context is not None:
205
+ print(f"{context}: Restored training weights")
206
+
207
+ @torch.no_grad()
208
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
209
+ sd = torch.load(path, map_location="cpu")
210
+ if "state_dict" in list(sd.keys()):
211
+ sd = sd["state_dict"]
212
+ keys = list(sd.keys())
213
+ for k in keys:
214
+ for ik in ignore_keys:
215
+ if k.startswith(ik):
216
+ print("Deleting key {} from state_dict.".format(k))
217
+ del sd[k]
218
+ if self.make_it_fit:
219
+ n_params = len([name for name, _ in
220
+ itertools.chain(self.named_parameters(),
221
+ self.named_buffers())])
222
+ for name, param in tqdm(
223
+ itertools.chain(self.named_parameters(),
224
+ self.named_buffers()),
225
+ desc="Fitting old weights to new weights",
226
+ total=n_params
227
+ ):
228
+ if not name in sd:
229
+ continue
230
+ old_shape = sd[name].shape
231
+ new_shape = param.shape
232
+ assert len(old_shape) == len(new_shape)
233
+ if len(new_shape) > 2:
234
+ # we only modify first two axes
235
+ assert new_shape[2:] == old_shape[2:]
236
+ # assumes first axis corresponds to output dim
237
+ if not new_shape == old_shape:
238
+ new_param = param.clone()
239
+ old_param = sd[name]
240
+ if len(new_shape) == 1:
241
+ for i in range(new_param.shape[0]):
242
+ new_param[i] = old_param[i % old_shape[0]]
243
+ elif len(new_shape) >= 2:
244
+ for i in range(new_param.shape[0]):
245
+ for j in range(new_param.shape[1]):
246
+ new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]]
247
+
248
+ n_used_old = torch.ones(old_shape[1])
249
+ for j in range(new_param.shape[1]):
250
+ n_used_old[j % old_shape[1]] += 1
251
+ n_used_new = torch.zeros(new_shape[1])
252
+ for j in range(new_param.shape[1]):
253
+ n_used_new[j] = n_used_old[j % old_shape[1]]
254
+
255
+ n_used_new = n_used_new[None, :]
256
+ while len(n_used_new.shape) < len(new_shape):
257
+ n_used_new = n_used_new.unsqueeze(-1)
258
+ new_param /= n_used_new
259
+
260
+ sd[name] = new_param
261
+
262
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
263
+ sd, strict=False)
264
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
265
+ if len(missing) > 0:
266
+ print(f"Missing Keys:\n {missing}")
267
+ if len(unexpected) > 0:
268
+ print(f"\nUnexpected Keys:\n {unexpected}")
269
+
270
+ def q_mean_variance(self, x_start, t):
271
+ """
272
+ Get the distribution q(x_t | x_0).
273
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
274
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
275
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
276
+ """
277
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
278
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
279
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
280
+ return mean, variance, log_variance
281
+
282
+ def predict_start_from_noise(self, x_t, t, noise):
283
+ return (
284
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
285
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
286
+ )
287
+
288
+ def predict_start_from_z_and_v(self, x_t, t, v):
289
+ # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
290
+ # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
291
+ return (
292
+ extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t -
293
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
294
+ )
295
+
296
+ def predict_eps_from_z_and_v(self, x_t, t, v):
297
+ return (
298
+ extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v +
299
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t
300
+ )
301
+
302
+ def q_posterior(self, x_start, x_t, t):
303
+ posterior_mean = (
304
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
305
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
306
+ )
307
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
308
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
309
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
310
+
311
+ def p_mean_variance(self, x, t, clip_denoised: bool):
312
+ model_out = self.model(x, t)
313
+ if self.parameterization == "eps":
314
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
315
+ elif self.parameterization == "x0":
316
+ x_recon = model_out
317
+ if clip_denoised:
318
+ x_recon.clamp_(-1., 1.)
319
+
320
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
321
+ return model_mean, posterior_variance, posterior_log_variance
322
+
323
+ @torch.no_grad()
324
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
325
+ b, *_, device = *x.shape, x.device
326
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
327
+ noise = noise_like(x.shape, device, repeat_noise)
328
+ # no noise when t == 0
329
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
330
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
331
+
332
+ @torch.no_grad()
333
+ def p_sample_loop(self, shape, return_intermediates=False):
334
+ device = self.betas.device
335
+ b = shape[0]
336
+ img = torch.randn(shape, device=device)
337
+ intermediates = [img]
338
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
339
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
340
+ clip_denoised=self.clip_denoised)
341
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
342
+ intermediates.append(img)
343
+ if return_intermediates:
344
+ return img, intermediates
345
+ return img
346
+
347
+ @torch.no_grad()
348
+ def sample(self, batch_size=16, return_intermediates=False):
349
+ image_size = self.image_size
350
+ channels = self.channels
351
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
352
+ return_intermediates=return_intermediates)
353
+
354
+ def q_sample(self, x_start, t, noise=None):
355
+ noise = default(noise, lambda: torch.randn_like(x_start))
356
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
357
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
358
+
359
+ def get_v(self, x, noise, t):
360
+ return (
361
+ extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
362
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
363
+ )
364
+
365
+ def get_loss(self, pred, target, mean=True):
366
+ if self.loss_type == 'l1':
367
+ loss = (target - pred).abs()
368
+ if mean:
369
+ loss = loss.mean()
370
+ elif self.loss_type == 'l2':
371
+ if mean:
372
+ loss = torch.nn.functional.mse_loss(target, pred)
373
+ else:
374
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
375
+ else:
376
+ raise NotImplementedError("unknown loss type '{loss_type}'")
377
+
378
+ return loss
379
+
380
+ def p_losses(self, x_start, t, noise=None):
381
+ noise = default(noise, lambda: torch.randn_like(x_start))
382
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
383
+ model_out = self.model(x_noisy, t)
384
+
385
+ loss_dict = {}
386
+ if self.parameterization == "eps":
387
+ target = noise
388
+ elif self.parameterization == "x0":
389
+ target = x_start
390
+ elif self.parameterization == "v":
391
+ target = self.get_v(x_start, noise, t)
392
+ else:
393
+ raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
394
+
395
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
396
+
397
+ log_prefix = 'train' if self.training else 'val'
398
+
399
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
400
+ loss_simple = loss.mean() * self.l_simple_weight
401
+
402
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
403
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
404
+
405
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
406
+
407
+ loss_dict.update({f'{log_prefix}/loss': loss})
408
+
409
+ return loss, loss_dict
410
+
411
+ def forward(self, x, *args, **kwargs):
412
+ # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
413
+ # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
414
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
415
+ return self.p_losses(x, t, *args, **kwargs)
416
+
417
+ def get_input(self, batch, k):
418
+ x = batch[k]
419
+ if len(x.shape) == 3:
420
+ x = x[..., None]
421
+ x = rearrange(x, 'b h w c -> b c h w')
422
+ x = x.to(memory_format=torch.contiguous_format).float()
423
+ return x
424
+
425
+ def shared_step(self, batch):
426
+ x = self.get_input(batch, self.first_stage_key)
427
+ loss, loss_dict = self(x)
428
+ return loss, loss_dict
429
+
430
+ def training_step(self, batch, batch_idx):
431
+ for k in self.ucg_training:
432
+ p = self.ucg_training[k]["p"]
433
+ val = self.ucg_training[k]["val"]
434
+ if val is None:
435
+ val = ""
436
+ for i in range(len(batch[k])):
437
+ if self.ucg_prng.choice(2, p=[1 - p, p]):
438
+ batch[k][i] = val
439
+
440
+ loss, loss_dict = self.shared_step(batch)
441
+
442
+ self.log_dict(loss_dict, prog_bar=True,
443
+ logger=True, on_step=True, on_epoch=True)
444
+
445
+ self.log("global_step", self.global_step,
446
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
447
+
448
+ if self.use_scheduler:
449
+ lr = self.optimizers().param_groups[0]['lr']
450
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
451
+
452
+ return loss
453
+
454
+ @torch.no_grad()
455
+ def validation_step(self, batch, batch_idx):
456
+ _, loss_dict_no_ema = self.shared_step(batch)
457
+ with self.ema_scope():
458
+ _, loss_dict_ema = self.shared_step(batch)
459
+ loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
460
+ self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
461
+ self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
462
+
463
+ def on_train_batch_end(self, *args, **kwargs):
464
+ if self.use_ema:
465
+ self.model_ema(self.model)
466
+
467
+ def _get_rows_from_list(self, samples):
468
+ n_imgs_per_row = len(samples)
469
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
470
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
471
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
472
+ return denoise_grid
473
+
474
+ @torch.no_grad()
475
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
476
+ log = dict()
477
+ x = self.get_input(batch, self.first_stage_key)
478
+ N = min(x.shape[0], N)
479
+ n_row = min(x.shape[0], n_row)
480
+ x = x.to(self.device)[:N]
481
+ log["inputs"] = x
482
+
483
+ # get diffusion row
484
+ diffusion_row = list()
485
+ x_start = x[:n_row]
486
+
487
+ for t in range(self.num_timesteps):
488
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
489
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
490
+ t = t.to(self.device).long()
491
+ noise = torch.randn_like(x_start)
492
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
493
+ diffusion_row.append(x_noisy)
494
+
495
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
496
+
497
+ if sample:
498
+ # get denoise row
499
+ with self.ema_scope("Plotting"):
500
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
501
+
502
+ log["samples"] = samples
503
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
504
+
505
+ if return_keys:
506
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
507
+ return log
508
+ else:
509
+ return {key: log[key] for key in return_keys}
510
+ return log
511
+
512
+ def configure_optimizers(self):
513
+ lr = self.learning_rate
514
+ params = list(self.model.parameters())
515
+ if self.learn_logvar:
516
+ params = params + [self.logvar]
517
+ opt = torch.optim.AdamW(params, lr=lr)
518
+ return opt
519
+
520
+
521
+ class LatentDiffusion(DDPM):
522
+ """main class"""
523
+
524
+ def __init__(self,
525
+ first_stage_config,
526
+ cond_stage_config,
527
+ num_timesteps_cond=None,
528
+ cond_stage_key="image",
529
+ cond_stage_trainable=False,
530
+ concat_mode=True,
531
+ cond_stage_forward=None,
532
+ conditioning_key=None,
533
+ scale_factor=1.0,
534
+ scale_by_std=False,
535
+ force_null_conditioning=False,
536
+ *args, **kwargs):
537
+ self.force_null_conditioning = force_null_conditioning
538
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
539
+ self.scale_by_std = scale_by_std
540
+ assert self.num_timesteps_cond <= kwargs['timesteps']
541
+ # for backwards compatibility after implementation of DiffusionWrapper
542
+ if conditioning_key is None:
543
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
544
+ if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:
545
+ conditioning_key = None
546
+ ckpt_path = kwargs.pop("ckpt_path", None)
547
+ reset_ema = kwargs.pop("reset_ema", False)
548
+ reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False)
549
+ ignore_keys = kwargs.pop("ignore_keys", [])
550
+ super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
551
+ self.concat_mode = concat_mode
552
+ self.cond_stage_trainable = cond_stage_trainable
553
+ self.cond_stage_key = cond_stage_key
554
+ try:
555
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
556
+ except:
557
+ self.num_downs = 0
558
+ if not scale_by_std:
559
+ self.scale_factor = scale_factor
560
+ else:
561
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
562
+ self.instantiate_first_stage(first_stage_config)
563
+ self.instantiate_cond_stage(cond_stage_config)
564
+ self.cond_stage_forward = cond_stage_forward
565
+ self.clip_denoised = False
566
+ self.bbox_tokenizer = None
567
+
568
+ self.restarted_from_ckpt = False
569
+ if ckpt_path is not None:
570
+ self.init_from_ckpt(ckpt_path, ignore_keys)
571
+ self.restarted_from_ckpt = True
572
+ if reset_ema:
573
+ assert self.use_ema
574
+ print(
575
+ f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
576
+ self.model_ema = LitEma(self.model)
577
+ if reset_num_ema_updates:
578
+ print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
579
+ assert self.use_ema
580
+ self.model_ema.reset_num_updates()
581
+
582
+ def make_cond_schedule(self, ):
583
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
584
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
585
+ self.cond_ids[:self.num_timesteps_cond] = ids
586
+
587
+ @rank_zero_only
588
+ @torch.no_grad()
589
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
590
+ # only for very first batch
591
+ if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
592
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
593
+ # set rescale weight to 1./std of encodings
594
+ print("### USING STD-RESCALING ###")
595
+ x = super().get_input(batch, self.first_stage_key)
596
+ x = x.to(self.device)
597
+ encoder_posterior = self.encode_first_stage(x)
598
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
599
+ del self.scale_factor
600
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
601
+ print(f"setting self.scale_factor to {self.scale_factor}")
602
+ print("### USING STD-RESCALING ###")
603
+
604
+ def register_schedule(self,
605
+ given_betas=None, beta_schedule="linear", timesteps=1000,
606
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
607
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
608
+
609
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
610
+ if self.shorten_cond_schedule:
611
+ self.make_cond_schedule()
612
+
613
+ def instantiate_first_stage(self, config):
614
+ model = instantiate_from_config(config)
615
+ self.first_stage_model = model.eval()
616
+ self.first_stage_model.train = disabled_train
617
+ for param in self.first_stage_model.parameters():
618
+ param.requires_grad = False
619
+
620
+ def instantiate_cond_stage(self, config):
621
+ if not self.cond_stage_trainable:
622
+ if config == "__is_first_stage__":
623
+ print("Using first stage also as cond stage.")
624
+ self.cond_stage_model = self.first_stage_model
625
+ elif config == "__is_unconditional__":
626
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
627
+ self.cond_stage_model = None
628
+ # self.be_unconditional = True
629
+ else:
630
+ model = instantiate_from_config(config)
631
+ self.cond_stage_model = model.eval()
632
+ self.cond_stage_model.train = disabled_train
633
+ for param in self.cond_stage_model.parameters():
634
+ param.requires_grad = False
635
+ else:
636
+ assert config != '__is_first_stage__'
637
+ assert config != '__is_unconditional__'
638
+ model = instantiate_from_config(config)
639
+ self.cond_stage_model = model
640
+
641
+ def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
642
+ denoise_row = []
643
+ for zd in tqdm(samples, desc=desc):
644
+ denoise_row.append(self.decode_first_stage(zd.to(self.device),
645
+ force_not_quantize=force_no_decoder_quantization))
646
+ n_imgs_per_row = len(denoise_row)
647
+ denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
648
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
649
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
650
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
651
+ return denoise_grid
652
+
653
+ def get_first_stage_encoding(self, encoder_posterior):
654
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
655
+ z = encoder_posterior.sample()
656
+ elif isinstance(encoder_posterior, torch.Tensor):
657
+ z = encoder_posterior
658
+ else:
659
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
660
+ return self.scale_factor * z
661
+
662
+ def get_learned_conditioning(self, c):
663
+ if self.cond_stage_forward is None:
664
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
665
+ c = self.cond_stage_model.encode(c)
666
+ if isinstance(c, DiagonalGaussianDistribution):
667
+ c = c.mode()
668
+ else:
669
+ c = self.cond_stage_model(c)
670
+ else:
671
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
672
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
673
+ return c
674
+
675
+ def meshgrid(self, h, w):
676
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
677
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
678
+
679
+ arr = torch.cat([y, x], dim=-1)
680
+ return arr
681
+
682
+ def delta_border(self, h, w):
683
+ """
684
+ :param h: height
685
+ :param w: width
686
+ :return: normalized distance to image border,
687
+ wtith min distance = 0 at border and max dist = 0.5 at image center
688
+ """
689
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
690
+ arr = self.meshgrid(h, w) / lower_right_corner
691
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
692
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
693
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
694
+ return edge_dist
695
+
696
+ def get_weighting(self, h, w, Ly, Lx, device):
697
+ weighting = self.delta_border(h, w)
698
+ weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
699
+ self.split_input_params["clip_max_weight"], )
700
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
701
+
702
+ if self.split_input_params["tie_braker"]:
703
+ L_weighting = self.delta_border(Ly, Lx)
704
+ L_weighting = torch.clip(L_weighting,
705
+ self.split_input_params["clip_min_tie_weight"],
706
+ self.split_input_params["clip_max_tie_weight"])
707
+
708
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
709
+ weighting = weighting * L_weighting
710
+ return weighting
711
+
712
+ def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
713
+ """
714
+ :param x: img of size (bs, c, h, w)
715
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
716
+ """
717
+ bs, nc, h, w = x.shape
718
+
719
+ # number of crops in image
720
+ Ly = (h - kernel_size[0]) // stride[0] + 1
721
+ Lx = (w - kernel_size[1]) // stride[1] + 1
722
+
723
+ if uf == 1 and df == 1:
724
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
725
+ unfold = torch.nn.Unfold(**fold_params)
726
+
727
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
728
+
729
+ weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
730
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
731
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
732
+
733
+ elif uf > 1 and df == 1:
734
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
735
+ unfold = torch.nn.Unfold(**fold_params)
736
+
737
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
738
+ dilation=1, padding=0,
739
+ stride=(stride[0] * uf, stride[1] * uf))
740
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
741
+
742
+ weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
743
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
744
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
745
+
746
+ elif df > 1 and uf == 1:
747
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
748
+ unfold = torch.nn.Unfold(**fold_params)
749
+
750
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
751
+ dilation=1, padding=0,
752
+ stride=(stride[0] // df, stride[1] // df))
753
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
754
+
755
+ weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
756
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
757
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
758
+
759
+ else:
760
+ raise NotImplementedError
761
+
762
+ return fold, unfold, normalization, weighting
763
+
764
+ @torch.no_grad()
765
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
766
+ cond_key=None, return_original_cond=False, bs=None, return_x=False):
767
+ x = super().get_input(batch, k)
768
+ if bs is not None:
769
+ x = x[:bs]
770
+ x = x.to(self.device)
771
+ encoder_posterior = self.encode_first_stage(x)
772
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
773
+
774
+ if self.model.conditioning_key is not None and not self.force_null_conditioning:
775
+ if cond_key is None:
776
+ cond_key = self.cond_stage_key
777
+ if cond_key != self.first_stage_key:
778
+ if cond_key in ['caption', 'coordinates_bbox', "txt"]:
779
+ xc = batch[cond_key]
780
+ elif cond_key in ['class_label', 'cls']:
781
+ xc = batch
782
+ else:
783
+ xc = super().get_input(batch, cond_key).to(self.device)
784
+ else:
785
+ xc = x
786
+ if not self.cond_stage_trainable or force_c_encode:
787
+ if isinstance(xc, dict) or isinstance(xc, list):
788
+ c = self.get_learned_conditioning(xc)
789
+ else:
790
+ c = self.get_learned_conditioning(xc.to(self.device))
791
+ else:
792
+ c = xc
793
+ if bs is not None:
794
+ c = c[:bs]
795
+
796
+ if self.use_positional_encodings:
797
+ pos_x, pos_y = self.compute_latent_shifts(batch)
798
+ ckey = __conditioning_keys__[self.model.conditioning_key]
799
+ c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
800
+
801
+ else:
802
+ c = None
803
+ xc = None
804
+ if self.use_positional_encodings:
805
+ pos_x, pos_y = self.compute_latent_shifts(batch)
806
+ c = {'pos_x': pos_x, 'pos_y': pos_y}
807
+ out = [z, c]
808
+ if return_first_stage_outputs:
809
+ xrec = self.decode_first_stage(z)
810
+ out.extend([x, xrec])
811
+ if return_x:
812
+ out.extend([x])
813
+ if return_original_cond:
814
+ out.append(xc)
815
+ return out
816
+
817
+ @torch.no_grad()
818
+ def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
819
+ if predict_cids:
820
+ if z.dim() == 4:
821
+ z = torch.argmax(z.exp(), dim=1).long()
822
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
823
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
824
+
825
+ z = 1. / self.scale_factor * z
826
+ return self.first_stage_model.decode(z)
827
+
828
+ @torch.no_grad()
829
+ def encode_first_stage(self, x):
830
+ return self.first_stage_model.encode(x)
831
+
832
+ def shared_step(self, batch, **kwargs):
833
+ x, c = self.get_input(batch, self.first_stage_key)
834
+ loss = self(x, c)
835
+ return loss
836
+
837
+ def forward(self, x, c, *args, **kwargs):
838
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
839
+ if self.model.conditioning_key is not None:
840
+ assert c is not None
841
+ if self.cond_stage_trainable:
842
+ c = self.get_learned_conditioning(c)
843
+ if self.shorten_cond_schedule: # TODO: drop this option
844
+ tc = self.cond_ids[t].to(self.device)
845
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
846
+ return self.p_losses(x, c, t, *args, **kwargs)
847
+
848
+ def apply_model(self, x_noisy, t, cond, return_ids=False):
849
+ if isinstance(cond, dict):
850
+ # hybrid case, cond is expected to be a dict
851
+ pass
852
+ else:
853
+ if not isinstance(cond, list):
854
+ cond = [cond]
855
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
856
+ cond = {key: cond}
857
+
858
+ x_recon = self.model(x_noisy, t, **cond)
859
+
860
+ if isinstance(x_recon, tuple) and not return_ids:
861
+ return x_recon[0]
862
+ else:
863
+ return x_recon
864
+
865
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
866
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
867
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
868
+
869
+ def _prior_bpd(self, x_start):
870
+ """
871
+ Get the prior KL term for the variational lower-bound, measured in
872
+ bits-per-dim.
873
+ This term can't be optimized, as it only depends on the encoder.
874
+ :param x_start: the [N x C x ...] tensor of inputs.
875
+ :return: a batch of [N] KL values (in bits), one per batch element.
876
+ """
877
+ batch_size = x_start.shape[0]
878
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
879
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
880
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
881
+ return mean_flat(kl_prior) / np.log(2.0)
882
+
883
+ def p_losses(self, x_start, cond, t, noise=None):
884
+ noise = default(noise, lambda: torch.randn_like(x_start))
885
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
886
+ model_output = self.apply_model(x_noisy, t, cond)
887
+
888
+ loss_dict = {}
889
+ prefix = 'train' if self.training else 'val'
890
+
891
+ if self.parameterization == "x0":
892
+ target = x_start
893
+ elif self.parameterization == "eps":
894
+ target = noise
895
+ elif self.parameterization == "v":
896
+ target = self.get_v(x_start, noise, t)
897
+ else:
898
+ raise NotImplementedError()
899
+
900
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
901
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
902
+
903
+ logvar_t = self.logvar[t].to(self.device)
904
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
905
+ # loss = loss_simple / torch.exp(self.logvar) + self.logvar
906
+ if self.learn_logvar:
907
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
908
+ loss_dict.update({'logvar': self.logvar.data.mean()})
909
+
910
+ loss = self.l_simple_weight * loss.mean()
911
+
912
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
913
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
914
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
915
+ loss += (self.original_elbo_weight * loss_vlb)
916
+ loss_dict.update({f'{prefix}/loss': loss})
917
+
918
+ return loss, loss_dict
919
+
920
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
921
+ return_x0=False, score_corrector=None, corrector_kwargs=None):
922
+ t_in = t
923
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
924
+
925
+ if score_corrector is not None:
926
+ assert self.parameterization == "eps"
927
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
928
+
929
+ if return_codebook_ids:
930
+ model_out, logits = model_out
931
+
932
+ if self.parameterization == "eps":
933
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
934
+ elif self.parameterization == "x0":
935
+ x_recon = model_out
936
+ else:
937
+ raise NotImplementedError()
938
+
939
+ if clip_denoised:
940
+ x_recon.clamp_(-1., 1.)
941
+ if quantize_denoised:
942
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
943
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
944
+ if return_codebook_ids:
945
+ return model_mean, posterior_variance, posterior_log_variance, logits
946
+ elif return_x0:
947
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
948
+ else:
949
+ return model_mean, posterior_variance, posterior_log_variance
950
+
951
+ @torch.no_grad()
952
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
953
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
954
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
955
+ b, *_, device = *x.shape, x.device
956
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
957
+ return_codebook_ids=return_codebook_ids,
958
+ quantize_denoised=quantize_denoised,
959
+ return_x0=return_x0,
960
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
961
+ if return_codebook_ids:
962
+ raise DeprecationWarning("Support dropped.")
963
+ model_mean, _, model_log_variance, logits = outputs
964
+ elif return_x0:
965
+ model_mean, _, model_log_variance, x0 = outputs
966
+ else:
967
+ model_mean, _, model_log_variance = outputs
968
+
969
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
970
+ if noise_dropout > 0.:
971
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
972
+ # no noise when t == 0
973
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
974
+
975
+ if return_codebook_ids:
976
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
977
+ if return_x0:
978
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
979
+ else:
980
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
981
+
982
+ @torch.no_grad()
983
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
984
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
985
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
986
+ log_every_t=None):
987
+ if not log_every_t:
988
+ log_every_t = self.log_every_t
989
+ timesteps = self.num_timesteps
990
+ if batch_size is not None:
991
+ b = batch_size if batch_size is not None else shape[0]
992
+ shape = [batch_size] + list(shape)
993
+ else:
994
+ b = batch_size = shape[0]
995
+ if x_T is None:
996
+ img = torch.randn(shape, device=self.device)
997
+ else:
998
+ img = x_T
999
+ intermediates = []
1000
+ if cond is not None:
1001
+ if isinstance(cond, dict):
1002
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1003
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1004
+ else:
1005
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1006
+
1007
+ if start_T is not None:
1008
+ timesteps = min(timesteps, start_T)
1009
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1010
+ total=timesteps) if verbose else reversed(
1011
+ range(0, timesteps))
1012
+ if type(temperature) == float:
1013
+ temperature = [temperature] * timesteps
1014
+
1015
+ for i in iterator:
1016
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1017
+ if self.shorten_cond_schedule:
1018
+ assert self.model.conditioning_key != 'hybrid'
1019
+ tc = self.cond_ids[ts].to(cond.device)
1020
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1021
+
1022
+ img, x0_partial = self.p_sample(img, cond, ts,
1023
+ clip_denoised=self.clip_denoised,
1024
+ quantize_denoised=quantize_denoised, return_x0=True,
1025
+ temperature=temperature[i], noise_dropout=noise_dropout,
1026
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1027
+ if mask is not None:
1028
+ assert x0 is not None
1029
+ img_orig = self.q_sample(x0, ts)
1030
+ img = img_orig * mask + (1. - mask) * img
1031
+
1032
+ if i % log_every_t == 0 or i == timesteps - 1:
1033
+ intermediates.append(x0_partial)
1034
+ if callback: callback(i)
1035
+ if img_callback: img_callback(img, i)
1036
+ return img, intermediates
1037
+
1038
+ @torch.no_grad()
1039
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1040
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1041
+ mask=None, x0=None, img_callback=None, start_T=None,
1042
+ log_every_t=None):
1043
+
1044
+ if not log_every_t:
1045
+ log_every_t = self.log_every_t
1046
+ device = self.betas.device
1047
+ b = shape[0]
1048
+ if x_T is None:
1049
+ img = torch.randn(shape, device=device)
1050
+ else:
1051
+ img = x_T
1052
+
1053
+ intermediates = [img]
1054
+ if timesteps is None:
1055
+ timesteps = self.num_timesteps
1056
+
1057
+ if start_T is not None:
1058
+ timesteps = min(timesteps, start_T)
1059
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1060
+ range(0, timesteps))
1061
+
1062
+ if mask is not None:
1063
+ assert x0 is not None
1064
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1065
+
1066
+ for i in iterator:
1067
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1068
+ if self.shorten_cond_schedule:
1069
+ assert self.model.conditioning_key != 'hybrid'
1070
+ tc = self.cond_ids[ts].to(cond.device)
1071
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1072
+
1073
+ img = self.p_sample(img, cond, ts,
1074
+ clip_denoised=self.clip_denoised,
1075
+ quantize_denoised=quantize_denoised)
1076
+ if mask is not None:
1077
+ img_orig = self.q_sample(x0, ts)
1078
+ img = img_orig * mask + (1. - mask) * img
1079
+
1080
+ if i % log_every_t == 0 or i == timesteps - 1:
1081
+ intermediates.append(img)
1082
+ if callback: callback(i)
1083
+ if img_callback: img_callback(img, i)
1084
+
1085
+ if return_intermediates:
1086
+ return img, intermediates
1087
+ return img
1088
+
1089
+ @torch.no_grad()
1090
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1091
+ verbose=True, timesteps=None, quantize_denoised=False,
1092
+ mask=None, x0=None, shape=None, **kwargs):
1093
+ if shape is None:
1094
+ shape = (batch_size, self.channels, self.image_size, self.image_size)
1095
+ if cond is not None:
1096
+ if isinstance(cond, dict):
1097
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1098
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1099
+ else:
1100
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1101
+ return self.p_sample_loop(cond,
1102
+ shape,
1103
+ return_intermediates=return_intermediates, x_T=x_T,
1104
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1105
+ mask=mask, x0=x0)
1106
+
1107
+ @torch.no_grad()
1108
+ def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
1109
+ if ddim:
1110
+ ddim_sampler = DDIMSampler(self)
1111
+ shape = (self.channels, self.image_size, self.image_size)
1112
+ samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,
1113
+ shape, cond, verbose=False, **kwargs)
1114
+
1115
+ else:
1116
+ samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1117
+ return_intermediates=True, **kwargs)
1118
+
1119
+ return samples, intermediates
1120
+
1121
+ @torch.no_grad()
1122
+ def get_unconditional_conditioning(self, batch_size, null_label=None):
1123
+ if null_label is not None:
1124
+ xc = null_label
1125
+ if isinstance(xc, ListConfig):
1126
+ xc = list(xc)
1127
+ if isinstance(xc, dict) or isinstance(xc, list):
1128
+ c = self.get_learned_conditioning(xc)
1129
+ else:
1130
+ if hasattr(xc, "to"):
1131
+ xc = xc.to(self.device)
1132
+ c = self.get_learned_conditioning(xc)
1133
+ else:
1134
+ if self.cond_stage_key in ["class_label", "cls"]:
1135
+ xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)
1136
+ return self.get_learned_conditioning(xc)
1137
+ else:
1138
+ raise NotImplementedError("todo")
1139
+ if isinstance(c, list): # in case the encoder gives us a list
1140
+ for i in range(len(c)):
1141
+ c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)
1142
+ else:
1143
+ c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)
1144
+ return c
1145
+
1146
+ @torch.no_grad()
1147
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,
1148
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1149
+ plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
1150
+ use_ema_scope=True,
1151
+ **kwargs):
1152
+ ema_scope = self.ema_scope if use_ema_scope else nullcontext
1153
+ use_ddim = ddim_steps is not None
1154
+
1155
+ log = dict()
1156
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1157
+ return_first_stage_outputs=True,
1158
+ force_c_encode=True,
1159
+ return_original_cond=True,
1160
+ bs=N)
1161
+ N = min(x.shape[0], N)
1162
+ n_row = min(x.shape[0], n_row)
1163
+ log["inputs"] = x
1164
+ log["reconstruction"] = xrec
1165
+ if self.model.conditioning_key is not None:
1166
+ if hasattr(self.cond_stage_model, "decode"):
1167
+ xc = self.cond_stage_model.decode(c)
1168
+ log["conditioning"] = xc
1169
+ elif self.cond_stage_key in ["caption", "txt"]:
1170
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
1171
+ log["conditioning"] = xc
1172
+ elif self.cond_stage_key in ['class_label', "cls"]:
1173
+ try:
1174
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
1175
+ log['conditioning'] = xc
1176
+ except KeyError:
1177
+ # probably no "human_label" in batch
1178
+ pass
1179
+ elif isimage(xc):
1180
+ log["conditioning"] = xc
1181
+ if ismap(xc):
1182
+ log["original_conditioning"] = self.to_rgb(xc)
1183
+
1184
+ if plot_diffusion_rows:
1185
+ # get diffusion row
1186
+ diffusion_row = list()
1187
+ z_start = z[:n_row]
1188
+ for t in range(self.num_timesteps):
1189
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1190
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1191
+ t = t.to(self.device).long()
1192
+ noise = torch.randn_like(z_start)
1193
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1194
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1195
+
1196
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1197
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1198
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1199
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1200
+ log["diffusion_row"] = diffusion_grid
1201
+
1202
+ if sample:
1203
+ # get denoise row
1204
+ with ema_scope("Sampling"):
1205
+ samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1206
+ ddim_steps=ddim_steps, eta=ddim_eta)
1207
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1208
+ x_samples = self.decode_first_stage(samples)
1209
+ log["samples"] = x_samples
1210
+ if plot_denoise_rows:
1211
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1212
+ log["denoise_row"] = denoise_grid
1213
+
1214
+ if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1215
+ self.first_stage_model, IdentityFirstStage):
1216
+ # also display when quantizing x0 while sampling
1217
+ with ema_scope("Plotting Quantized Denoised"):
1218
+ samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1219
+ ddim_steps=ddim_steps, eta=ddim_eta,
1220
+ quantize_denoised=True)
1221
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1222
+ # quantize_denoised=True)
1223
+ x_samples = self.decode_first_stage(samples.to(self.device))
1224
+ log["samples_x0_quantized"] = x_samples
1225
+
1226
+ if unconditional_guidance_scale > 1.0:
1227
+ uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)
1228
+ if self.model.conditioning_key == "crossattn-adm":
1229
+ uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]}
1230
+ with ema_scope("Sampling with classifier-free guidance"):
1231
+ samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1232
+ ddim_steps=ddim_steps, eta=ddim_eta,
1233
+ unconditional_guidance_scale=unconditional_guidance_scale,
1234
+ unconditional_conditioning=uc,
1235
+ )
1236
+ x_samples_cfg = self.decode_first_stage(samples_cfg)
1237
+ log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
1238
+
1239
+ if inpaint:
1240
+ # make a simple center square
1241
+ b, h, w = z.shape[0], z.shape[2], z.shape[3]
1242
+ mask = torch.ones(N, h, w).to(self.device)
1243
+ # zeros will be filled in
1244
+ mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1245
+ mask = mask[:, None, ...]
1246
+ with ema_scope("Plotting Inpaint"):
1247
+ samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
1248
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1249
+ x_samples = self.decode_first_stage(samples.to(self.device))
1250
+ log["samples_inpainting"] = x_samples
1251
+ log["mask"] = mask
1252
+
1253
+ # outpaint
1254
+ mask = 1. - mask
1255
+ with ema_scope("Plotting Outpaint"):
1256
+ samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
1257
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1258
+ x_samples = self.decode_first_stage(samples.to(self.device))
1259
+ log["samples_outpainting"] = x_samples
1260
+
1261
+ if plot_progressive_rows:
1262
+ with ema_scope("Plotting Progressives"):
1263
+ img, progressives = self.progressive_denoising(c,
1264
+ shape=(self.channels, self.image_size, self.image_size),
1265
+ batch_size=N)
1266
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1267
+ log["progressive_row"] = prog_row
1268
+
1269
+ if return_keys:
1270
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1271
+ return log
1272
+ else:
1273
+ return {key: log[key] for key in return_keys}
1274
+ return log
1275
+
1276
+ def configure_optimizers(self):
1277
+ lr = self.learning_rate
1278
+ params = list(self.model.parameters())
1279
+ if self.cond_stage_trainable:
1280
+ print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1281
+ params = params + list(self.cond_stage_model.parameters())
1282
+ if self.learn_logvar:
1283
+ print('Diffusion model optimizing logvar')
1284
+ params.append(self.logvar)
1285
+ opt = torch.optim.AdamW(params, lr=lr)
1286
+ if self.use_scheduler:
1287
+ assert 'target' in self.scheduler_config
1288
+ scheduler = instantiate_from_config(self.scheduler_config)
1289
+
1290
+ print("Setting up LambdaLR scheduler...")
1291
+ scheduler = [
1292
+ {
1293
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1294
+ 'interval': 'step',
1295
+ 'frequency': 1
1296
+ }]
1297
+ return [opt], scheduler
1298
+ return opt
1299
+
1300
+ @torch.no_grad()
1301
+ def to_rgb(self, x):
1302
+ x = x.float()
1303
+ if not hasattr(self, "colorize"):
1304
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1305
+ x = nn.functional.conv2d(x, weight=self.colorize)
1306
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1307
+ return x
1308
+
1309
+
1310
+ class DiffusionWrapper(pl.LightningModule):
1311
+ def __init__(self, diff_model_config, conditioning_key):
1312
+ super().__init__()
1313
+ self.sequential_cross_attn = diff_model_config.pop("sequential_crossattn", False)
1314
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1315
+ self.conditioning_key = conditioning_key
1316
+ assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'hybrid-adm', 'crossattn-adm']
1317
+
1318
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None):
1319
+ if self.conditioning_key is None:
1320
+ out = self.diffusion_model(x, t)
1321
+ elif self.conditioning_key == 'concat':
1322
+ xc = torch.cat([x] + c_concat, dim=1)
1323
+ out = self.diffusion_model(xc, t)
1324
+ elif self.conditioning_key == 'crossattn':
1325
+ if not self.sequential_cross_attn:
1326
+ cc = torch.cat(c_crossattn, 1)
1327
+ else:
1328
+ cc = c_crossattn
1329
+ out = self.diffusion_model(x, t, context=cc)
1330
+ elif self.conditioning_key == 'hybrid':
1331
+ xc = torch.cat([x] + c_concat, dim=1)
1332
+ cc = torch.cat(c_crossattn, 1)
1333
+ out = self.diffusion_model(xc, t, context=cc)
1334
+ elif self.conditioning_key == 'hybrid-adm':
1335
+ assert c_adm is not None
1336
+ xc = torch.cat([x] + c_concat, dim=1)
1337
+ cc = torch.cat(c_crossattn, 1)
1338
+ out = self.diffusion_model(xc, t, context=cc, y=c_adm)
1339
+ elif self.conditioning_key == 'crossattn-adm':
1340
+ assert c_adm is not None
1341
+ cc = torch.cat(c_crossattn, 1)
1342
+ out = self.diffusion_model(x, t, context=cc, y=c_adm)
1343
+ elif self.conditioning_key == 'adm':
1344
+ cc = c_crossattn[0]
1345
+ out = self.diffusion_model(x, t, y=cc)
1346
+ else:
1347
+ raise NotImplementedError()
1348
+
1349
+ return out
1350
+
1351
+
1352
+ class LatentUpscaleDiffusion(LatentDiffusion):
1353
+ def __init__(self, *args, low_scale_config, low_scale_key="LR", noise_level_key=None, **kwargs):
1354
+ super().__init__(*args, **kwargs)
1355
+ # assumes that neither the cond_stage nor the low_scale_model contain trainable params
1356
+ assert not self.cond_stage_trainable
1357
+ self.instantiate_low_stage(low_scale_config)
1358
+ self.low_scale_key = low_scale_key
1359
+ self.noise_level_key = noise_level_key
1360
+
1361
+ def instantiate_low_stage(self, config):
1362
+ model = instantiate_from_config(config)
1363
+ self.low_scale_model = model.eval()
1364
+ self.low_scale_model.train = disabled_train
1365
+ for param in self.low_scale_model.parameters():
1366
+ param.requires_grad = False
1367
+
1368
+ @torch.no_grad()
1369
+ def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
1370
+ if not log_mode:
1371
+ z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
1372
+ else:
1373
+ z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1374
+ force_c_encode=True, return_original_cond=True, bs=bs)
1375
+ x_low = batch[self.low_scale_key][:bs]
1376
+ x_low = rearrange(x_low, 'b h w c -> b c h w')
1377
+ x_low = x_low.to(memory_format=torch.contiguous_format).float()
1378
+ zx, noise_level = self.low_scale_model(x_low)
1379
+ if self.noise_level_key is not None:
1380
+ # get noise level from batch instead, e.g. when extracting a custom noise level for bsr
1381
+ raise NotImplementedError('TODO')
1382
+
1383
+ all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level}
1384
+ if log_mode:
1385
+ # TODO: maybe disable if too expensive
1386
+ x_low_rec = self.low_scale_model.decode(zx)
1387
+ return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level
1388
+ return z, all_conds
1389
+
1390
+ @torch.no_grad()
1391
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1392
+ plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
1393
+ unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
1394
+ **kwargs):
1395
+ ema_scope = self.ema_scope if use_ema_scope else nullcontext
1396
+ use_ddim = ddim_steps is not None
1397
+
1398
+ log = dict()
1399
+ z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,
1400
+ log_mode=True)
1401
+ N = min(x.shape[0], N)
1402
+ n_row = min(x.shape[0], n_row)
1403
+ log["inputs"] = x
1404
+ log["reconstruction"] = xrec
1405
+ log["x_lr"] = x_low
1406
+ log[f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}"] = x_low_rec
1407
+ if self.model.conditioning_key is not None:
1408
+ if hasattr(self.cond_stage_model, "decode"):
1409
+ xc = self.cond_stage_model.decode(c)
1410
+ log["conditioning"] = xc
1411
+ elif self.cond_stage_key in ["caption", "txt"]:
1412
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
1413
+ log["conditioning"] = xc
1414
+ elif self.cond_stage_key in ['class_label', 'cls']:
1415
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
1416
+ log['conditioning'] = xc
1417
+ elif isimage(xc):
1418
+ log["conditioning"] = xc
1419
+ if ismap(xc):
1420
+ log["original_conditioning"] = self.to_rgb(xc)
1421
+
1422
+ if plot_diffusion_rows:
1423
+ # get diffusion row
1424
+ diffusion_row = list()
1425
+ z_start = z[:n_row]
1426
+ for t in range(self.num_timesteps):
1427
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1428
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1429
+ t = t.to(self.device).long()
1430
+ noise = torch.randn_like(z_start)
1431
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1432
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1433
+
1434
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1435
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1436
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1437
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1438
+ log["diffusion_row"] = diffusion_grid
1439
+
1440
+ if sample:
1441
+ # get denoise row
1442
+ with ema_scope("Sampling"):
1443
+ samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1444
+ ddim_steps=ddim_steps, eta=ddim_eta)
1445
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1446
+ x_samples = self.decode_first_stage(samples)
1447
+ log["samples"] = x_samples
1448
+ if plot_denoise_rows:
1449
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1450
+ log["denoise_row"] = denoise_grid
1451
+
1452
+ if unconditional_guidance_scale > 1.0:
1453
+ uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
1454
+ # TODO explore better "unconditional" choices for the other keys
1455
+ # maybe guide away from empty text label and highest noise level and maximally degraded zx?
1456
+ uc = dict()
1457
+ for k in c:
1458
+ if k == "c_crossattn":
1459
+ assert isinstance(c[k], list) and len(c[k]) == 1
1460
+ uc[k] = [uc_tmp]
1461
+ elif k == "c_adm": # todo: only run with text-based guidance?
1462
+ assert isinstance(c[k], torch.Tensor)
1463
+ #uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level
1464
+ uc[k] = c[k]
1465
+ elif isinstance(c[k], list):
1466
+ uc[k] = [c[k][i] for i in range(len(c[k]))]
1467
+ else:
1468
+ uc[k] = c[k]
1469
+
1470
+ with ema_scope("Sampling with classifier-free guidance"):
1471
+ samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1472
+ ddim_steps=ddim_steps, eta=ddim_eta,
1473
+ unconditional_guidance_scale=unconditional_guidance_scale,
1474
+ unconditional_conditioning=uc,
1475
+ )
1476
+ x_samples_cfg = self.decode_first_stage(samples_cfg)
1477
+ log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
1478
+
1479
+ if plot_progressive_rows:
1480
+ with ema_scope("Plotting Progressives"):
1481
+ img, progressives = self.progressive_denoising(c,
1482
+ shape=(self.channels, self.image_size, self.image_size),
1483
+ batch_size=N)
1484
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1485
+ log["progressive_row"] = prog_row
1486
+
1487
+ return log
1488
+
1489
+
1490
+ class LatentFinetuneDiffusion(LatentDiffusion):
1491
+ """
1492
+ Basis for different finetunas, such as inpainting or depth2image
1493
+ To disable finetuning mode, set finetune_keys to None
1494
+ """
1495
+
1496
+ def __init__(self,
1497
+ concat_keys: tuple,
1498
+ finetune_keys=("model.diffusion_model.input_blocks.0.0.weight",
1499
+ "model_ema.diffusion_modelinput_blocks00weight"
1500
+ ),
1501
+ keep_finetune_dims=4,
1502
+ # if model was trained without concat mode before and we would like to keep these channels
1503
+ c_concat_log_start=None, # to log reconstruction of c_concat codes
1504
+ c_concat_log_end=None,
1505
+ *args, **kwargs
1506
+ ):
1507
+ ckpt_path = kwargs.pop("ckpt_path", None)
1508
+ ignore_keys = kwargs.pop("ignore_keys", list())
1509
+ super().__init__(*args, **kwargs)
1510
+ self.finetune_keys = finetune_keys
1511
+ self.concat_keys = concat_keys
1512
+ self.keep_dims = keep_finetune_dims
1513
+ self.c_concat_log_start = c_concat_log_start
1514
+ self.c_concat_log_end = c_concat_log_end
1515
+ if exists(self.finetune_keys): assert exists(ckpt_path), 'can only finetune from a given checkpoint'
1516
+ if exists(ckpt_path):
1517
+ self.init_from_ckpt(ckpt_path, ignore_keys)
1518
+
1519
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
1520
+ sd = torch.load(path, map_location="cpu")
1521
+ if "state_dict" in list(sd.keys()):
1522
+ sd = sd["state_dict"]
1523
+ keys = list(sd.keys())
1524
+ for k in keys:
1525
+ for ik in ignore_keys:
1526
+ if k.startswith(ik):
1527
+ print("Deleting key {} from state_dict.".format(k))
1528
+ del sd[k]
1529
+
1530
+ # make it explicit, finetune by including extra input channels
1531
+ if exists(self.finetune_keys) and k in self.finetune_keys:
1532
+ new_entry = None
1533
+ for name, param in self.named_parameters():
1534
+ if name in self.finetune_keys:
1535
+ print(
1536
+ f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only")
1537
+ new_entry = torch.zeros_like(param) # zero init
1538
+ assert exists(new_entry), 'did not find matching parameter to modify'
1539
+ new_entry[:, :self.keep_dims, ...] = sd[k]
1540
+ sd[k] = new_entry
1541
+
1542
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
1543
+ sd, strict=False)
1544
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
1545
+ if len(missing) > 0:
1546
+ print(f"Missing Keys: {missing}")
1547
+ if len(unexpected) > 0:
1548
+ print(f"Unexpected Keys: {unexpected}")
1549
+
1550
+ @torch.no_grad()
1551
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1552
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1553
+ plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
1554
+ use_ema_scope=True,
1555
+ **kwargs):
1556
+ ema_scope = self.ema_scope if use_ema_scope else nullcontext
1557
+ use_ddim = ddim_steps is not None
1558
+
1559
+ log = dict()
1560
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, bs=N, return_first_stage_outputs=True)
1561
+ c_cat, c = c["c_concat"][0], c["c_crossattn"][0]
1562
+ N = min(x.shape[0], N)
1563
+ n_row = min(x.shape[0], n_row)
1564
+ log["inputs"] = x
1565
+ log["reconstruction"] = xrec
1566
+ if self.model.conditioning_key is not None:
1567
+ if hasattr(self.cond_stage_model, "decode"):
1568
+ xc = self.cond_stage_model.decode(c)
1569
+ log["conditioning"] = xc
1570
+ elif self.cond_stage_key in ["caption", "txt"]:
1571
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
1572
+ log["conditioning"] = xc
1573
+ elif self.cond_stage_key in ['class_label', 'cls']:
1574
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
1575
+ log['conditioning'] = xc
1576
+ elif isimage(xc):
1577
+ log["conditioning"] = xc
1578
+ if ismap(xc):
1579
+ log["original_conditioning"] = self.to_rgb(xc)
1580
+
1581
+ if not (self.c_concat_log_start is None and self.c_concat_log_end is None):
1582
+ log["c_concat_decoded"] = self.decode_first_stage(c_cat[:, self.c_concat_log_start:self.c_concat_log_end])
1583
+
1584
+ if plot_diffusion_rows:
1585
+ # get diffusion row
1586
+ diffusion_row = list()
1587
+ z_start = z[:n_row]
1588
+ for t in range(self.num_timesteps):
1589
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1590
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1591
+ t = t.to(self.device).long()
1592
+ noise = torch.randn_like(z_start)
1593
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1594
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1595
+
1596
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1597
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1598
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1599
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1600
+ log["diffusion_row"] = diffusion_grid
1601
+
1602
+ if sample:
1603
+ # get denoise row
1604
+ with ema_scope("Sampling"):
1605
+ samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
1606
+ batch_size=N, ddim=use_ddim,
1607
+ ddim_steps=ddim_steps, eta=ddim_eta)
1608
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1609
+ x_samples = self.decode_first_stage(samples)
1610
+ log["samples"] = x_samples
1611
+ if plot_denoise_rows:
1612
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1613
+ log["denoise_row"] = denoise_grid
1614
+
1615
+ if unconditional_guidance_scale > 1.0:
1616
+ uc_cross = self.get_unconditional_conditioning(N, unconditional_guidance_label)
1617
+ uc_cat = c_cat
1618
+ uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
1619
+ with ema_scope("Sampling with classifier-free guidance"):
1620
+ samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
1621
+ batch_size=N, ddim=use_ddim,
1622
+ ddim_steps=ddim_steps, eta=ddim_eta,
1623
+ unconditional_guidance_scale=unconditional_guidance_scale,
1624
+ unconditional_conditioning=uc_full,
1625
+ )
1626
+ x_samples_cfg = self.decode_first_stage(samples_cfg)
1627
+ log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
1628
+
1629
+ return log
1630
+
1631
+
1632
+ class LatentInpaintDiffusion(LatentFinetuneDiffusion):
1633
+ """
1634
+ can either run as pure inpainting model (only concat mode) or with mixed conditionings,
1635
+ e.g. mask as concat and text via cross-attn.
1636
+ To disable finetuning mode, set finetune_keys to None
1637
+ """
1638
+
1639
+ def __init__(self,
1640
+ concat_keys=("mask", "masked_image"),
1641
+ masked_image_key="masked_image",
1642
+ *args, **kwargs
1643
+ ):
1644
+ super().__init__(concat_keys, *args, **kwargs)
1645
+ self.masked_image_key = masked_image_key
1646
+ assert self.masked_image_key in concat_keys
1647
+
1648
+ @torch.no_grad()
1649
+ def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
1650
+ # note: restricted to non-trainable encoders currently
1651
+ assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for inpainting'
1652
+ z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1653
+ force_c_encode=True, return_original_cond=True, bs=bs)
1654
+
1655
+ assert exists(self.concat_keys)
1656
+ c_cat = list()
1657
+ for ck in self.concat_keys:
1658
+ cc = rearrange(batch[ck], 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
1659
+ if bs is not None:
1660
+ cc = cc[:bs]
1661
+ cc = cc.to(self.device)
1662
+ bchw = z.shape
1663
+ if ck != self.masked_image_key:
1664
+ cc = torch.nn.functional.interpolate(cc, size=bchw[-2:])
1665
+ else:
1666
+ cc = self.get_first_stage_encoding(self.encode_first_stage(cc))
1667
+ c_cat.append(cc)
1668
+ c_cat = torch.cat(c_cat, dim=1)
1669
+ all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
1670
+ if return_first_stage_outputs:
1671
+ return z, all_conds, x, xrec, xc
1672
+ return z, all_conds
1673
+
1674
+ @torch.no_grad()
1675
+ def log_images(self, *args, **kwargs):
1676
+ log = super(LatentInpaintDiffusion, self).log_images(*args, **kwargs)
1677
+ log["masked_image"] = rearrange(args[0]["masked_image"],
1678
+ 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
1679
+ return log
1680
+
1681
+
1682
+ class LatentDepth2ImageDiffusion(LatentFinetuneDiffusion):
1683
+ """
1684
+ condition on monocular depth estimation
1685
+ """
1686
+
1687
+ def __init__(self, depth_stage_config, concat_keys=("midas_in",), *args, **kwargs):
1688
+ super().__init__(concat_keys=concat_keys, *args, **kwargs)
1689
+ self.depth_model = instantiate_from_config(depth_stage_config)
1690
+ self.depth_stage_key = concat_keys[0]
1691
+
1692
+ @torch.no_grad()
1693
+ def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
1694
+ # note: restricted to non-trainable encoders currently
1695
+ assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for depth2img'
1696
+ z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1697
+ force_c_encode=True, return_original_cond=True, bs=bs)
1698
+
1699
+ assert exists(self.concat_keys)
1700
+ assert len(self.concat_keys) == 1
1701
+ c_cat = list()
1702
+ for ck in self.concat_keys:
1703
+ cc = batch[ck]
1704
+ if bs is not None:
1705
+ cc = cc[:bs]
1706
+ cc = cc.to(self.device)
1707
+ cc = self.depth_model(cc)
1708
+ cc = torch.nn.functional.interpolate(
1709
+ cc,
1710
+ size=z.shape[2:],
1711
+ mode="bicubic",
1712
+ align_corners=False,
1713
+ )
1714
+
1715
+ depth_min, depth_max = torch.amin(cc, dim=[1, 2, 3], keepdim=True), torch.amax(cc, dim=[1, 2, 3],
1716
+ keepdim=True)
1717
+ cc = 2. * (cc - depth_min) / (depth_max - depth_min + 0.001) - 1.
1718
+ c_cat.append(cc)
1719
+ c_cat = torch.cat(c_cat, dim=1)
1720
+ all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
1721
+ if return_first_stage_outputs:
1722
+ return z, all_conds, x, xrec, xc
1723
+ return z, all_conds
1724
+
1725
+ @torch.no_grad()
1726
+ def log_images(self, *args, **kwargs):
1727
+ log = super().log_images(*args, **kwargs)
1728
+ depth = self.depth_model(args[0][self.depth_stage_key])
1729
+ depth_min, depth_max = torch.amin(depth, dim=[1, 2, 3], keepdim=True), \
1730
+ torch.amax(depth, dim=[1, 2, 3], keepdim=True)
1731
+ log["depth"] = 2. * (depth - depth_min) / (depth_max - depth_min) - 1.
1732
+ return log
1733
+
1734
+
1735
+ class LatentUpscaleFinetuneDiffusion(LatentFinetuneDiffusion):
1736
+ """
1737
+ condition on low-res image (and optionally on some spatial noise augmentation)
1738
+ """
1739
+ def __init__(self, concat_keys=("lr",), reshuffle_patch_size=None,
1740
+ low_scale_config=None, low_scale_key=None, *args, **kwargs):
1741
+ super().__init__(concat_keys=concat_keys, *args, **kwargs)
1742
+ self.reshuffle_patch_size = reshuffle_patch_size
1743
+ self.low_scale_model = None
1744
+ if low_scale_config is not None:
1745
+ print("Initializing a low-scale model")
1746
+ assert exists(low_scale_key)
1747
+ self.instantiate_low_stage(low_scale_config)
1748
+ self.low_scale_key = low_scale_key
1749
+
1750
+ def instantiate_low_stage(self, config):
1751
+ model = instantiate_from_config(config)
1752
+ self.low_scale_model = model.eval()
1753
+ self.low_scale_model.train = disabled_train
1754
+ for param in self.low_scale_model.parameters():
1755
+ param.requires_grad = False
1756
+
1757
+ @torch.no_grad()
1758
+ def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
1759
+ # note: restricted to non-trainable encoders currently
1760
+ assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for upscaling-ft'
1761
+ z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1762
+ force_c_encode=True, return_original_cond=True, bs=bs)
1763
+
1764
+ assert exists(self.concat_keys)
1765
+ assert len(self.concat_keys) == 1
1766
+ # optionally make spatial noise_level here
1767
+ c_cat = list()
1768
+ noise_level = None
1769
+ for ck in self.concat_keys:
1770
+ cc = batch[ck]
1771
+ cc = rearrange(cc, 'b h w c -> b c h w')
1772
+ if exists(self.reshuffle_patch_size):
1773
+ assert isinstance(self.reshuffle_patch_size, int)
1774
+ cc = rearrange(cc, 'b c (p1 h) (p2 w) -> b (p1 p2 c) h w',
1775
+ p1=self.reshuffle_patch_size, p2=self.reshuffle_patch_size)
1776
+ if bs is not None:
1777
+ cc = cc[:bs]
1778
+ cc = cc.to(self.device)
1779
+ if exists(self.low_scale_model) and ck == self.low_scale_key:
1780
+ cc, noise_level = self.low_scale_model(cc)
1781
+ c_cat.append(cc)
1782
+ c_cat = torch.cat(c_cat, dim=1)
1783
+ if exists(noise_level):
1784
+ all_conds = {"c_concat": [c_cat], "c_crossattn": [c], "c_adm": noise_level}
1785
+ else:
1786
+ all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
1787
+ if return_first_stage_outputs:
1788
+ return z, all_conds, x, xrec, xc
1789
+ return z, all_conds
1790
+
1791
+ @torch.no_grad()
1792
+ def log_images(self, *args, **kwargs):
1793
+ log = super().log_images(*args, **kwargs)
1794
+ log["lr"] = rearrange(args[0]["lr"], 'b h w c -> b c h w')
1795
+ return log
ldm/models/diffusion/dpm_solver/__init__.py ADDED
@@ -0,0 +1 @@
 
1
+ from .sampler import DPMSolverSampler
ldm/models/diffusion/dpm_solver/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (212 Bytes). View file
ldm/models/diffusion/dpm_solver/__pycache__/dpm_solver.cpython-39.pyc ADDED
Binary file (51.6 kB). View file
ldm/models/diffusion/dpm_solver/__pycache__/sampler.cpython-39.pyc ADDED
Binary file (2.79 kB). View file
ldm/models/diffusion/dpm_solver/dpm_solver.py ADDED
@@ -0,0 +1,1154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import math
4
+ from tqdm import tqdm
5
+
6
+
7
+ class NoiseScheduleVP:
8
+ def __init__(
9
+ self,
10
+ schedule='discrete',
11
+ betas=None,
12
+ alphas_cumprod=None,
13
+ continuous_beta_0=0.1,
14
+ continuous_beta_1=20.,
15
+ ):
16
+ """Create a wrapper class for the forward SDE (VP type).
17
+ ***
18
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
19
+ We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
20
+ ***
21
+ The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
22
+ We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
23
+ Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
24
+ log_alpha_t = self.marginal_log_mean_coeff(t)
25
+ sigma_t = self.marginal_std(t)
26
+ lambda_t = self.marginal_lambda(t)
27
+ Moreover, as lambda(t) is an invertible function, we also support its inverse function:
28
+ t = self.inverse_lambda(lambda_t)
29
+ ===============================================================
30
+ We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
31
+ 1. For discrete-time DPMs:
32
+ For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
33
+ t_i = (i + 1) / N
34
+ e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
35
+ We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
36
+ Args:
37
+ betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
38
+ alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
39
+ Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
40
+ **Important**: Please pay special attention for the args for `alphas_cumprod`:
41
+ The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
42
+ q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
43
+ Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
44
+ alpha_{t_n} = \sqrt{\hat{alpha_n}},
45
+ and
46
+ log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
47
+ 2. For continuous-time DPMs:
48
+ We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
49
+ schedule are the default settings in DDPM and improved-DDPM:
50
+ Args:
51
+ beta_min: A `float` number. The smallest beta for the linear schedule.
52
+ beta_max: A `float` number. The largest beta for the linear schedule.
53
+ cosine_s: A `float` number. The hyperparameter in the cosine schedule.
54
+ cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
55
+ T: A `float` number. The ending time of the forward process.
56
+ ===============================================================
57
+ Args:
58
+ schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
59
+ 'linear' or 'cosine' for continuous-time DPMs.
60
+ Returns:
61
+ A wrapper object of the forward SDE (VP type).
62
+
63
+ ===============================================================
64
+ Example:
65
+ # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
66
+ >>> ns = NoiseScheduleVP('discrete', betas=betas)
67
+ # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
68
+ >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
69
+ # For continuous-time DPMs (VPSDE), linear schedule:
70
+ >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
71
+ """
72
+
73
+ if schedule not in ['discrete', 'linear', 'cosine']:
74
+ raise ValueError(
75
+ "Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(
76
+ schedule))
77
+
78
+ self.schedule = schedule
79
+ if schedule == 'discrete':
80
+ if betas is not None:
81
+ log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
82
+ else:
83
+ assert alphas_cumprod is not None
84
+ log_alphas = 0.5 * torch.log(alphas_cumprod)
85
+ self.total_N = len(log_alphas)
86
+ self.T = 1.
87
+ self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
88
+ self.log_alpha_array = log_alphas.reshape((1, -1,))
89
+ else:
90
+ self.total_N = 1000
91
+ self.beta_0 = continuous_beta_0
92
+ self.beta_1 = continuous_beta_1
93
+ self.cosine_s = 0.008
94
+ self.cosine_beta_max = 999.
95
+ self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (
96
+ 1. + self.cosine_s) / math.pi - self.cosine_s
97
+ self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
98
+ self.schedule = schedule
99
+ if schedule == 'cosine':
100
+ # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
101
+ # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
102
+ self.T = 0.9946
103
+ else:
104
+ self.T = 1.
105
+
106
+ def marginal_log_mean_coeff(self, t):
107
+ """
108
+ Compute log(alpha_t) of a given continuous-time label t in [0, T].
109
+ """
110
+ if self.schedule == 'discrete':
111
+ return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device),
112
+ self.log_alpha_array.to(t.device)).reshape((-1))
113
+ elif self.schedule == 'linear':
114
+ return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
115
+ elif self.schedule == 'cosine':
116
+ log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
117
+ log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
118
+ return log_alpha_t
119
+
120
+ def marginal_alpha(self, t):
121
+ """
122
+ Compute alpha_t of a given continuous-time label t in [0, T].
123
+ """
124
+ return torch.exp(self.marginal_log_mean_coeff(t))
125
+
126
+ def marginal_std(self, t):
127
+ """
128
+ Compute sigma_t of a given continuous-time label t in [0, T].
129
+ """
130
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
131
+
132
+ def marginal_lambda(self, t):
133
+ """
134
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
135
+ """
136
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
137
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
138
+ return log_mean_coeff - log_std
139
+
140
+ def inverse_lambda(self, lamb):
141
+ """
142
+ Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
143
+ """
144
+ if self.schedule == 'linear':
145
+ tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
146
+ Delta = self.beta_0 ** 2 + tmp
147
+ return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
148
+ elif self.schedule == 'discrete':
149
+ log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
150
+ t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]),
151
+ torch.flip(self.t_array.to(lamb.device), [1]))
152
+ return t.reshape((-1,))
153
+ else:
154
+ log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
155
+ t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (
156
+ 1. + self.cosine_s) / math.pi - self.cosine_s
157
+ t = t_fn(log_alpha)
158
+ return t
159
+
160
+
161
+ def model_wrapper(
162
+ model,
163
+ noise_schedule,
164
+ model_type="noise",
165
+ model_kwargs={},
166
+ guidance_type="uncond",
167
+ condition=None,
168
+ unconditional_condition=None,
169
+ guidance_scale=1.,
170
+ classifier_fn=None,
171
+ classifier_kwargs={},
172
+ ):
173
+ """Create a wrapper function for the noise prediction model.
174
+ DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
175
+ firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
176
+ We support four types of the diffusion model by setting `model_type`:
177
+ 1. "noise": noise prediction model. (Trained by predicting noise).
178
+ 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
179
+ 3. "v": velocity prediction model. (Trained by predicting the velocity).
180
+ The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
181
+ [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
182
+ arXiv preprint arXiv:2202.00512 (2022).
183
+ [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
184
+ arXiv preprint arXiv:2210.02303 (2022).
185
+
186
+ 4. "score": marginal score function. (Trained by denoising score matching).
187
+ Note that the score function and the noise prediction model follows a simple relationship:
188
+ ```
189
+ noise(x_t, t) = -sigma_t * score(x_t, t)
190
+ ```
191
+ We support three types of guided sampling by DPMs by setting `guidance_type`:
192
+ 1. "uncond": unconditional sampling by DPMs.
193
+ The input `model` has the following format:
194
+ ``
195
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
196
+ ``
197
+ 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
198
+ The input `model` has the following format:
199
+ ``
200
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
201
+ ``
202
+ The input `classifier_fn` has the following format:
203
+ ``
204
+ classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
205
+ ``
206
+ [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
207
+ in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
208
+ 3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
209
+ The input `model` has the following format:
210
+ ``
211
+ model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
212
+ ``
213
+ And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
214
+ [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
215
+ arXiv preprint arXiv:2207.12598 (2022).
216
+
217
+ The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
218
+ or continuous-time labels (i.e. epsilon to T).
219
+ We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
220
+ ``
221
+ def model_fn(x, t_continuous) -> noise:
222
+ t_input = get_model_input_time(t_continuous)
223
+ return noise_pred(model, x, t_input, **model_kwargs)
224
+ ``
225
+ where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
226
+ ===============================================================
227
+ Args:
228
+ model: A diffusion model with the corresponding format described above.
229
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
230
+ model_type: A `str`. The parameterization type of the diffusion model.
231
+ "noise" or "x_start" or "v" or "score".
232
+ model_kwargs: A `dict`. A dict for the other inputs of the model function.
233
+ guidance_type: A `str`. The type of the guidance for sampling.
234
+ "uncond" or "classifier" or "classifier-free".
235
+ condition: A pytorch tensor. The condition for the guided sampling.
236
+ Only used for "classifier" or "classifier-free" guidance type.
237
+ unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
238
+ Only used for "classifier-free" guidance type.
239
+ guidance_scale: A `float`. The scale for the guided sampling.
240
+ classifier_fn: A classifier function. Only used for the classifier guidance.
241
+ classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
242
+ Returns:
243
+ A noise prediction model that accepts the noised data and the continuous time as the inputs.
244
+ """
245
+
246
+ def get_model_input_time(t_continuous):
247
+ """
248
+ Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
249
+ For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
250
+ For continuous-time DPMs, we just use `t_continuous`.
251
+ """
252
+ if noise_schedule.schedule == 'discrete':
253
+ return (t_continuous - 1. / noise_schedule.total_N) * 1000.
254
+ else:
255
+ return t_continuous
256
+
257
+ def noise_pred_fn(x, t_continuous, cond=None):
258
+ if t_continuous.reshape((-1,)).shape[0] == 1:
259
+ t_continuous = t_continuous.expand((x.shape[0]))
260
+ t_input = get_model_input_time(t_continuous)
261
+ if cond is None:
262
+ output = model(x, t_input, **model_kwargs)
263
+ else:
264
+ output = model(x, t_input, cond, **model_kwargs)
265
+ if model_type == "noise":
266
+ return output
267
+ elif model_type == "x_start":
268
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
269
+ dims = x.dim()
270
+ return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
271
+ elif model_type == "v":
272
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
273
+ dims = x.dim()
274
+ return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
275
+ elif model_type == "score":
276
+ sigma_t = noise_schedule.marginal_std(t_continuous)
277
+ dims = x.dim()
278
+ return -expand_dims(sigma_t, dims) * output
279
+
280
+ def cond_grad_fn(x, t_input):
281
+ """
282
+ Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
283
+ """
284
+ with torch.enable_grad():
285
+ x_in = x.detach().requires_grad_(True)
286
+ log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
287
+ return torch.autograd.grad(log_prob.sum(), x_in)[0]
288
+
289
+ def model_fn(x, t_continuous):
290
+ """
291
+ The noise predicition model function that is used for DPM-Solver.
292
+ """
293
+ if t_continuous.reshape((-1,)).shape[0] == 1:
294
+ t_continuous = t_continuous.expand((x.shape[0]))
295
+ if guidance_type == "uncond":
296
+ return noise_pred_fn(x, t_continuous)
297
+ elif guidance_type == "classifier":
298
+ assert classifier_fn is not None
299
+ t_input = get_model_input_time(t_continuous)
300
+ cond_grad = cond_grad_fn(x, t_input)
301
+ sigma_t = noise_schedule.marginal_std(t_continuous)
302
+ noise = noise_pred_fn(x, t_continuous)
303
+ return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
304
+ elif guidance_type == "classifier-free":
305
+ if guidance_scale == 1. or unconditional_condition is None:
306
+ return noise_pred_fn(x, t_continuous, cond=condition)
307
+ else:
308
+ x_in = torch.cat([x] * 2)
309
+ t_in = torch.cat([t_continuous] * 2)
310
+ c_in = torch.cat([unconditional_condition, condition])
311
+ noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
312
+ return noise_uncond + guidance_scale * (noise - noise_uncond)
313
+
314
+ assert model_type in ["noise", "x_start", "v"]
315
+ assert guidance_type in ["uncond", "classifier", "classifier-free"]
316
+ return model_fn
317
+
318
+
319
+ class DPM_Solver:
320
+ def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):
321
+ """Construct a DPM-Solver.
322
+ We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0").
323
+ If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).
324
+ If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).
325
+ In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True.
326
+ The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.
327
+ Args:
328
+ model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):
329
+ ``
330
+ def model_fn(x, t_continuous):
331
+ return noise
332
+ ``
333
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
334
+ predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.
335
+ thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1].
336
+ max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.
337
+
338
+ [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.
339
+ """
340
+ self.model = model_fn
341
+ self.noise_schedule = noise_schedule
342
+ self.predict_x0 = predict_x0
343
+ self.thresholding = thresholding
344
+ self.max_val = max_val
345
+
346
+ def noise_prediction_fn(self, x, t):
347
+ """
348
+ Return the noise prediction model.
349
+ """
350
+ return self.model(x, t)
351
+
352
+ def data_prediction_fn(self, x, t):
353
+ """
354
+ Return the data prediction model (with thresholding).
355
+ """
356
+ noise = self.noise_prediction_fn(x, t)
357
+ dims = x.dim()
358
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
359
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
360
+ if self.thresholding:
361
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
362
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
363
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
364
+ x0 = torch.clamp(x0, -s, s) / s
365
+ return x0
366
+
367
+ def model_fn(self, x, t):
368
+ """
369
+ Convert the model to the noise prediction model or the data prediction model.
370
+ """
371
+ if self.predict_x0:
372
+ return self.data_prediction_fn(x, t)
373
+ else:
374
+ return self.noise_prediction_fn(x, t)
375
+
376
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
377
+ """Compute the intermediate time steps for sampling.
378
+ Args:
379
+ skip_type: A `str`. The type for the spacing of the time steps. We support three types:
380
+ - 'logSNR': uniform logSNR for the time steps.
381
+ - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
382
+ - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
383
+ t_T: A `float`. The starting time of the sampling (default is T).
384
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
385
+ N: A `int`. The total number of the spacing of the time steps.
386
+ device: A torch device.
387
+ Returns:
388
+ A pytorch tensor of the time steps, with the shape (N + 1,).
389
+ """
390
+ if skip_type == 'logSNR':
391
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
392
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
393
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
394
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
395
+ elif skip_type == 'time_uniform':
396
+ return torch.linspace(t_T, t_0, N + 1).to(device)
397
+ elif skip_type == 'time_quadratic':
398
+ t_order = 2
399
+ t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device)
400
+ return t
401
+ else:
402
+ raise ValueError(
403
+ "Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
404
+
405
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
406
+ """
407
+ Get the order of each step for sampling by the singlestep DPM-Solver.
408
+ We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
409
+ Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
410
+ - If order == 1:
411
+ We take `steps` of DPM-Solver-1 (i.e. DDIM).
412
+ - If order == 2:
413
+ - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.
414
+ - If steps % 2 == 0, we use K steps of DPM-Solver-2.
415
+ - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.
416
+ - If order == 3:
417
+ - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
418
+ - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.
419
+ - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.
420
+ - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.
421
+ ============================================
422
+ Args:
423
+ order: A `int`. The max order for the solver (2 or 3).
424
+ steps: A `int`. The total number of function evaluations (NFE).
425
+ skip_type: A `str`. The type for the spacing of the time steps. We support three types:
426
+ - 'logSNR': uniform logSNR for the time steps.
427
+ - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
428
+ - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
429
+ t_T: A `float`. The starting time of the sampling (default is T).
430
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
431
+ device: A torch device.
432
+ Returns:
433
+ orders: A list of the solver order of each step.
434
+ """
435
+ if order == 3:
436
+ K = steps // 3 + 1
437
+ if steps % 3 == 0:
438
+ orders = [3, ] * (K - 2) + [2, 1]
439
+ elif steps % 3 == 1:
440
+ orders = [3, ] * (K - 1) + [1]
441
+ else:
442
+ orders = [3, ] * (K - 1) + [2]
443
+ elif order == 2:
444
+ if steps % 2 == 0:
445
+ K = steps // 2
446
+ orders = [2, ] * K
447
+ else:
448
+ K = steps // 2 + 1
449
+ orders = [2, ] * (K - 1) + [1]
450
+ elif order == 1:
451
+ K = 1
452
+ orders = [1, ] * steps
453
+ else:
454
+ raise ValueError("'order' must be '1' or '2' or '3'.")
455
+ if skip_type == 'logSNR':
456
+ # To reproduce the results in DPM-Solver paper
457
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
458
+ else:
459
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[
460
+ torch.cumsum(torch.tensor([0, ] + orders)).to(device)]
461
+ return timesteps_outer, orders
462
+
463
+ def denoise_to_zero_fn(self, x, s):
464
+ """
465
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
466
+ """
467
+ return self.data_prediction_fn(x, s)
468
+
469
+ def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
470
+ """
471
+ DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
472
+ Args:
473
+ x: A pytorch tensor. The initial value at time `s`.
474
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
475
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
476
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
477
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
478
+ return_intermediate: A `bool`. If true, also return the model value at time `s`.
479
+ Returns:
480
+ x_t: A pytorch tensor. The approximated solution at time `t`.
481
+ """
482
+ ns = self.noise_schedule
483
+ dims = x.dim()
484
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
485
+ h = lambda_t - lambda_s
486
+ log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)
487
+ sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)
488
+ alpha_t = torch.exp(log_alpha_t)
489
+
490
+ if self.predict_x0:
491
+ phi_1 = torch.expm1(-h)
492
+ if model_s is None:
493
+ model_s = self.model_fn(x, s)
494
+ x_t = (
495
+ expand_dims(sigma_t / sigma_s, dims) * x
496
+ - expand_dims(alpha_t * phi_1, dims) * model_s
497
+ )
498
+ if return_intermediate:
499
+ return x_t, {'model_s': model_s}
500
+ else:
501
+ return x_t
502
+ else:
503
+ phi_1 = torch.expm1(h)
504
+ if model_s is None:
505
+ model_s = self.model_fn(x, s)
506
+ x_t = (
507
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
508
+ - expand_dims(sigma_t * phi_1, dims) * model_s
509
+ )
510
+ if return_intermediate:
511
+ return x_t, {'model_s': model_s}
512
+ else:
513
+ return x_t
514
+
515
+ def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,
516
+ solver_type='dpm_solver'):
517
+ """
518
+ Singlestep solver DPM-Solver-2 from time `s` to time `t`.
519
+ Args:
520
+ x: A pytorch tensor. The initial value at time `s`.
521
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
522
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
523
+ r1: A `float`. The hyperparameter of the second-order solver.
524
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
525
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
526
+ return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
527
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
528
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
529
+ Returns:
530
+ x_t: A pytorch tensor. The approximated solution at time `t`.
531
+ """
532
+ if solver_type not in ['dpm_solver', 'taylor']:
533
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
534
+ if r1 is None:
535
+ r1 = 0.5
536
+ ns = self.noise_schedule
537
+ dims = x.dim()
538
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
539
+ h = lambda_t - lambda_s
540
+ lambda_s1 = lambda_s + r1 * h
541
+ s1 = ns.inverse_lambda(lambda_s1)
542
+ log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(
543
+ s1), ns.marginal_log_mean_coeff(t)
544
+ sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
545
+ alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
546
+
547
+ if self.predict_x0:
548
+ phi_11 = torch.expm1(-r1 * h)
549
+ phi_1 = torch.expm1(-h)
550
+
551
+ if model_s is None:
552
+ model_s = self.model_fn(x, s)
553
+ x_s1 = (
554
+ expand_dims(sigma_s1 / sigma_s, dims) * x
555
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
556
+ )
557
+ model_s1 = self.model_fn(x_s1, s1)
558
+ if solver_type == 'dpm_solver':
559
+ x_t = (
560
+ expand_dims(sigma_t / sigma_s, dims) * x
561
+ - expand_dims(alpha_t * phi_1, dims) * model_s
562
+ - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
563
+ )
564
+ elif solver_type == 'taylor':
565
+ x_t = (
566
+ expand_dims(sigma_t / sigma_s, dims) * x
567
+ - expand_dims(alpha_t * phi_1, dims) * model_s
568
+ + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (
569
+ model_s1 - model_s)
570
+ )
571
+ else:
572
+ phi_11 = torch.expm1(r1 * h)
573
+ phi_1 = torch.expm1(h)
574
+
575
+ if model_s is None:
576
+ model_s = self.model_fn(x, s)
577
+ x_s1 = (
578
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
579
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
580
+ )
581
+ model_s1 = self.model_fn(x_s1, s1)
582
+ if solver_type == 'dpm_solver':
583
+ x_t = (
584
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
585
+ - expand_dims(sigma_t * phi_1, dims) * model_s
586
+ - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
587
+ )
588
+ elif solver_type == 'taylor':
589
+ x_t = (
590
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
591
+ - expand_dims(sigma_t * phi_1, dims) * model_s
592
+ - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
593
+ )
594
+ if return_intermediate:
595
+ return x_t, {'model_s': model_s, 'model_s1': model_s1}
596
+ else:
597
+ return x_t
598
+
599
+ def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,
600
+ return_intermediate=False, solver_type='dpm_solver'):
601
+ """
602
+ Singlestep solver DPM-Solver-3 from time `s` to time `t`.
603
+ Args:
604
+ x: A pytorch tensor. The initial value at time `s`.
605
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
606
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
607
+ r1: A `float`. The hyperparameter of the third-order solver.
608
+ r2: A `float`. The hyperparameter of the third-order solver.
609
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
610
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
611
+ model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
612
+ If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
613
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
614
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
615
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
616
+ Returns:
617
+ x_t: A pytorch tensor. The approximated solution at time `t`.
618
+ """
619
+ if solver_type not in ['dpm_solver', 'taylor']:
620
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
621
+ if r1 is None:
622
+ r1 = 1. / 3.
623
+ if r2 is None:
624
+ r2 = 2. / 3.
625
+ ns = self.noise_schedule
626
+ dims = x.dim()
627
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
628
+ h = lambda_t - lambda_s
629
+ lambda_s1 = lambda_s + r1 * h
630
+ lambda_s2 = lambda_s + r2 * h
631
+ s1 = ns.inverse_lambda(lambda_s1)
632
+ s2 = ns.inverse_lambda(lambda_s2)
633
+ log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(
634
+ s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
635
+ sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(
636
+ s2), ns.marginal_std(t)
637
+ alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
638
+
639
+ if self.predict_x0:
640
+ phi_11 = torch.expm1(-r1 * h)
641
+ phi_12 = torch.expm1(-r2 * h)
642
+ phi_1 = torch.expm1(-h)
643
+ phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
644
+ phi_2 = phi_1 / h + 1.
645
+ phi_3 = phi_2 / h - 0.5
646
+
647
+ if model_s is None:
648
+ model_s = self.model_fn(x, s)
649
+ if model_s1 is None:
650
+ x_s1 = (
651
+ expand_dims(sigma_s1 / sigma_s, dims) * x
652
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
653
+ )
654
+ model_s1 = self.model_fn(x_s1, s1)
655
+ x_s2 = (
656
+ expand_dims(sigma_s2 / sigma_s, dims) * x
657
+ - expand_dims(alpha_s2 * phi_12, dims) * model_s
658
+ + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
659
+ )
660
+ model_s2 = self.model_fn(x_s2, s2)
661
+ if solver_type == 'dpm_solver':
662
+ x_t = (
663
+ expand_dims(sigma_t / sigma_s, dims) * x
664
+ - expand_dims(alpha_t * phi_1, dims) * model_s
665
+ + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
666
+ )
667
+ elif solver_type == 'taylor':
668
+ D1_0 = (1. / r1) * (model_s1 - model_s)
669
+ D1_1 = (1. / r2) * (model_s2 - model_s)
670
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
671
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
672
+ x_t = (
673
+ expand_dims(sigma_t / sigma_s, dims) * x
674
+ - expand_dims(alpha_t * phi_1, dims) * model_s
675
+ + expand_dims(alpha_t * phi_2, dims) * D1
676
+ - expand_dims(alpha_t * phi_3, dims) * D2
677
+ )
678
+ else:
679
+ phi_11 = torch.expm1(r1 * h)
680
+ phi_12 = torch.expm1(r2 * h)
681
+ phi_1 = torch.expm1(h)
682
+ phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.
683
+ phi_2 = phi_1 / h - 1.
684
+ phi_3 = phi_2 / h - 0.5
685
+
686
+ if model_s is None:
687
+ model_s = self.model_fn(x, s)
688
+ if model_s1 is None:
689
+ x_s1 = (
690
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
691
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
692
+ )
693
+ model_s1 = self.model_fn(x_s1, s1)
694
+ x_s2 = (
695
+ expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x
696
+ - expand_dims(sigma_s2 * phi_12, dims) * model_s
697
+ - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)
698
+ )
699
+ model_s2 = self.model_fn(x_s2, s2)
700
+ if solver_type == 'dpm_solver':
701
+ x_t = (
702
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
703
+ - expand_dims(sigma_t * phi_1, dims) * model_s
704
+ - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)
705
+ )
706
+ elif solver_type == 'taylor':
707
+ D1_0 = (1. / r1) * (model_s1 - model_s)
708
+ D1_1 = (1. / r2) * (model_s2 - model_s)
709
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
710
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
711
+ x_t = (
712
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
713
+ - expand_dims(sigma_t * phi_1, dims) * model_s
714
+ - expand_dims(sigma_t * phi_2, dims) * D1
715
+ - expand_dims(sigma_t * phi_3, dims) * D2
716
+ )
717
+
718
+ if return_intermediate:
719
+ return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}
720
+ else:
721
+ return x_t
722
+
723
+ def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"):
724
+ """
725
+ Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
726
+ Args:
727
+ x: A pytorch tensor. The initial value at time `s`.
728
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
729
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
730
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
731
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
732
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
733
+ Returns:
734
+ x_t: A pytorch tensor. The approximated solution at time `t`.
735
+ """
736
+ if solver_type not in ['dpm_solver', 'taylor']:
737
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
738
+ ns = self.noise_schedule
739
+ dims = x.dim()
740
+ model_prev_1, model_prev_0 = model_prev_list
741
+ t_prev_1, t_prev_0 = t_prev_list
742
+ lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(
743
+ t_prev_0), ns.marginal_lambda(t)
744
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
745
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
746
+ alpha_t = torch.exp(log_alpha_t)
747
+
748
+ h_0 = lambda_prev_0 - lambda_prev_1
749
+ h = lambda_t - lambda_prev_0
750
+ r0 = h_0 / h
751
+ D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
752
+ if self.predict_x0:
753
+ if solver_type == 'dpm_solver':
754
+ x_t = (
755
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
756
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
757
+ - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0
758
+ )
759
+ elif solver_type == 'taylor':
760
+ x_t = (
761
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
762
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
763
+ + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0
764
+ )
765
+ else:
766
+ if solver_type == 'dpm_solver':
767
+ x_t = (
768
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
769
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
770
+ - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0
771
+ )
772
+ elif solver_type == 'taylor':
773
+ x_t = (
774
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
775
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
776
+ - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0
777
+ )
778
+ return x_t
779
+
780
+ def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):
781
+ """
782
+ Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
783
+ Args:
784
+ x: A pytorch tensor. The initial value at time `s`.
785
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
786
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
787
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
788
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
789
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
790
+ Returns:
791
+ x_t: A pytorch tensor. The approximated solution at time `t`.
792
+ """
793
+ ns = self.noise_schedule
794
+ dims = x.dim()
795
+ model_prev_2, model_prev_1, model_prev_0 = model_prev_list
796
+ t_prev_2, t_prev_1, t_prev_0 = t_prev_list
797
+ lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(
798
+ t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
799
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
800
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
801
+ alpha_t = torch.exp(log_alpha_t)
802
+
803
+ h_1 = lambda_prev_1 - lambda_prev_2
804
+ h_0 = lambda_prev_0 - lambda_prev_1
805
+ h = lambda_t - lambda_prev_0
806
+ r0, r1 = h_0 / h, h_1 / h
807
+ D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
808
+ D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)
809
+ D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)
810
+ D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)
811
+ if self.predict_x0:
812
+ x_t = (
813
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
814
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
815
+ + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1
816
+ - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2
817
+ )
818
+ else:
819
+ x_t = (
820
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
821
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
822
+ - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1
823
+ - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2
824
+ )
825
+ return x_t
826
+
827
+ def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None,
828
+ r2=None):
829
+ """
830
+ Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
831
+ Args:
832
+ x: A pytorch tensor. The initial value at time `s`.
833
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
834
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
835
+ order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
836
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
837
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
838
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
839
+ r1: A `float`. The hyperparameter of the second-order or third-order solver.
840
+ r2: A `float`. The hyperparameter of the third-order solver.
841
+ Returns:
842
+ x_t: A pytorch tensor. The approximated solution at time `t`.
843
+ """
844
+ if order == 1:
845
+ return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)
846
+ elif order == 2:
847
+ return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate,
848
+ solver_type=solver_type, r1=r1)
849
+ elif order == 3:
850
+ return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate,
851
+ solver_type=solver_type, r1=r1, r2=r2)
852
+ else:
853
+ raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
854
+
855
+ def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):
856
+ """
857
+ Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
858
+ Args:
859
+ x: A pytorch tensor. The initial value at time `s`.
860
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
861
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
862
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
863
+ order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
864
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
865
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
866
+ Returns:
867
+ x_t: A pytorch tensor. The approximated solution at time `t`.
868
+ """
869
+ if order == 1:
870
+ return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])
871
+ elif order == 2:
872
+ return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
873
+ elif order == 3:
874
+ return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
875
+ else:
876
+ raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
877
+
878
+ def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5,
879
+ solver_type='dpm_solver'):
880
+ """
881
+ The adaptive step size solver based on singlestep DPM-Solver.
882
+ Args:
883
+ x: A pytorch tensor. The initial value at time `t_T`.
884
+ order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.
885
+ t_T: A `float`. The starting time of the sampling (default is T).
886
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
887
+ h_init: A `float`. The initial step size (for logSNR).
888
+ atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].
889
+ rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.
890
+ theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].
891
+ t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the
892
+ current time and `t_0` is less than `t_err`. The default setting is 1e-5.
893
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
894
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
895
+ Returns:
896
+ x_0: A pytorch tensor. The approximated solution at time `t_0`.
897
+ [1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021.
898
+ """
899
+ ns = self.noise_schedule
900
+ s = t_T * torch.ones((x.shape[0],)).to(x)
901
+ lambda_s = ns.marginal_lambda(s)
902
+ lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))
903
+ h = h_init * torch.ones_like(s).to(x)
904
+ x_prev = x
905
+ nfe = 0
906
+ if order == 2:
907
+ r1 = 0.5
908
+ lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)
909
+ higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
910
+ solver_type=solver_type,
911
+ **kwargs)
912
+ elif order == 3:
913
+ r1, r2 = 1. / 3., 2. / 3.
914
+ lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
915
+ return_intermediate=True,
916
+ solver_type=solver_type)
917
+ higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2,
918
+ solver_type=solver_type,
919
+ **kwargs)
920
+ else:
921
+ raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order))
922
+ while torch.abs((s - t_0)).mean() > t_err:
923
+ t = ns.inverse_lambda(lambda_s + h)
924
+ x_lower, lower_noise_kwargs = lower_update(x, s, t)
925
+ x_higher = higher_update(x, s, t, **lower_noise_kwargs)
926
+ delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))
927
+ norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))
928
+ E = norm_fn((x_higher - x_lower) / delta).max()
929
+ if torch.all(E <= 1.):
930
+ x = x_higher
931
+ s = t
932
+ x_prev = x_lower
933
+ lambda_s = ns.marginal_lambda(s)
934
+ h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)
935
+ nfe += order
936
+ print('adaptive solver nfe', nfe)
937
+ return x
938
+
939
+ def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',
940
+ method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
941
+ atol=0.0078, rtol=0.05,
942
+ ):
943
+ """
944
+ Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
945
+ =====================================================
946
+ We support the following algorithms for both noise prediction model and data prediction model:
947
+ - 'singlestep':
948
+ Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver.
949
+ We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).
950
+ The total number of function evaluations (NFE) == `steps`.
951
+ Given a fixed NFE == `steps`, the sampling procedure is:
952
+ - If `order` == 1:
953
+ - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).
954
+ - If `order` == 2:
955
+ - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.
956
+ - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.
957
+ - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
958
+ - If `order` == 3:
959
+ - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
960
+ - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
961
+ - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.
962
+ - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.
963
+ - 'multistep':
964
+ Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.
965
+ We initialize the first `order` values by lower order multistep solvers.
966
+ Given a fixed NFE == `steps`, the sampling procedure is:
967
+ Denote K = steps.
968
+ - If `order` == 1:
969
+ - We use K steps of DPM-Solver-1 (i.e. DDIM).
970
+ - If `order` == 2:
971
+ - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.
972
+ - If `order` == 3:
973
+ - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.
974
+ - 'singlestep_fixed':
975
+ Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).
976
+ We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.
977
+ - 'adaptive':
978
+ Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper).
979
+ We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.
980
+ You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs
981
+ (NFE) and the sample quality.
982
+ - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.
983
+ - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.
984
+ =====================================================
985
+ Some advices for choosing the algorithm:
986
+ - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:
987
+ Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`.
988
+ e.g.
989
+ >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)
990
+ >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,
991
+ skip_type='time_uniform', method='singlestep')
992
+ - For **guided sampling with large guidance scale** by DPMs:
993
+ Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.
994
+ e.g.
995
+ >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)
996
+ >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,
997
+ skip_type='time_uniform', method='multistep')
998
+ We support three types of `skip_type`:
999
+ - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**
1000
+ - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.
1001
+ - 'time_quadratic': quadratic time for the time steps.
1002
+ =====================================================
1003
+ Args:
1004
+ x: A pytorch tensor. The initial value at time `t_start`
1005
+ e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.
1006
+ steps: A `int`. The total number of function evaluations (NFE).
1007
+ t_start: A `float`. The starting time of the sampling.
1008
+ If `T` is None, we use self.noise_schedule.T (default is 1.0).
1009
+ t_end: A `float`. The ending time of the sampling.
1010
+ If `t_end` is None, we use 1. / self.noise_schedule.total_N.
1011
+ e.g. if total_N == 1000, we have `t_end` == 1e-3.
1012
+ For discrete-time DPMs:
1013
+ - We recommend `t_end` == 1. / self.noise_schedule.total_N.
1014
+ For continuous-time DPMs:
1015
+ - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.
1016
+ order: A `int`. The order of DPM-Solver.
1017
+ skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.
1018
+ method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.
1019
+ denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step.
1020
+ Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1).
1021
+ This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and
1022
+ score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID
1023
+ for diffusion models sampling by diffusion SDEs for low-resolutional images
1024
+ (such as CIFAR-10). However, we observed that such trick does not matter for
1025
+ high-resolutional images. As it needs an additional NFE, we do not recommend
1026
+ it for high-resolutional images.
1027
+ lower_order_final: A `bool`. Whether to use lower order solvers at the final steps.
1028
+ Only valid for `method=multistep` and `steps < 15`. We empirically find that
1029
+ this trick is a key to stabilizing the sampling by DPM-Solver with very few steps
1030
+ (especially for steps <= 10). So we recommend to set it to be `True`.
1031
+ solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.
1032
+ atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1033
+ rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1034
+ Returns:
1035
+ x_end: A pytorch tensor. The approximated solution at time `t_end`.
1036
+ """
1037
+ t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
1038
+ t_T = self.noise_schedule.T if t_start is None else t_start
1039
+ device = x.device
1040
+ if method == 'adaptive':
1041
+ with torch.no_grad():
1042
+ x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol,
1043
+ solver_type=solver_type)
1044
+ elif method == 'multistep':
1045
+ assert steps >= order
1046
+ timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
1047
+ assert timesteps.shape[0] - 1 == steps
1048
+ with torch.no_grad():
1049
+ vec_t = timesteps[0].expand((x.shape[0]))
1050
+ model_prev_list = [self.model_fn(x, vec_t)]
1051
+ t_prev_list = [vec_t]
1052
+ # Init the first `order` values by lower order multistep DPM-Solver.
1053
+ for init_order in tqdm(range(1, order), desc="DPM init order"):
1054
+ vec_t = timesteps[init_order].expand(x.shape[0])
1055
+ x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order,
1056
+ solver_type=solver_type)
1057
+ model_prev_list.append(self.model_fn(x, vec_t))
1058
+ t_prev_list.append(vec_t)
1059
+ # Compute the remaining values by `order`-th order multistep DPM-Solver.
1060
+ for step in tqdm(range(order, steps + 1), desc="DPM multistep"):
1061
+ vec_t = timesteps[step].expand(x.shape[0])
1062
+ if lower_order_final and steps < 15:
1063
+ step_order = min(order, steps + 1 - step)
1064
+ else:
1065
+ step_order = order
1066
+ x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order,
1067
+ solver_type=solver_type)
1068
+ for i in range(order - 1):
1069
+ t_prev_list[i] = t_prev_list[i + 1]
1070
+ model_prev_list[i] = model_prev_list[i + 1]
1071
+ t_prev_list[-1] = vec_t
1072
+ # We do not need to evaluate the final model value.
1073
+ if step < steps:
1074
+ model_prev_list[-1] = self.model_fn(x, vec_t)
1075
+ elif method in ['singlestep', 'singlestep_fixed']:
1076
+ if method == 'singlestep':
1077
+ timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order,
1078
+ skip_type=skip_type,
1079
+ t_T=t_T, t_0=t_0,
1080
+ device=device)
1081
+ elif method == 'singlestep_fixed':
1082
+ K = steps // order
1083
+ orders = [order, ] * K
1084
+ timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)
1085
+ for i, order in enumerate(orders):
1086
+ t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]
1087
+ timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(),
1088
+ N=order, device=device)
1089
+ lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)
1090
+ vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0])
1091
+ h = lambda_inner[-1] - lambda_inner[0]
1092
+ r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h
1093
+ r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h
1094
+ x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)
1095
+ if denoise_to_zero:
1096
+ x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
1097
+ return x
1098
+
1099
+
1100
+ #############################################################
1101
+ # other utility functions
1102
+ #############################################################
1103
+
1104
+ def interpolate_fn(x, xp, yp):
1105
+ """
1106
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
1107
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
1108
+ The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
1109
+ Args:
1110
+ x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
1111
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
1112
+ yp: PyTorch tensor with shape [C, K].
1113
+ Returns:
1114
+ The function values f(x), with shape [N, C].
1115
+ """
1116
+ N, K = x.shape[0], xp.shape[1]
1117
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
1118
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
1119
+ x_idx = torch.argmin(x_indices, dim=2)
1120
+ cand_start_idx = x_idx - 1
1121
+ start_idx = torch.where(
1122
+ torch.eq(x_idx, 0),
1123
+ torch.tensor(1, device=x.device),
1124
+ torch.where(
1125
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1126
+ ),
1127
+ )
1128
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
1129
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
1130
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
1131
+ start_idx2 = torch.where(
1132
+ torch.eq(x_idx, 0),
1133
+ torch.tensor(0, device=x.device),
1134
+ torch.where(
1135
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1136
+ ),
1137
+ )
1138
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
1139
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
1140
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
1141
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
1142
+ return cand
1143
+
1144
+
1145
+ def expand_dims(v, dims):
1146
+ """
1147
+ Expand the tensor `v` to the dim `dims`.
1148
+ Args:
1149
+ `v`: a PyTorch tensor with shape [N].
1150
+ `dim`: a `int`.
1151
+ Returns:
1152
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
1153
+ """
1154
+ return v[(...,) + (None,) * (dims - 1)]
ldm/models/diffusion/dpm_solver/sampler.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+ import torch
3
+
4
+ from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver
5
+
6
+
7
+ MODEL_TYPES = {
8
+ "eps": "noise",
9
+ "v": "v"
10
+ }
11
+
12
+
13
+ class DPMSolverSampler(object):
14
+ def __init__(self, model, **kwargs):
15
+ super().__init__()
16
+ self.model = model
17
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
18
+ self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))
19
+
20
+ def register_buffer(self, name, attr):
21
+ if type(attr) == torch.Tensor:
22
+ if attr.device != torch.device("cuda"):
23
+ attr = attr.to(torch.device("cuda"))
24
+ setattr(self, name, attr)
25
+
26
+ @torch.no_grad()
27
+ def sample(self,
28
+ S,
29
+ batch_size,
30
+ shape,
31
+ conditioning=None,
32
+ callback=None,
33
+ normals_sequence=None,
34
+ img_callback=None,
35
+ quantize_x0=False,
36
+ eta=0.,
37
+ mask=None,
38
+ x0=None,
39
+ temperature=1.,
40
+ noise_dropout=0.,
41
+ score_corrector=None,
42
+ corrector_kwargs=None,
43
+ verbose=True,
44
+ x_T=None,
45
+ log_every_t=100,
46
+ unconditional_guidance_scale=1.,
47
+ unconditional_conditioning=None,
48
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
49
+ **kwargs
50
+ ):
51
+ if conditioning is not None:
52
+ if isinstance(conditioning, dict):
53
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
54
+ if cbs != batch_size:
55
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
56
+ else:
57
+ if conditioning.shape[0] != batch_size:
58
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
59
+
60
+ # sampling
61
+ C, H, W = shape
62
+ size = (batch_size, C, H, W)
63
+
64
+ print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}')
65
+
66
+ device = self.model.betas.device
67
+ if x_T is None:
68
+ img = torch.randn(size, device=device)
69
+ else:
70
+ img = x_T
71
+
72
+ ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)
73
+
74
+ model_fn = model_wrapper(
75
+ lambda x, t, c: self.model.apply_model(x, t, c),
76
+ ns,
77
+ model_type=MODEL_TYPES[self.model.parameterization],
78
+ guidance_type="classifier-free",
79
+ condition=conditioning,
80
+ unconditional_condition=unconditional_conditioning,
81
+ guidance_scale=unconditional_guidance_scale,
82
+ )
83
+
84
+ dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False)
85
+ x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True)
86
+
87
+ return x.to(device), None
ldm/models/diffusion/plms.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+ from functools import partial
7
+
8
+ from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
9
+ from ldm.models.diffusion.sampling_util import norm_thresholding
10
+
11
+
12
+ class PLMSSampler(object):
13
+ def __init__(self, model, schedule="linear", **kwargs):
14
+ super().__init__()
15
+ self.model = model
16
+ self.ddpm_num_timesteps = model.num_timesteps
17
+ self.schedule = schedule
18
+
19
+ def register_buffer(self, name, attr):
20
+ if type(attr) == torch.Tensor:
21
+ if attr.device != torch.device("cuda"):
22
+ attr = attr.to(torch.device("cuda"))
23
+ setattr(self, name, attr)
24
+
25
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
26
+ if ddim_eta != 0:
27
+ raise ValueError('ddim_eta must be 0 for PLMS')
28
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
29
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
30
+ alphas_cumprod = self.model.alphas_cumprod
31
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
32
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
33
+
34
+ self.register_buffer('betas', to_torch(self.model.betas))
35
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
36
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
37
+
38
+ # calculations for diffusion q(x_t | x_{t-1}) and others
39
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
40
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
41
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
42
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
43
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
44
+
45
+ # ddim sampling parameters
46
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
47
+ ddim_timesteps=self.ddim_timesteps,
48
+ eta=ddim_eta,verbose=verbose)
49
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
50
+ self.register_buffer('ddim_alphas', ddim_alphas)
51
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
52
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
53
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
54
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
55
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
56
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
57
+
58
+ @torch.no_grad()
59
+ def sample(self,
60
+ S,
61
+ batch_size,
62
+ shape,
63
+ conditioning=None,
64
+ callback=None,
65
+ normals_sequence=None,
66
+ img_callback=None,
67
+ quantize_x0=False,
68
+ eta=0.,
69
+ mask=None,
70
+ x0=None,
71
+ temperature=1.,
72
+ noise_dropout=0.,
73
+ score_corrector=None,
74
+ corrector_kwargs=None,
75
+ verbose=True,
76
+ x_T=None,
77
+ log_every_t=100,
78
+ unconditional_guidance_scale=1.,
79
+ unconditional_conditioning=None,
80
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
81
+ dynamic_threshold=None,
82
+ **kwargs
83
+ ):
84
+ if conditioning is not None:
85
+ if isinstance(conditioning, dict):
86
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
87
+ if cbs != batch_size:
88
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
89
+ else:
90
+ if conditioning.shape[0] != batch_size:
91
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
92
+
93
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
94
+ # sampling
95
+ C, H, W = shape
96
+ size = (batch_size, C, H, W)
97
+ print(f'Data shape for PLMS sampling is {size}')
98
+
99
+ samples, intermediates = self.plms_sampling(conditioning, size,
100
+ callback=callback,
101
+ img_callback=img_callback,
102
+ quantize_denoised=quantize_x0,
103
+ mask=mask, x0=x0,
104
+ ddim_use_original_steps=False,
105
+ noise_dropout=noise_dropout,
106
+ temperature=temperature,
107
+ score_corrector=score_corrector,
108
+ corrector_kwargs=corrector_kwargs,
109
+ x_T=x_T,
110
+ log_every_t=log_every_t,
111
+ unconditional_guidance_scale=unconditional_guidance_scale,
112
+ unconditional_conditioning=unconditional_conditioning,
113
+ dynamic_threshold=dynamic_threshold,
114
+ )
115
+ return samples, intermediates
116
+
117
+ @torch.no_grad()
118
+ def plms_sampling(self, cond, shape,
119
+ x_T=None, ddim_use_original_steps=False,
120
+ callback=None, timesteps=None, quantize_denoised=False,
121
+ mask=None, x0=None, img_callback=None, log_every_t=100,
122
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
123
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
124
+ dynamic_threshold=None):
125
+ device = self.model.betas.device
126
+ b = shape[0]
127
+ if x_T is None:
128
+ img = torch.randn(shape, device=device)
129
+ else:
130
+ img = x_T
131
+
132
+ if timesteps is None:
133
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
134
+ elif timesteps is not None and not ddim_use_original_steps:
135
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
136
+ timesteps = self.ddim_timesteps[:subset_end]
137
+
138
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
139
+ time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
140
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
141
+ print(f"Running PLMS Sampling with {total_steps} timesteps")
142
+
143
+ iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
144
+ old_eps = []
145
+
146
+ for i, step in enumerate(iterator):
147
+ index = total_steps - i - 1
148
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
149
+ ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
150
+
151
+ if mask is not None:
152
+ assert x0 is not None
153
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
154
+ img = img_orig * mask + (1. - mask) * img
155
+
156
+ outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
157
+ quantize_denoised=quantize_denoised, temperature=temperature,
158
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
159
+ corrector_kwargs=corrector_kwargs,
160
+ unconditional_guidance_scale=unconditional_guidance_scale,
161
+ unconditional_conditioning=unconditional_conditioning,
162
+ old_eps=old_eps, t_next=ts_next,
163
+ dynamic_threshold=dynamic_threshold)
164
+ img, pred_x0, e_t = outs
165
+ old_eps.append(e_t)
166
+ if len(old_eps) >= 4:
167
+ old_eps.pop(0)
168
+ if callback: callback(i)
169
+ if img_callback: img_callback(pred_x0, i)
170
+
171
+ if index % log_every_t == 0 or index == total_steps - 1:
172
+ intermediates['x_inter'].append(img)
173
+ intermediates['pred_x0'].append(pred_x0)
174
+
175
+ return img, intermediates
176
+
177
+ @torch.no_grad()
178
+ def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
179
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
180
+ unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None,
181
+ dynamic_threshold=None):
182
+ b, *_, device = *x.shape, x.device
183
+
184
+ def get_model_output(x, t):
185
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
186
+ e_t = self.model.apply_model(x, t, c)
187
+ else:
188
+ x_in = torch.cat([x] * 2)
189
+ t_in = torch.cat([t] * 2)
190
+ c_in = torch.cat([unconditional_conditioning, c])
191
+ e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
192
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
193
+
194
+ if score_corrector is not None:
195
+ assert self.model.parameterization == "eps"
196
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
197
+
198
+ return e_t
199
+
200
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
201
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
202
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
203
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
204
+
205
+ def get_x_prev_and_pred_x0(e_t, index):
206
+ # select parameters corresponding to the currently considered timestep
207
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
208
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
209
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
210
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
211
+
212
+ # current prediction for x_0
213
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
214
+ if quantize_denoised:
215
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
216
+ if dynamic_threshold is not None:
217
+ pred_x0 = norm_thresholding(pred_x0, dynamic_threshold)
218
+ # direction pointing to x_t
219
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
220
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
221
+ if noise_dropout > 0.:
222
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
223
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
224
+ return x_prev, pred_x0
225
+
226
+ e_t = get_model_output(x, t)
227
+ if len(old_eps) == 0:
228
+ # Pseudo Improved Euler (2nd order)
229
+ x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
230
+ e_t_next = get_model_output(x_prev, t_next)
231
+ e_t_prime = (e_t + e_t_next) / 2
232
+ elif len(old_eps) == 1:
233
+ # 2nd order Pseudo Linear Multistep (Adams-Bashforth)
234
+ e_t_prime = (3 * e_t - old_eps[-1]) / 2
235
+ elif len(old_eps) == 2:
236
+ # 3nd order Pseudo Linear Multistep (Adams-Bashforth)
237
+ e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
238
+ elif len(old_eps) >= 3:
239
+ # 4nd order Pseudo Linear Multistep (Adams-Bashforth)
240
+ e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
241
+
242
+ x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
243
+
244
+ return x_prev, pred_x0, e_t
ldm/models/diffusion/sampling_util.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ def append_dims(x, target_dims):
6
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions.
7
+ From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py"""
8
+ dims_to_append = target_dims - x.ndim
9
+ if dims_to_append < 0:
10
+ raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
11
+ return x[(...,) + (None,) * dims_to_append]
12
+
13
+
14
+ def norm_thresholding(x0, value):
15
+ s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim)
16
+ return x0 * (value / s)
17
+
18
+
19
+ def spatial_norm_thresholding(x0, value):
20
+ # b c h w
21
+ s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value)
22
+ return x0 * (value / s)
ldm/modules/__pycache__/attention.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
ldm/modules/__pycache__/attention.cpython-38.pyc ADDED
Binary file (10.4 kB). View file
ldm/modules/__pycache__/attention.cpython-39.pyc ADDED
Binary file (10.4 kB). View file
ldm/modules/__pycache__/ema.cpython-310.pyc ADDED
Binary file (3.19 kB). View file
ldm/modules/__pycache__/ema.cpython-38.pyc ADDED
Binary file (3.18 kB). View file
ldm/modules/__pycache__/ema.cpython-39.pyc ADDED
Binary file (3.18 kB). View file
ldm/modules/attention.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inspect import isfunction
2
+ import math
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn, einsum
6
+ from einops import rearrange, repeat
7
+ from typing import Optional, Any
8
+
9
+ from ldm.modules.diffusionmodules.util import checkpoint
10
+
11
+
12
+ try:
13
+ import xformers
14
+ import xformers.ops
15
+ XFORMERS_IS_AVAILBLE = True
16
+ except:
17
+ XFORMERS_IS_AVAILBLE = False
18
+
19
+ # CrossAttn precision handling
20
+ import os
21
+ _ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")
22
+
23
+ def exists(val):
24
+ return val is not None
25
+
26
+
27
+ def uniq(arr):
28
+ return{el: True for el in arr}.keys()
29
+
30
+
31
+ def default(val, d):
32
+ if exists(val):
33
+ return val
34
+ return d() if isfunction(d) else d
35
+
36
+
37
+ def max_neg_value(t):
38
+ return -torch.finfo(t.dtype).max
39
+
40
+
41
+ def init_(tensor):
42
+ dim = tensor.shape[-1]
43
+ std = 1 / math.sqrt(dim)
44
+ tensor.uniform_(-std, std)
45
+ return tensor
46
+
47
+
48
+ # feedforward
49
+ class GEGLU(nn.Module):
50
+ def __init__(self, dim_in, dim_out):
51
+ super().__init__()
52
+ self.proj = nn.Linear(dim_in, dim_out * 2)
53
+
54
+ def forward(self, x):
55
+ x, gate = self.proj(x).chunk(2, dim=-1)
56
+ return x * F.gelu(gate)
57
+
58
+
59
+ class FeedForward(nn.Module):
60
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
61
+ super().__init__()
62
+ inner_dim = int(dim * mult)
63
+ dim_out = default(dim_out, dim)
64
+ project_in = nn.Sequential(
65
+ nn.Linear(dim, inner_dim),
66
+ nn.GELU()
67
+ ) if not glu else GEGLU(dim, inner_dim)
68
+
69
+ self.net = nn.Sequential(
70
+ project_in,
71
+ nn.Dropout(dropout),
72
+ nn.Linear(inner_dim, dim_out)
73
+ )
74
+
75
+ def forward(self, x):
76
+ return self.net(x)
77
+
78
+
79
+ def zero_module(module):
80
+ """
81
+ Zero out the parameters of a module and return it.
82
+ """
83
+ for p in module.parameters():
84
+ p.detach().zero_()
85
+ return module
86
+
87
+
88
+ def Normalize(in_channels):
89
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
90
+
91
+
92
+ class SpatialSelfAttention(nn.Module):
93
+ def __init__(self, in_channels):
94
+ super().__init__()
95
+ self.in_channels = in_channels
96
+
97
+ self.norm = Normalize(in_channels)
98
+ self.q = torch.nn.Conv2d(in_channels,
99
+ in_channels,
100
+ kernel_size=1,
101
+ stride=1,
102
+ padding=0)
103
+ self.k = torch.nn.Conv2d(in_channels,
104
+ in_channels,
105
+ kernel_size=1,
106
+ stride=1,
107
+ padding=0)
108
+ self.v = torch.nn.Conv2d(in_channels,
109
+ in_channels,
110
+ kernel_size=1,
111
+ stride=1,
112
+ padding=0)
113
+ self.proj_out = torch.nn.Conv2d(in_channels,
114
+ in_channels,
115
+ kernel_size=1,
116
+ stride=1,
117
+ padding=0)
118
+
119
+ def forward(self, x):
120
+ h_ = x
121
+ h_ = self.norm(h_)
122
+ q = self.q(h_)
123
+ k = self.k(h_)
124
+ v = self.v(h_)
125
+
126
+ # compute attention
127
+ b,c,h,w = q.shape
128
+ q = rearrange(q, 'b c h w -> b (h w) c')
129
+ k = rearrange(k, 'b c h w -> b c (h w)')
130
+ w_ = torch.einsum('bij,bjk->bik', q, k)
131
+
132
+ w_ = w_ * (int(c)**(-0.5))
133
+ w_ = torch.nn.functional.softmax(w_, dim=2)
134
+
135
+ # attend to values
136
+ v = rearrange(v, 'b c h w -> b c (h w)')
137
+ w_ = rearrange(w_, 'b i j -> b j i')
138
+ h_ = torch.einsum('bij,bjk->bik', v, w_)
139
+ h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
140
+ h_ = self.proj_out(h_)
141
+
142
+ return x+h_
143
+
144
+
145
+ class CrossAttention(nn.Module):
146
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
147
+ super().__init__()
148
+ inner_dim = dim_head * heads
149
+ context_dim = default(context_dim, query_dim)
150
+
151
+ self.scale = dim_head ** -0.5
152
+ self.heads = heads
153
+
154
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
155
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
156
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
157
+
158
+ self.to_out = nn.Sequential(
159
+ nn.Linear(inner_dim, query_dim),
160
+ nn.Dropout(dropout)
161
+ )
162
+
163
+ def forward(self, x, context=None, mask=None):
164
+ h = self.heads
165
+
166
+ q = self.to_q(x)
167
+ context = default(context, x)
168
+ k = self.to_k(context)
169
+ v = self.to_v(context)
170
+
171
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
172
+
173
+ # force cast to fp32 to avoid overflowing
174
+ if _ATTN_PRECISION =="fp32":
175
+ with torch.autocast(enabled=False, device_type = 'cuda'):
176
+ q, k = q.float(), k.float()
177
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
178
+ else:
179
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
180
+
181
+ del q, k
182
+
183
+ if exists(mask):
184
+ mask = rearrange(mask, 'b ... -> b (...)')
185
+ max_neg_value = -torch.finfo(sim.dtype).max
186
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
187
+ sim.masked_fill_(~mask, max_neg_value)
188
+
189
+ # attention, what we cannot get enough of
190
+ sim = sim.softmax(dim=-1)
191
+
192
+ out = einsum('b i j, b j d -> b i d', sim, v)
193
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
194
+ return self.to_out(out)
195
+
196
+
197
+ class MemoryEfficientCrossAttention(nn.Module):
198
+ # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
199
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
200
+ super().__init__()
201
+ print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
202
+ f"{heads} heads.")
203
+ inner_dim = dim_head * heads
204
+ context_dim = default(context_dim, query_dim)
205
+
206
+ self.heads = heads
207
+ self.dim_head = dim_head
208
+
209
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
210
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
211
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
212
+
213
+ self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
214
+ self.attention_op: Optional[Any] = None
215
+
216
+ def forward(self, x, context=None, mask=None):
217
+ q = self.to_q(x)
218
+ context = default(context, x)
219
+ k = self.to_k(context)
220
+ v = self.to_v(context)
221
+
222
+ b, _, _ = q.shape
223
+ q, k, v = map(
224
+ lambda t: t.unsqueeze(3)
225
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
226
+ .permute(0, 2, 1, 3)
227
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
228
+ .contiguous(),
229
+ (q, k, v),
230
+ )
231
+
232
+ # actually compute the attention, what we cannot get enough of
233
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
234
+
235
+ if exists(mask):
236
+ raise NotImplementedError
237
+ out = (
238
+ out.unsqueeze(0)
239
+ .reshape(b, self.heads, out.shape[1], self.dim_head)
240
+ .permute(0, 2, 1, 3)
241
+ .reshape(b, out.shape[1], self.heads * self.dim_head)
242
+ )
243
+ return self.to_out(out)
244
+
245
+
246
+ class BasicTransformerBlock(nn.Module):
247
+ ATTENTION_MODES = {
248
+ "softmax": CrossAttention, # vanilla attention
249
+ "softmax-xformers": MemoryEfficientCrossAttention
250
+ }
251
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
252
+ disable_self_attn=False):
253
+ super().__init__()
254
+ attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax"
255
+ assert attn_mode in self.ATTENTION_MODES
256
+ attn_cls = self.ATTENTION_MODES[attn_mode]
257
+ self.disable_self_attn = disable_self_attn
258
+ self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
259
+ context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn
260
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
261
+ self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim,
262
+ heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
263
+ self.norm1 = nn.LayerNorm(dim)
264
+ self.norm2 = nn.LayerNorm(dim)
265
+ self.norm3 = nn.LayerNorm(dim)
266
+ self.checkpoint = checkpoint
267
+
268
+ def forward(self, x, context=None):
269
+ return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
270
+
271
+ def _forward(self, x, context=None):
272
+ x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
273
+ x = self.attn2(self.norm2(x), context=context) + x
274
+ x = self.ff(self.norm3(x)) + x
275
+ return x
276
+
277
+
278
+ class SpatialTransformer(nn.Module):
279
+ """
280
+ Transformer block for image-like data.
281
+ First, project the input (aka embedding)
282
+ and reshape to b, t, d.
283
+ Then apply standard transformer action.
284
+ Finally, reshape to image
285
+ NEW: use_linear for more efficiency instead of the 1x1 convs
286
+ """
287
+ def __init__(self, in_channels, n_heads, d_head,
288
+ depth=1, dropout=0., context_dim=None,
289
+ disable_self_attn=False, use_linear=False,
290
+ use_checkpoint=True):
291
+ super().__init__()
292
+ if exists(context_dim) and not isinstance(context_dim, list):
293
+ context_dim = [context_dim]
294
+ self.in_channels = in_channels
295
+ inner_dim = n_heads * d_head
296
+ self.norm = Normalize(in_channels)
297
+ if not use_linear:
298
+ self.proj_in = nn.Conv2d(in_channels,
299
+ inner_dim,
300
+ kernel_size=1,
301
+ stride=1,
302
+ padding=0)
303
+ else:
304
+ self.proj_in = nn.Linear(in_channels, inner_dim)
305
+
306
+ self.transformer_blocks = nn.ModuleList(
307
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
308
+ disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)
309
+ for d in range(depth)]
310
+ )
311
+ if not use_linear:
312
+ self.proj_out = zero_module(nn.Conv2d(inner_dim,
313
+ in_channels,
314
+ kernel_size=1,
315
+ stride=1,
316
+ padding=0))
317
+ else:
318
+ self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
319
+ self.use_linear = use_linear
320
+
321
+ def forward(self, x, context=None):
322
+ # note: if no context is given, cross-attention defaults to self-attention
323
+ if not isinstance(context, list):
324
+ context = [context]
325
+ b, c, h, w = x.shape
326
+ x_in = x
327
+ x = self.norm(x)
328
+ if not self.use_linear:
329
+ x = self.proj_in(x)
330
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
331
+ if self.use_linear:
332
+ x = self.proj_in(x)
333
+ for i, block in enumerate(self.transformer_blocks):
334
+ x = block(x, context=context[i])
335
+ if self.use_linear:
336
+ x = self.proj_out(x)
337
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
338
+ if not self.use_linear:
339
+ x = self.proj_out(x)
340
+ return x + x_in
341
+
ldm/modules/diffusionmodules/__init__.py ADDED
File without changes
ldm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (163 Bytes). View file
ldm/modules/diffusionmodules/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (161 Bytes). View file
ldm/modules/diffusionmodules/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (161 Bytes). View file