ablattmann commited on
Commit
aea2f58
β€’
1 Parent(s): 182dd36

Former-commit-id: e66308c7f2e64cb581c6d27ab6fbeb846828253b

This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. README.md +103 -3
  2. assets/inpainting.png +0 -0
  3. assets/reconstruction1.png +0 -0
  4. assets/reconstruction2.png +0 -0
  5. configs/autoencoder/autoencoder_kl_16x16x16.yaml +54 -0
  6. configs/autoencoder/autoencoder_kl_32x32x4.yaml +53 -0
  7. configs/autoencoder/autoencoder_kl_64x64x3.yaml +54 -0
  8. configs/autoencoder/autoencoder_kl_8x8x64.yaml +53 -0
  9. configs/latent-diffusion/lsun_churches_f8-autoencoder-ldm.yaml +95 -0
  10. data/DejaVuSans.ttf +0 -0
  11. data/example_conditioning/superresolution/sample_0.jpg +0 -0
  12. data/example_conditioning/text_conditional/sample_0.txt +1 -0
  13. data/imagenet_train_hr_indices.p.REMOVED.git-id +1 -0
  14. data/imagenet_val_hr_indices.p +0 -0
  15. data/index_synset.yaml +1000 -0
  16. data/inpainting_examples/6458524847_2f4c361183_k.png +0 -0
  17. data/inpainting_examples/6458524847_2f4c361183_k_mask.png +0 -0
  18. data/inpainting_examples/8399166846_f6fb4e4b8e_k.png +0 -0
  19. data/inpainting_examples/8399166846_f6fb4e4b8e_k_mask.png +0 -0
  20. data/inpainting_examples/alex-iby-G_Pk4D9rMLs.png +0 -0
  21. data/inpainting_examples/alex-iby-G_Pk4D9rMLs_mask.png +0 -0
  22. data/inpainting_examples/bench2.png +0 -0
  23. data/inpainting_examples/bench2_mask.png +0 -0
  24. data/inpainting_examples/bertrand-gabioud-CpuFzIsHYJ0.png +0 -0
  25. data/inpainting_examples/bertrand-gabioud-CpuFzIsHYJ0_mask.png +0 -0
  26. data/inpainting_examples/billow926-12-Wc-Zgx6Y.png +0 -0
  27. data/inpainting_examples/billow926-12-Wc-Zgx6Y_mask.png +0 -0
  28. data/inpainting_examples/overture-creations-5sI6fQgYIuo.png +0 -0
  29. data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png +0 -0
  30. data/inpainting_examples/photo-1583445095369-9c651e7e5d34.png +0 -0
  31. data/inpainting_examples/photo-1583445095369-9c651e7e5d34_mask.png +0 -0
  32. environment.yaml +27 -0
  33. ldm/data/__init__.py +0 -0
  34. ldm/data/base.py +23 -0
  35. ldm/data/imagenet.py +394 -0
  36. ldm/data/lsun.py +92 -0
  37. ldm/lr_scheduler.py +98 -0
  38. ldm/models/autoencoder.py +443 -0
  39. ldm/models/diffusion/__init__.py +0 -0
  40. ldm/models/diffusion/classifier.py +267 -0
  41. ldm/models/diffusion/ddim.py +186 -0
  42. ldm/models/diffusion/ddpm.py +1430 -0
  43. ldm/modules/attention.py +261 -0
  44. ldm/modules/diffusionmodules/__init__.py +0 -0
  45. ldm/modules/diffusionmodules/model.py +835 -0
  46. ldm/modules/diffusionmodules/openaimodel.py +936 -0
  47. ldm/modules/diffusionmodules/util.py +261 -0
  48. ldm/modules/distributions/__init__.py +0 -0
  49. ldm/modules/distributions/distributions.py +92 -0
  50. ldm/modules/ema.py +76 -0
README.md CHANGED
@@ -1,4 +1,104 @@
1
- # latent-diffusion
2
- High-Resolution Image Synthesis with Latent Diffusion Models
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- ...coming soonβ„’
 
1
+ # Latent Diffusion Models
2
+
3
+ ## Requirements
4
+ A suitable [conda](https://conda.io/) environment named `ldm` can be created
5
+ and activated with:
6
+
7
+ ```
8
+ conda env create -f environment.yaml
9
+ conda activate ldm
10
+ ```
11
+
12
+ # Model Zoo
13
+
14
+ ## Pretrained Autoencoding Models
15
+ ![rec2](assets/reconstruction2.png)
16
+
17
+
18
+ | Model | FID vs val | PSNR | PSIM | Link | Comments
19
+ |-------------------------|------------|----------------|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|
20
+ | f=4, VQ (Z=8192, d=3) | 0.58 | 27.43 +/- 4.26 | 0.53 +/- 0.21 | https://ommer-lab.com/files/latent-diffusion/vq-f4.zip | |
21
+ | f=4, VQ (Z=8192, d=3) | 1.06 | 25.21 +/- 4.17 | 0.72 +/- 0.26 | https://heibox.uni-heidelberg.de/f/9c6681f64bb94338a069/?dl=1 | no attention |
22
+ | f=8, VQ (Z=16384, d=4) | 1.14 | 23.07 +/- 3.99 | 1.17 +/- 0.36 | https://ommer-lab.com/files/latent-diffusion/vq-f8.zip | |
23
+ | f=8, VQ (Z=256, d=4) | 1.49 | 22.35 +/- 3.81 | 1.26 +/- 0.37 | https://ommer-lab.com/files/latent-diffusion/vq-f8-n256.zip |
24
+ | f=16, VQ (Z=16384, d=8) | 5.15 | 20.83 +/- 3.61 | 1.73 +/- 0.43 | https://heibox.uni-heidelberg.de/f/0e42b04e2e904890a9b6/?dl=1 | |
25
+ | | | | | | |
26
+ | f=4, KL | 0.27 | 27.53 +/- 4.54 | 0.55 +/- 0.24 | https://ommer-lab.com/files/latent-diffusion/kl-f4.zip | |
27
+ | f=8, KL | 0.90 | 24.19 +/- 4.19 | 1.02 +/- 0.35 | https://ommer-lab.com/files/latent-diffusion/kl-f8.zip | |
28
+ | f=16, KL (d=16) | 0.87 | 24.08 +/- 4.22 | 1.07 +/- 0.36 | https://ommer-lab.com/files/latent-diffusion/kl-f16.zip | |
29
+ | f=32, KL (d=64) | 2.04 | 22.27 +/- 3.93 | 1.41 +/- 0.40 | https://ommer-lab.com/files/latent-diffusion/kl-f32.zip | |
30
+
31
+ ### Get the models
32
+
33
+ Running the following script downloads und extracts all available pretrained autoencoding models.
34
+
35
+ ```shell script
36
+ bash scripts/download_first_stages.sh
37
+ ```
38
+
39
+ The first stage models can then be found in `models/first_stage_models/<model_spec>`
40
+
41
+ ## Pretrained LDMs
42
+ | Datset | Task | Model | FID | IS | Prec | Recall | Link | Comments
43
+ |---------------------------------|------|--------------|---------------|-----------------|------|------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------|
44
+ | CelebA-HQ | Unconditional Image Synthesis | LDM-VQ-4 (200 DDIM steps, eta=0)| 5.11 (5.11) | 3.29 | 0.72 | 0.49 | https://ommer-lab.com/files/latent-diffusion/celeba.zip | |
45
+ | FFHQ | Unconditional Image Synthesis | LDM-VQ-4 (200 DDIM steps, eta=1)| 4.98 (4.98) | 4.50 (4.50) | 0.73 | 0.50 | https://ommer-lab.com/files/latent-diffusion/ffhq.zip | |
46
+ | LSUN-Churches | Unconditional Image Synthesis | LDM-KL-8 (400 DDIM steps, eta=0)| 4.02 (4.02) | 2.72 | 0.64 | 0.52 | https://ommer-lab.com/files/latent-diffusion/lsun_churches.zip | |
47
+ | LSUN-Bedrooms | Unconditional Image Synthesis | LDM-VQ-4 (200 DDIM steps, eta=1)| 2.95 (3.0) | 2.22 (2.23)| 0.66 | 0.48 | https://ommer-lab.com/files/latent-diffusion/lsun_bedrooms.zip | |
48
+ | ImageNet | Class-conditional Image Synthesis | LDM-VQ-8 (200 DDIM steps, eta=1) | 7.77(7.76)* /15.82** | 201.56(209.52)* /78.82** | 0.84* / 0.65** | 0.35* / 0.63** | https://ommer-lab.com/files/latent-diffusion/cin.zip | *: w/ guiding, classifier_scale 10 **: w/o guiding, scores in bracket calculated with script provided by [ADM](https://github.com/openai/guided-diffusion) |
49
+ | Conceptual Captions | Text-conditional Image Synthesis | LDM-VQ-f4 (100 DDIM steps, eta=0) | 16.79 | 13.89 | N/A | N/A | https://ommer-lab.com/files/latent-diffusion/text2img.zip | finetuned from LAION |
50
+ | OpenImages | Super-resolution | N/A | N/A | N/A | N/A | N/A | https://ommer-lab.com/files/latent-diffusion/sr_bsr.zip | BSR image degradation |
51
+ | OpenImages | Layout-to-Image Synthesis | LDM-VQ-4 (200 DDIM steps, eta=0) | 32.02 | 15.92 | N/A | N/A | https://ommer-lab.com/files/latent-diffusion/layout2img_model.zip | |
52
+ | Landscapes (finetuned 512) | Semantic Image Synthesis | LDM-VQ-4 (100 DDIM steps, eta=1) | N/A | N/A | N/A | N/A | https://ommer-lab.com/files/latent-diffusion/semantic_synthesis.zip | |
53
+
54
+
55
+ ### Get the models
56
+
57
+ The LDMs listed above can jointly be downloaded and extracted via
58
+
59
+ ```shell script
60
+ bash scripts/download_models.sh
61
+ ```
62
+
63
+ The models can then be found in `models/ldm/<model_spec>`.
64
+
65
+ ### Sampling with unconditional models
66
+
67
+ We provide a first script for sampling from our unconditional models. Start it via
68
+
69
+ ```shell script
70
+ CUDA_VISIBLE_DEVICES=<GPU_ID> python scripts/sample_diffusion.py -r models/ldm/<model_spec>/model.ckpt -l <logdir> -n <\#samples> --batch_size <batch_size> -c <\#ddim steps> -e <\#eta>
71
+ ```
72
+
73
+ # Inpainting
74
+ ![inpainting](assets/inpainting.png)
75
+
76
+ Download the pre-trained weights
77
+ ```
78
+ wget XXX
79
+ ```
80
+
81
+ and sample with
82
+ ```
83
+ python scripts/inpaint.py --indir data/inpainting_examples/ --outdir outputs/inpainting_results
84
+ ```
85
+ `indir` should contain images `*.png` and masks `<image_fname>_mask.png` like
86
+ the examples provided in `data/inpainting_examples`.
87
+
88
+
89
+ ## Comin Soon...
90
+
91
+ * Code for training LDMs and the corresponding compression models.
92
+ * Inference scripts for conditional LDMs for various conditioning modalities.
93
+ * In the meantime, you can play with our colab notebook https://colab.research.google.com/drive/1xqzUi2iXQXDqXBHQGP9Mqt2YrYW6cx-J?usp=sharing
94
+ * We will also release some further pretrained models.
95
+ ## Comments
96
+
97
+ - Our codebase for the diffusion models builds heavily on [OpenAI's codebase](https://github.com/openai/guided-diffusion)
98
+ and [https://github.com/lucidrains/denoising-diffusion-pytorch](https://github.com/lucidrains/denoising-diffusion-pytorch).
99
+ Thanks for open-sourcing!
100
+
101
+ - The implementation of the transformer encoder is from [x-transformers](https://github.com/lucidrains/x-transformers) by [lucidrains](https://github.com/lucidrains?tab=repositories).
102
+
103
+
104
 
 
assets/inpainting.png ADDED
assets/reconstruction1.png ADDED
assets/reconstruction2.png ADDED
configs/autoencoder/autoencoder_kl_16x16x16.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 16
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 16
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,1,2,2,4] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [16]
24
+ dropout: 0.0
25
+
26
+
27
+ data:
28
+ target: main.DataModuleFromConfig
29
+ params:
30
+ batch_size: 12
31
+ wrap: True
32
+ train:
33
+ target: ldm.data.imagenet.ImageNetSRTrain
34
+ params:
35
+ size: 256
36
+ degradation: pil_nearest
37
+ validation:
38
+ target: ldm.data.imagenet.ImageNetSRValidation
39
+ params:
40
+ size: 256
41
+ degradation: pil_nearest
42
+
43
+ lightning:
44
+ callbacks:
45
+ image_logger:
46
+ target: main.ImageLogger
47
+ params:
48
+ batch_frequency: 1000
49
+ max_images: 8
50
+ increase_log_steps: True
51
+
52
+ trainer:
53
+ benchmark: True
54
+ accumulate_grad_batches: 2
configs/autoencoder/autoencoder_kl_32x32x4.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 4
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 4
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,2,4,4 ] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [ ]
24
+ dropout: 0.0
25
+
26
+ data:
27
+ target: main.DataModuleFromConfig
28
+ params:
29
+ batch_size: 12
30
+ wrap: True
31
+ train:
32
+ target: ldm.data.imagenet.ImageNetSRTrain
33
+ params:
34
+ size: 256
35
+ degradation: pil_nearest
36
+ validation:
37
+ target: ldm.data.imagenet.ImageNetSRValidation
38
+ params:
39
+ size: 256
40
+ degradation: pil_nearest
41
+
42
+ lightning:
43
+ callbacks:
44
+ image_logger:
45
+ target: main.ImageLogger
46
+ params:
47
+ batch_frequency: 1000
48
+ max_images: 8
49
+ increase_log_steps: True
50
+
51
+ trainer:
52
+ benchmark: True
53
+ accumulate_grad_batches: 2
configs/autoencoder/autoencoder_kl_64x64x3.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 3
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 3
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,2,4 ] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [ ]
24
+ dropout: 0.0
25
+
26
+
27
+ data:
28
+ target: main.DataModuleFromConfig
29
+ params:
30
+ batch_size: 12
31
+ wrap: True
32
+ train:
33
+ target: ldm.data.imagenet.ImageNetSRTrain
34
+ params:
35
+ size: 256
36
+ degradation: pil_nearest
37
+ validation:
38
+ target: ldm.data.imagenet.ImageNetSRValidation
39
+ params:
40
+ size: 256
41
+ degradation: pil_nearest
42
+
43
+ lightning:
44
+ callbacks:
45
+ image_logger:
46
+ target: main.ImageLogger
47
+ params:
48
+ batch_frequency: 1000
49
+ max_images: 8
50
+ increase_log_steps: True
51
+
52
+ trainer:
53
+ benchmark: True
54
+ accumulate_grad_batches: 2
configs/autoencoder/autoencoder_kl_8x8x64.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 64
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 64
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,1,2,2,4,4] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [16,8]
24
+ dropout: 0.0
25
+
26
+ data:
27
+ target: main.DataModuleFromConfig
28
+ params:
29
+ batch_size: 12
30
+ wrap: True
31
+ train:
32
+ target: ldm.data.imagenet.ImageNetSRTrain
33
+ params:
34
+ size: 256
35
+ degradation: pil_nearest
36
+ validation:
37
+ target: ldm.data.imagenet.ImageNetSRValidation
38
+ params:
39
+ size: 256
40
+ degradation: pil_nearest
41
+
42
+ lightning:
43
+ callbacks:
44
+ image_logger:
45
+ target: main.ImageLogger
46
+ params:
47
+ batch_frequency: 1000
48
+ max_images: 8
49
+ increase_log_steps: True
50
+
51
+ trainer:
52
+ benchmark: True
53
+ accumulate_grad_batches: 2
configs/latent-diffusion/lsun_churches_f8-autoencoder-ldm.yaml ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 5.0e-5 # set to target_lr by starting main.py with '--scale_lr False'
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0155
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ loss_type: l1
11
+ first_stage_key: "image"
12
+ cond_stage_key: "image"
13
+ image_size: 32
14
+ channels: 4
15
+ cond_stage_trainable: False
16
+ concat_mode: False
17
+ scale_by_std: True
18
+ monitor: 'val/loss_simple_ema'
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [10000]
24
+ cycle_lengths: [10000000000000]
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
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 192
36
+ attention_resolutions: [ 1, 2, 4, 8 ] # 32, 16, 8, 4
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1,2,2,4,4 ] # 32, 16, 8, 4, 2
39
+ num_heads: 8
40
+ use_scale_shift_norm: True
41
+ resblock_updown: True
42
+
43
+ first_stage_config:
44
+ target: ldm.models.autoencoder.AutoencoderKL
45
+ params:
46
+ embed_dim: 4
47
+ monitor: "val/rec_loss"
48
+ ckpt_path: "/export/compvis-nfs/user/ablattma/logs/braket/2021-11-26T11-25-56_lsun_churches-convae-f8-ft_from_oi/checkpoints/step=000180071-fidfrechet_inception_distance=2.335.ckpt"
49
+ ddconfig:
50
+ double_z: True
51
+ z_channels: 4
52
+ resolution: 256
53
+ in_channels: 3
54
+ out_ch: 3
55
+ ch: 128
56
+ ch_mult: [ 1,2,4,4 ] # num_down = len(ch_mult)-1
57
+ num_res_blocks: 2
58
+ attn_resolutions: [ ]
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config: "__is_unconditional__"
64
+
65
+ data:
66
+ target: main.DataModuleFromConfig
67
+ params:
68
+ batch_size: 24 # TODO: was 96 in our experiments
69
+ num_workers: 5
70
+ wrap: False
71
+ train:
72
+ target: ldm.data.lsun.LSUNChurchesTrain
73
+ params:
74
+ size: 256
75
+ validation:
76
+ target: ldm.data.lsun.LSUNChurchesValidation
77
+ params:
78
+ size: 256
79
+
80
+ lightning:
81
+ callbacks:
82
+ image_logger:
83
+ target: main.ImageLogger
84
+ params:
85
+ batch_frequency: 1000 # TODO 5000
86
+ max_images: 8
87
+ increase_log_steps: False
88
+
89
+ metrics_over_trainsteps_checkpoint:
90
+ target: pytorch_lightning.callbacks.ModelCheckpoint
91
+ params:
92
+ every_n_train_steps: 20000
93
+
94
+ trainer:
95
+ benchmark: True
data/DejaVuSans.ttf ADDED
Binary file (757 kB). View file
 
data/example_conditioning/superresolution/sample_0.jpg ADDED
data/example_conditioning/text_conditional/sample_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A basket of cerries
data/imagenet_train_hr_indices.p.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ b8d6d4689d2ecf32147e9cc2f5e6c50e072df26f
data/imagenet_val_hr_indices.p ADDED
Binary file (146 kB). View file
 
data/index_synset.yaml ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 0: n01440764
2
+ 1: n01443537
3
+ 2: n01484850
4
+ 3: n01491361
5
+ 4: n01494475
6
+ 5: n01496331
7
+ 6: n01498041
8
+ 7: n01514668
9
+ 8: n07646067
10
+ 9: n01518878
11
+ 10: n01530575
12
+ 11: n01531178
13
+ 12: n01532829
14
+ 13: n01534433
15
+ 14: n01537544
16
+ 15: n01558993
17
+ 16: n01560419
18
+ 17: n01580077
19
+ 18: n01582220
20
+ 19: n01592084
21
+ 20: n01601694
22
+ 21: n13382471
23
+ 22: n01614925
24
+ 23: n01616318
25
+ 24: n01622779
26
+ 25: n01629819
27
+ 26: n01630670
28
+ 27: n01631663
29
+ 28: n01632458
30
+ 29: n01632777
31
+ 30: n01641577
32
+ 31: n01644373
33
+ 32: n01644900
34
+ 33: n01664065
35
+ 34: n01665541
36
+ 35: n01667114
37
+ 36: n01667778
38
+ 37: n01669191
39
+ 38: n01675722
40
+ 39: n01677366
41
+ 40: n01682714
42
+ 41: n01685808
43
+ 42: n01687978
44
+ 43: n01688243
45
+ 44: n01689811
46
+ 45: n01692333
47
+ 46: n01693334
48
+ 47: n01694178
49
+ 48: n01695060
50
+ 49: n01697457
51
+ 50: n01698640
52
+ 51: n01704323
53
+ 52: n01728572
54
+ 53: n01728920
55
+ 54: n01729322
56
+ 55: n01729977
57
+ 56: n01734418
58
+ 57: n01735189
59
+ 58: n01737021
60
+ 59: n01739381
61
+ 60: n01740131
62
+ 61: n01742172
63
+ 62: n01744401
64
+ 63: n01748264
65
+ 64: n01749939
66
+ 65: n01751748
67
+ 66: n01753488
68
+ 67: n01755581
69
+ 68: n01756291
70
+ 69: n01768244
71
+ 70: n01770081
72
+ 71: n01770393
73
+ 72: n01773157
74
+ 73: n01773549
75
+ 74: n01773797
76
+ 75: n01774384
77
+ 76: n01774750
78
+ 77: n01775062
79
+ 78: n04432308
80
+ 79: n01784675
81
+ 80: n01795545
82
+ 81: n01796340
83
+ 82: n01797886
84
+ 83: n01798484
85
+ 84: n01806143
86
+ 85: n07647321
87
+ 86: n07647496
88
+ 87: n01817953
89
+ 88: n01818515
90
+ 89: n01819313
91
+ 90: n01820546
92
+ 91: n01824575
93
+ 92: n01828970
94
+ 93: n01829413
95
+ 94: n01833805
96
+ 95: n01843065
97
+ 96: n01843383
98
+ 97: n01847000
99
+ 98: n01855032
100
+ 99: n07646821
101
+ 100: n01860187
102
+ 101: n01871265
103
+ 102: n01872772
104
+ 103: n01873310
105
+ 104: n01877812
106
+ 105: n01882714
107
+ 106: n01883070
108
+ 107: n01910747
109
+ 108: n01914609
110
+ 109: n01917289
111
+ 110: n01924916
112
+ 111: n01930112
113
+ 112: n01943899
114
+ 113: n01944390
115
+ 114: n13719102
116
+ 115: n01950731
117
+ 116: n01955084
118
+ 117: n01968897
119
+ 118: n01978287
120
+ 119: n01978455
121
+ 120: n01980166
122
+ 121: n01981276
123
+ 122: n01983481
124
+ 123: n01984695
125
+ 124: n01985128
126
+ 125: n01986214
127
+ 126: n01990800
128
+ 127: n02002556
129
+ 128: n02002724
130
+ 129: n02006656
131
+ 130: n02007558
132
+ 131: n02009229
133
+ 132: n02009912
134
+ 133: n02011460
135
+ 134: n03126707
136
+ 135: n02013706
137
+ 136: n02017213
138
+ 137: n02018207
139
+ 138: n02018795
140
+ 139: n02025239
141
+ 140: n02027492
142
+ 141: n02028035
143
+ 142: n02033041
144
+ 143: n02037110
145
+ 144: n02051845
146
+ 145: n02056570
147
+ 146: n02058221
148
+ 147: n02066245
149
+ 148: n02071294
150
+ 149: n02074367
151
+ 150: n02077923
152
+ 151: n08742578
153
+ 152: n02085782
154
+ 153: n02085936
155
+ 154: n02086079
156
+ 155: n02086240
157
+ 156: n02086646
158
+ 157: n02086910
159
+ 158: n02087046
160
+ 159: n02087394
161
+ 160: n02088094
162
+ 161: n02088238
163
+ 162: n02088364
164
+ 163: n02088466
165
+ 164: n02088632
166
+ 165: n02089078
167
+ 166: n02089867
168
+ 167: n02089973
169
+ 168: n02090379
170
+ 169: n02090622
171
+ 170: n02090721
172
+ 171: n02091032
173
+ 172: n02091134
174
+ 173: n02091244
175
+ 174: n02091467
176
+ 175: n02091635
177
+ 176: n02091831
178
+ 177: n02092002
179
+ 178: n02092339
180
+ 179: n02093256
181
+ 180: n02093428
182
+ 181: n02093647
183
+ 182: n02093754
184
+ 183: n02093859
185
+ 184: n02093991
186
+ 185: n02094114
187
+ 186: n02094258
188
+ 187: n02094433
189
+ 188: n02095314
190
+ 189: n02095570
191
+ 190: n02095889
192
+ 191: n02096051
193
+ 192: n02096177
194
+ 193: n02096294
195
+ 194: n02096437
196
+ 195: n02096585
197
+ 196: n02097047
198
+ 197: n02097130
199
+ 198: n02097209
200
+ 199: n02097298
201
+ 200: n02097474
202
+ 201: n02097658
203
+ 202: n02098105
204
+ 203: n02098286
205
+ 204: n02098413
206
+ 205: n02099267
207
+ 206: n02099429
208
+ 207: n02099601
209
+ 208: n02099712
210
+ 209: n02099849
211
+ 210: n02100236
212
+ 211: n02100583
213
+ 212: n02100735
214
+ 213: n02100877
215
+ 214: n02101006
216
+ 215: n02101388
217
+ 216: n02101556
218
+ 217: n02102040
219
+ 218: n02102177
220
+ 219: n02102318
221
+ 220: n02102480
222
+ 221: n02102973
223
+ 222: n02104029
224
+ 223: n02104365
225
+ 224: n02105056
226
+ 225: n02105162
227
+ 226: n02105251
228
+ 227: n02105412
229
+ 228: n02105505
230
+ 229: n02105641
231
+ 230: n02105855
232
+ 231: n02106030
233
+ 232: n02106166
234
+ 233: n02106382
235
+ 234: n02106550
236
+ 235: n02106662
237
+ 236: n02107142
238
+ 237: n02107312
239
+ 238: n02107574
240
+ 239: n02107683
241
+ 240: n02107908
242
+ 241: n02108000
243
+ 242: n02108089
244
+ 243: n02108422
245
+ 244: n02108551
246
+ 245: n02108915
247
+ 246: n02109047
248
+ 247: n02109525
249
+ 248: n02109961
250
+ 249: n02110063
251
+ 250: n02110185
252
+ 251: n02110341
253
+ 252: n02110627
254
+ 253: n02110806
255
+ 254: n02110958
256
+ 255: n02111129
257
+ 256: n02111277
258
+ 257: n02111500
259
+ 258: n02111889
260
+ 259: n02112018
261
+ 260: n02112137
262
+ 261: n02112350
263
+ 262: n02112706
264
+ 263: n02113023
265
+ 264: n02113186
266
+ 265: n02113624
267
+ 266: n02113712
268
+ 267: n02113799
269
+ 268: n02113978
270
+ 269: n02114367
271
+ 270: n02114548
272
+ 271: n02114712
273
+ 272: n02114855
274
+ 273: n02115641
275
+ 274: n02115913
276
+ 275: n02116738
277
+ 276: n02117135
278
+ 277: n02119022
279
+ 278: n02119789
280
+ 279: n02120079
281
+ 280: n02120505
282
+ 281: n02123045
283
+ 282: n02123159
284
+ 283: n02123394
285
+ 284: n02123597
286
+ 285: n02124075
287
+ 286: n02125311
288
+ 287: n02127052
289
+ 288: n02128385
290
+ 289: n02128757
291
+ 290: n02128925
292
+ 291: n02129165
293
+ 292: n02129604
294
+ 293: n02130308
295
+ 294: n02132136
296
+ 295: n02133161
297
+ 296: n02134084
298
+ 297: n02134418
299
+ 298: n02137549
300
+ 299: n02138441
301
+ 300: n02165105
302
+ 301: n02165456
303
+ 302: n02167151
304
+ 303: n02168699
305
+ 304: n02169497
306
+ 305: n02172182
307
+ 306: n02174001
308
+ 307: n02177972
309
+ 308: n03373237
310
+ 309: n07975909
311
+ 310: n02219486
312
+ 311: n02226429
313
+ 312: n02229544
314
+ 313: n02231487
315
+ 314: n02233338
316
+ 315: n02236044
317
+ 316: n02256656
318
+ 317: n02259212
319
+ 318: n02264363
320
+ 319: n02268443
321
+ 320: n02268853
322
+ 321: n02276258
323
+ 322: n02277742
324
+ 323: n02279972
325
+ 324: n02280649
326
+ 325: n02281406
327
+ 326: n02281787
328
+ 327: n02317335
329
+ 328: n02319095
330
+ 329: n02321529
331
+ 330: n02325366
332
+ 331: n02326432
333
+ 332: n02328150
334
+ 333: n02342885
335
+ 334: n02346627
336
+ 335: n02356798
337
+ 336: n02361337
338
+ 337: n05262120
339
+ 338: n02364673
340
+ 339: n02389026
341
+ 340: n02391049
342
+ 341: n02395406
343
+ 342: n02396427
344
+ 343: n02397096
345
+ 344: n02398521
346
+ 345: n02403003
347
+ 346: n02408429
348
+ 347: n02410509
349
+ 348: n02412080
350
+ 349: n02415577
351
+ 350: n02417914
352
+ 351: n02422106
353
+ 352: n02422699
354
+ 353: n02423022
355
+ 354: n02437312
356
+ 355: n02437616
357
+ 356: n10771990
358
+ 357: n14765497
359
+ 358: n02443114
360
+ 359: n02443484
361
+ 360: n14765785
362
+ 361: n02445715
363
+ 362: n02447366
364
+ 363: n02454379
365
+ 364: n02457408
366
+ 365: n02480495
367
+ 366: n02480855
368
+ 367: n02481823
369
+ 368: n02483362
370
+ 369: n02483708
371
+ 370: n02484975
372
+ 371: n02486261
373
+ 372: n02486410
374
+ 373: n02487347
375
+ 374: n02488291
376
+ 375: n02488702
377
+ 376: n02489166
378
+ 377: n02490219
379
+ 378: n02492035
380
+ 379: n02492660
381
+ 380: n02493509
382
+ 381: n02493793
383
+ 382: n02494079
384
+ 383: n02497673
385
+ 384: n02500267
386
+ 385: n02504013
387
+ 386: n02504458
388
+ 387: n02509815
389
+ 388: n02510455
390
+ 389: n02514041
391
+ 390: n07783967
392
+ 391: n02536864
393
+ 392: n02606052
394
+ 393: n02607072
395
+ 394: n02640242
396
+ 395: n02641379
397
+ 396: n02643566
398
+ 397: n02655020
399
+ 398: n02666347
400
+ 399: n02667093
401
+ 400: n02669723
402
+ 401: n02672831
403
+ 402: n02676566
404
+ 403: n02687172
405
+ 404: n02690373
406
+ 405: n02692877
407
+ 406: n02699494
408
+ 407: n02701002
409
+ 408: n02704792
410
+ 409: n02708093
411
+ 410: n02727426
412
+ 411: n08496334
413
+ 412: n02747177
414
+ 413: n02749479
415
+ 414: n02769748
416
+ 415: n02776631
417
+ 416: n02777292
418
+ 417: n02782329
419
+ 418: n02783161
420
+ 419: n02786058
421
+ 420: n02787622
422
+ 421: n02788148
423
+ 422: n02790996
424
+ 423: n02791124
425
+ 424: n02791270
426
+ 425: n02793495
427
+ 426: n02794156
428
+ 427: n02795169
429
+ 428: n02797295
430
+ 429: n02799071
431
+ 430: n02802426
432
+ 431: n02804515
433
+ 432: n02804610
434
+ 433: n02807133
435
+ 434: n02808304
436
+ 435: n02808440
437
+ 436: n02814533
438
+ 437: n02814860
439
+ 438: n02815834
440
+ 439: n02817516
441
+ 440: n02823428
442
+ 441: n02823750
443
+ 442: n02825657
444
+ 443: n02834397
445
+ 444: n02835271
446
+ 445: n02837789
447
+ 446: n02840245
448
+ 447: n02841315
449
+ 448: n02843684
450
+ 449: n02859443
451
+ 450: n02860847
452
+ 451: n02865351
453
+ 452: n02869837
454
+ 453: n02870880
455
+ 454: n02871525
456
+ 455: n02877765
457
+ 456: n02880308
458
+ 457: n02883205
459
+ 458: n02892201
460
+ 459: n02892767
461
+ 460: n02894605
462
+ 461: n02895154
463
+ 462: n12520864
464
+ 463: n02909870
465
+ 464: n02910353
466
+ 465: n02916936
467
+ 466: n02917067
468
+ 467: n02927161
469
+ 468: n02930766
470
+ 469: n02939185
471
+ 470: n02948072
472
+ 471: n02950826
473
+ 472: n02951358
474
+ 473: n02951585
475
+ 474: n02963159
476
+ 475: n02965783
477
+ 476: n02966193
478
+ 477: n02966687
479
+ 478: n02971356
480
+ 479: n02974003
481
+ 480: n02977058
482
+ 481: n02978881
483
+ 482: n02979186
484
+ 483: n02980441
485
+ 484: n02981792
486
+ 485: n02988304
487
+ 486: n02992211
488
+ 487: n02992529
489
+ 488: n13652994
490
+ 489: n03000134
491
+ 490: n03000247
492
+ 491: n03000684
493
+ 492: n03014705
494
+ 493: n03016953
495
+ 494: n03017168
496
+ 495: n03018349
497
+ 496: n03026506
498
+ 497: n03028079
499
+ 498: n03032252
500
+ 499: n03041632
501
+ 500: n03042490
502
+ 501: n03045698
503
+ 502: n03047690
504
+ 503: n03062245
505
+ 504: n03063599
506
+ 505: n03063689
507
+ 506: n03065424
508
+ 507: n03075370
509
+ 508: n03085013
510
+ 509: n03089624
511
+ 510: n03095699
512
+ 511: n03100240
513
+ 512: n03109150
514
+ 513: n03110669
515
+ 514: n03124043
516
+ 515: n03124170
517
+ 516: n15142452
518
+ 517: n03126707
519
+ 518: n03127747
520
+ 519: n03127925
521
+ 520: n03131574
522
+ 521: n03133878
523
+ 522: n03134739
524
+ 523: n03141823
525
+ 524: n03146219
526
+ 525: n03160309
527
+ 526: n03179701
528
+ 527: n03180011
529
+ 528: n03187595
530
+ 529: n03188531
531
+ 530: n03196217
532
+ 531: n03197337
533
+ 532: n03201208
534
+ 533: n03207743
535
+ 534: n03207941
536
+ 535: n03208938
537
+ 536: n03216828
538
+ 537: n03218198
539
+ 538: n13872072
540
+ 539: n03223299
541
+ 540: n03240683
542
+ 541: n03249569
543
+ 542: n07647870
544
+ 543: n03255030
545
+ 544: n03259401
546
+ 545: n03271574
547
+ 546: n03272010
548
+ 547: n03272562
549
+ 548: n03290653
550
+ 549: n13869788
551
+ 550: n03297495
552
+ 551: n03314780
553
+ 552: n03325584
554
+ 553: n03337140
555
+ 554: n03344393
556
+ 555: n03345487
557
+ 556: n03347037
558
+ 557: n03355925
559
+ 558: n03372029
560
+ 559: n03376595
561
+ 560: n03379051
562
+ 561: n03384352
563
+ 562: n03388043
564
+ 563: n03388183
565
+ 564: n03388549
566
+ 565: n03393912
567
+ 566: n03394916
568
+ 567: n03400231
569
+ 568: n03404251
570
+ 569: n03417042
571
+ 570: n03424325
572
+ 571: n03425413
573
+ 572: n03443371
574
+ 573: n03444034
575
+ 574: n03445777
576
+ 575: n03445924
577
+ 576: n03447447
578
+ 577: n03447721
579
+ 578: n08286342
580
+ 579: n03452741
581
+ 580: n03457902
582
+ 581: n03459775
583
+ 582: n03461385
584
+ 583: n03467068
585
+ 584: n03476684
586
+ 585: n03476991
587
+ 586: n03478589
588
+ 587: n03482001
589
+ 588: n03482405
590
+ 589: n03483316
591
+ 590: n03485407
592
+ 591: n03485794
593
+ 592: n03492542
594
+ 593: n03494278
595
+ 594: n03495570
596
+ 595: n10161363
597
+ 596: n03498962
598
+ 597: n03527565
599
+ 598: n03529860
600
+ 599: n09218315
601
+ 600: n03532672
602
+ 601: n03534580
603
+ 602: n03535780
604
+ 603: n03538406
605
+ 604: n03544143
606
+ 605: n03584254
607
+ 606: n03584829
608
+ 607: n03590841
609
+ 608: n03594734
610
+ 609: n03594945
611
+ 610: n03595614
612
+ 611: n03598930
613
+ 612: n03599486
614
+ 613: n03602883
615
+ 614: n03617480
616
+ 615: n03623198
617
+ 616: n15102712
618
+ 617: n03630383
619
+ 618: n03633091
620
+ 619: n03637318
621
+ 620: n03642806
622
+ 621: n03649909
623
+ 622: n03657121
624
+ 623: n03658185
625
+ 624: n07977870
626
+ 625: n03662601
627
+ 626: n03666591
628
+ 627: n03670208
629
+ 628: n03673027
630
+ 629: n03676483
631
+ 630: n03680355
632
+ 631: n03690938
633
+ 632: n03691459
634
+ 633: n03692522
635
+ 634: n03697007
636
+ 635: n03706229
637
+ 636: n03709823
638
+ 637: n03710193
639
+ 638: n03710637
640
+ 639: n03710721
641
+ 640: n03717622
642
+ 641: n03720891
643
+ 642: n03721384
644
+ 643: n03725035
645
+ 644: n03729826
646
+ 645: n03733131
647
+ 646: n03733281
648
+ 647: n03733805
649
+ 648: n03742115
650
+ 649: n03743016
651
+ 650: n03759954
652
+ 651: n03761084
653
+ 652: n03763968
654
+ 653: n03764736
655
+ 654: n03769881
656
+ 655: n03770439
657
+ 656: n03770679
658
+ 657: n03773504
659
+ 658: n03775071
660
+ 659: n03775546
661
+ 660: n03776460
662
+ 661: n03777568
663
+ 662: n03777754
664
+ 663: n03781244
665
+ 664: n03782006
666
+ 665: n03785016
667
+ 666: n14955889
668
+ 667: n03787032
669
+ 668: n03788195
670
+ 669: n03788365
671
+ 670: n03791053
672
+ 671: n03792782
673
+ 672: n03792972
674
+ 673: n03793489
675
+ 674: n03794056
676
+ 675: n03796401
677
+ 676: n03803284
678
+ 677: n13652335
679
+ 678: n03814639
680
+ 679: n03814906
681
+ 680: n03825788
682
+ 681: n03832673
683
+ 682: n03837869
684
+ 683: n03838899
685
+ 684: n03840681
686
+ 685: n03841143
687
+ 686: n03843555
688
+ 687: n03854065
689
+ 688: n03857828
690
+ 689: n03866082
691
+ 690: n03868242
692
+ 691: n03868863
693
+ 692: n07281099
694
+ 693: n03873416
695
+ 694: n03874293
696
+ 695: n03874599
697
+ 696: n03876231
698
+ 697: n03877472
699
+ 698: n08053121
700
+ 699: n03884397
701
+ 700: n03887697
702
+ 701: n03888257
703
+ 702: n03888605
704
+ 703: n03891251
705
+ 704: n03891332
706
+ 705: n03895866
707
+ 706: n03899768
708
+ 707: n03902125
709
+ 708: n03903868
710
+ 709: n03908618
711
+ 710: n03908714
712
+ 711: n03916031
713
+ 712: n03920288
714
+ 713: n03924679
715
+ 714: n03929660
716
+ 715: n03929855
717
+ 716: n03930313
718
+ 717: n03930630
719
+ 718: n03934042
720
+ 719: n03935335
721
+ 720: n03937543
722
+ 721: n03938244
723
+ 722: n03942813
724
+ 723: n03944341
725
+ 724: n03947888
726
+ 725: n03950228
727
+ 726: n03954731
728
+ 727: n03956157
729
+ 728: n03958227
730
+ 729: n03961711
731
+ 730: n03967562
732
+ 731: n03970156
733
+ 732: n03976467
734
+ 733: n08620881
735
+ 734: n03977966
736
+ 735: n03980874
737
+ 736: n03982430
738
+ 737: n03983396
739
+ 738: n03991062
740
+ 739: n03992509
741
+ 740: n03995372
742
+ 741: n03998194
743
+ 742: n04004767
744
+ 743: n13937284
745
+ 744: n04008634
746
+ 745: n04009801
747
+ 746: n04019541
748
+ 747: n04023962
749
+ 748: n13413294
750
+ 749: n04033901
751
+ 750: n04033995
752
+ 751: n04037443
753
+ 752: n04039381
754
+ 753: n09403211
755
+ 754: n04041544
756
+ 755: n04044716
757
+ 756: n04049303
758
+ 757: n04065272
759
+ 758: n07056680
760
+ 759: n04069434
761
+ 760: n04070727
762
+ 761: n04074963
763
+ 762: n04081281
764
+ 763: n04086273
765
+ 764: n04090263
766
+ 765: n04099969
767
+ 766: n04111531
768
+ 767: n04116512
769
+ 768: n04118538
770
+ 769: n04118776
771
+ 770: n04120489
772
+ 771: n04125116
773
+ 772: n04127249
774
+ 773: n04131690
775
+ 774: n04133789
776
+ 775: n04136333
777
+ 776: n04141076
778
+ 777: n04141327
779
+ 778: n04141975
780
+ 779: n04146614
781
+ 780: n04147291
782
+ 781: n04149813
783
+ 782: n04152593
784
+ 783: n04154340
785
+ 784: n07917272
786
+ 785: n04162706
787
+ 786: n04179913
788
+ 787: n04192698
789
+ 788: n04200800
790
+ 789: n04201297
791
+ 790: n04204238
792
+ 791: n04204347
793
+ 792: n04208427
794
+ 793: n04209133
795
+ 794: n04209239
796
+ 795: n04228054
797
+ 796: n04229816
798
+ 797: n04235860
799
+ 798: n04238763
800
+ 799: n04239074
801
+ 800: n04243546
802
+ 801: n04251144
803
+ 802: n04252077
804
+ 803: n04252225
805
+ 804: n04254120
806
+ 805: n04254680
807
+ 806: n04254777
808
+ 807: n04258138
809
+ 808: n04259630
810
+ 809: n04263257
811
+ 810: n04264628
812
+ 811: n04265275
813
+ 812: n04266014
814
+ 813: n04270147
815
+ 814: n04273569
816
+ 815: n04275363
817
+ 816: n05605498
818
+ 817: n04285008
819
+ 818: n04286575
820
+ 819: n08646566
821
+ 820: n04310018
822
+ 821: n04311004
823
+ 822: n04311174
824
+ 823: n04317175
825
+ 824: n04325704
826
+ 825: n04326547
827
+ 826: n04328186
828
+ 827: n04330267
829
+ 828: n04332243
830
+ 829: n04335435
831
+ 830: n04337157
832
+ 831: n04344873
833
+ 832: n04346328
834
+ 833: n04347754
835
+ 834: n04350905
836
+ 835: n04355338
837
+ 836: n04355933
838
+ 837: n04356056
839
+ 838: n04357314
840
+ 839: n04366367
841
+ 840: n04367480
842
+ 841: n04370456
843
+ 842: n04371430
844
+ 843: n14009946
845
+ 844: n04372370
846
+ 845: n04376876
847
+ 846: n04380533
848
+ 847: n04389033
849
+ 848: n04392985
850
+ 849: n04398044
851
+ 850: n04399382
852
+ 851: n04404412
853
+ 852: n04409515
854
+ 853: n04417672
855
+ 854: n04418357
856
+ 855: n04423845
857
+ 856: n04428191
858
+ 857: n04429376
859
+ 858: n04435653
860
+ 859: n04442312
861
+ 860: n04443257
862
+ 861: n04447861
863
+ 862: n04456115
864
+ 863: n04458633
865
+ 864: n04461696
866
+ 865: n04462240
867
+ 866: n04465666
868
+ 867: n04467665
869
+ 868: n04476259
870
+ 869: n04479046
871
+ 870: n04482393
872
+ 871: n04483307
873
+ 872: n04485082
874
+ 873: n04486054
875
+ 874: n04487081
876
+ 875: n04487394
877
+ 876: n04493381
878
+ 877: n04501370
879
+ 878: n04505470
880
+ 879: n04507155
881
+ 880: n04509417
882
+ 881: n04515003
883
+ 882: n04517823
884
+ 883: n04522168
885
+ 884: n04523525
886
+ 885: n04525038
887
+ 886: n04525305
888
+ 887: n04532106
889
+ 888: n04532670
890
+ 889: n04536866
891
+ 890: n04540053
892
+ 891: n04542943
893
+ 892: n04548280
894
+ 893: n04548362
895
+ 894: n04550184
896
+ 895: n04552348
897
+ 896: n04553703
898
+ 897: n04554684
899
+ 898: n04557648
900
+ 899: n04560804
901
+ 900: n04562935
902
+ 901: n04579145
903
+ 902: n04579667
904
+ 903: n04584207
905
+ 904: n04589890
906
+ 905: n04590129
907
+ 906: n04591157
908
+ 907: n04591713
909
+ 908: n10782135
910
+ 909: n04596742
911
+ 910: n04598010
912
+ 911: n04599235
913
+ 912: n04604644
914
+ 913: n14423870
915
+ 914: n04612504
916
+ 915: n04613696
917
+ 916: n06359193
918
+ 917: n06596364
919
+ 918: n06785654
920
+ 919: n06794110
921
+ 920: n06874185
922
+ 921: n07248320
923
+ 922: n07565083
924
+ 923: n07657664
925
+ 924: n07583066
926
+ 925: n07584110
927
+ 926: n07590611
928
+ 927: n07613480
929
+ 928: n07614500
930
+ 929: n07615774
931
+ 930: n07684084
932
+ 931: n07693725
933
+ 932: n07695742
934
+ 933: n07697313
935
+ 934: n07697537
936
+ 935: n07711569
937
+ 936: n07714571
938
+ 937: n07714990
939
+ 938: n07715103
940
+ 939: n12159804
941
+ 940: n12160303
942
+ 941: n12160857
943
+ 942: n07717556
944
+ 943: n07718472
945
+ 944: n07718747
946
+ 945: n07720875
947
+ 946: n07730033
948
+ 947: n13001041
949
+ 948: n07742313
950
+ 949: n12630144
951
+ 950: n14991210
952
+ 951: n07749582
953
+ 952: n07753113
954
+ 953: n07753275
955
+ 954: n07753592
956
+ 955: n07754684
957
+ 956: n07760859
958
+ 957: n07768694
959
+ 958: n07802026
960
+ 959: n07831146
961
+ 960: n07836838
962
+ 961: n07860988
963
+ 962: n07871810
964
+ 963: n07873807
965
+ 964: n07875152
966
+ 965: n07880968
967
+ 966: n07892512
968
+ 967: n07920052
969
+ 968: n13904665
970
+ 969: n07932039
971
+ 970: n09193705
972
+ 971: n09229709
973
+ 972: n09246464
974
+ 973: n09256479
975
+ 974: n09288635
976
+ 975: n09332890
977
+ 976: n09399592
978
+ 977: n09421951
979
+ 978: n09428293
980
+ 979: n09468604
981
+ 980: n09472597
982
+ 981: n09835506
983
+ 982: n10148035
984
+ 983: n10565667
985
+ 984: n11879895
986
+ 985: n11939491
987
+ 986: n12057211
988
+ 987: n12144580
989
+ 988: n12267677
990
+ 989: n12620546
991
+ 990: n12768682
992
+ 991: n12985857
993
+ 992: n12998815
994
+ 993: n13037406
995
+ 994: n13040303
996
+ 995: n13044778
997
+ 996: n13052670
998
+ 997: n13054560
999
+ 998: n13133613
1000
+ 999: n15075141
data/inpainting_examples/6458524847_2f4c361183_k.png ADDED
data/inpainting_examples/6458524847_2f4c361183_k_mask.png ADDED
data/inpainting_examples/8399166846_f6fb4e4b8e_k.png ADDED
data/inpainting_examples/8399166846_f6fb4e4b8e_k_mask.png ADDED
data/inpainting_examples/alex-iby-G_Pk4D9rMLs.png ADDED
data/inpainting_examples/alex-iby-G_Pk4D9rMLs_mask.png ADDED
data/inpainting_examples/bench2.png ADDED
data/inpainting_examples/bench2_mask.png ADDED
data/inpainting_examples/bertrand-gabioud-CpuFzIsHYJ0.png ADDED
data/inpainting_examples/bertrand-gabioud-CpuFzIsHYJ0_mask.png ADDED
data/inpainting_examples/billow926-12-Wc-Zgx6Y.png ADDED
data/inpainting_examples/billow926-12-Wc-Zgx6Y_mask.png ADDED
data/inpainting_examples/overture-creations-5sI6fQgYIuo.png ADDED
data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png ADDED
data/inpainting_examples/photo-1583445095369-9c651e7e5d34.png ADDED
data/inpainting_examples/photo-1583445095369-9c651e7e5d34_mask.png ADDED
environment.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: ldm
2
+ channels:
3
+ - pytorch
4
+ - defaults
5
+ dependencies:
6
+ - python=3.8.5
7
+ - pip=20.3
8
+ - cudatoolkit=11.0
9
+ - pytorch=1.7.0
10
+ - torchvision=0.8.1
11
+ - numpy=1.19.2
12
+ - pip:
13
+ - albumentations==0.4.3
14
+ - opencv-python==4.1.2.30
15
+ - pudb==2019.2
16
+ - imageio==2.9.0
17
+ - imageio-ffmpeg==0.4.2
18
+ - pytorch-lightning==1.4.2
19
+ - omegaconf==2.1.1
20
+ - test-tube>=0.7.5
21
+ - streamlit>=0.73.1
22
+ - einops==0.3.0
23
+ - torch-fidelity==0.3.0
24
+ - transformers==4.3.1
25
+ - -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
26
+ - -e git+https://github.com/openai/CLIP.git@main#egg=clip
27
+ - -e .
ldm/data/__init__.py ADDED
File without changes
ldm/data/base.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ from torch.utils.data import Dataset, ConcatDataset, ChainDataset, IterableDataset
3
+
4
+
5
+ class Txt2ImgIterableBaseDataset(IterableDataset):
6
+ '''
7
+ Define an interface to make the IterableDatasets for text2img data chainable
8
+ '''
9
+ def __init__(self, num_records=0, valid_ids=None, size=256):
10
+ super().__init__()
11
+ self.num_records = num_records
12
+ self.valid_ids = valid_ids
13
+ self.sample_ids = valid_ids
14
+ self.size = size
15
+
16
+ print(f'{self.__class__.__name__} dataset contains {self.__len__()} examples.')
17
+
18
+ def __len__(self):
19
+ return self.num_records
20
+
21
+ @abstractmethod
22
+ def __iter__(self):
23
+ pass
ldm/data/imagenet.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, yaml, pickle, shutil, tarfile, glob
2
+ import cv2
3
+ import albumentations
4
+ import PIL
5
+ import numpy as np
6
+ import torchvision.transforms.functional as TF
7
+ from omegaconf import OmegaConf
8
+ from functools import partial
9
+ from PIL import Image
10
+ from tqdm import tqdm
11
+ from torch.utils.data import Dataset, Subset
12
+
13
+ import taming.data.utils as tdu
14
+ from taming.data.imagenet import str_to_indices, give_synsets_from_indices, download, retrieve
15
+ from taming.data.imagenet import ImagePaths
16
+
17
+ from ldm.modules.image_degradation import degradation_fn_bsr, degradation_fn_bsr_light
18
+
19
+
20
+ def synset2idx(path_to_yaml="data/index_synset.yaml"):
21
+ with open(path_to_yaml) as f:
22
+ di2s = yaml.load(f)
23
+ return dict((v,k) for k,v in di2s.items())
24
+
25
+
26
+ class ImageNetBase(Dataset):
27
+ def __init__(self, config=None):
28
+ self.config = config or OmegaConf.create()
29
+ if not type(self.config)==dict:
30
+ self.config = OmegaConf.to_container(self.config)
31
+ self.keep_orig_class_label = self.config.get("keep_orig_class_label", False)
32
+ self.process_images = True # if False we skip loading & processing images and self.data contains filepaths
33
+ self._prepare()
34
+ self._prepare_synset_to_human()
35
+ self._prepare_idx_to_synset()
36
+ self._prepare_human_to_integer_label()
37
+ self._load()
38
+
39
+ def __len__(self):
40
+ return len(self.data)
41
+
42
+ def __getitem__(self, i):
43
+ return self.data[i]
44
+
45
+ def _prepare(self):
46
+ raise NotImplementedError()
47
+
48
+ def _filter_relpaths(self, relpaths):
49
+ ignore = set([
50
+ "n06596364_9591.JPEG",
51
+ ])
52
+ relpaths = [rpath for rpath in relpaths if not rpath.split("/")[-1] in ignore]
53
+ if "sub_indices" in self.config:
54
+ indices = str_to_indices(self.config["sub_indices"])
55
+ synsets = give_synsets_from_indices(indices, path_to_yaml=self.idx2syn) # returns a list of strings
56
+ self.synset2idx = synset2idx(path_to_yaml=self.idx2syn)
57
+ files = []
58
+ for rpath in relpaths:
59
+ syn = rpath.split("/")[0]
60
+ if syn in synsets:
61
+ files.append(rpath)
62
+ return files
63
+ else:
64
+ return relpaths
65
+
66
+ def _prepare_synset_to_human(self):
67
+ SIZE = 2655750
68
+ URL = "https://heibox.uni-heidelberg.de/f/9f28e956cd304264bb82/?dl=1"
69
+ self.human_dict = os.path.join(self.root, "synset_human.txt")
70
+ if (not os.path.exists(self.human_dict) or
71
+ not os.path.getsize(self.human_dict)==SIZE):
72
+ download(URL, self.human_dict)
73
+
74
+ def _prepare_idx_to_synset(self):
75
+ URL = "https://heibox.uni-heidelberg.de/f/d835d5b6ceda4d3aa910/?dl=1"
76
+ self.idx2syn = os.path.join(self.root, "index_synset.yaml")
77
+ if (not os.path.exists(self.idx2syn)):
78
+ download(URL, self.idx2syn)
79
+
80
+ def _prepare_human_to_integer_label(self):
81
+ URL = "https://heibox.uni-heidelberg.de/f/2362b797d5be43b883f6/?dl=1"
82
+ self.human2integer = os.path.join(self.root, "imagenet1000_clsidx_to_labels.txt")
83
+ if (not os.path.exists(self.human2integer)):
84
+ download(URL, self.human2integer)
85
+ with open(self.human2integer, "r") as f:
86
+ lines = f.read().splitlines()
87
+ assert len(lines) == 1000
88
+ self.human2integer_dict = dict()
89
+ for line in lines:
90
+ value, key = line.split(":")
91
+ self.human2integer_dict[key] = int(value)
92
+
93
+ def _load(self):
94
+ with open(self.txt_filelist, "r") as f:
95
+ self.relpaths = f.read().splitlines()
96
+ l1 = len(self.relpaths)
97
+ self.relpaths = self._filter_relpaths(self.relpaths)
98
+ print("Removed {} files from filelist during filtering.".format(l1 - len(self.relpaths)))
99
+
100
+ self.synsets = [p.split("/")[0] for p in self.relpaths]
101
+ self.abspaths = [os.path.join(self.datadir, p) for p in self.relpaths]
102
+
103
+ unique_synsets = np.unique(self.synsets)
104
+ class_dict = dict((synset, i) for i, synset in enumerate(unique_synsets))
105
+ if not self.keep_orig_class_label:
106
+ self.class_labels = [class_dict[s] for s in self.synsets]
107
+ else:
108
+ self.class_labels = [self.synset2idx[s] for s in self.synsets]
109
+
110
+ with open(self.human_dict, "r") as f:
111
+ human_dict = f.read().splitlines()
112
+ human_dict = dict(line.split(maxsplit=1) for line in human_dict)
113
+
114
+ self.human_labels = [human_dict[s] for s in self.synsets]
115
+
116
+ labels = {
117
+ "relpath": np.array(self.relpaths),
118
+ "synsets": np.array(self.synsets),
119
+ "class_label": np.array(self.class_labels),
120
+ "human_label": np.array(self.human_labels),
121
+ }
122
+
123
+ if self.process_images:
124
+ self.size = retrieve(self.config, "size", default=256)
125
+ self.data = ImagePaths(self.abspaths,
126
+ labels=labels,
127
+ size=self.size,
128
+ random_crop=self.random_crop,
129
+ )
130
+ else:
131
+ self.data = self.abspaths
132
+
133
+
134
+ class ImageNetTrain(ImageNetBase):
135
+ NAME = "ILSVRC2012_train"
136
+ URL = "http://www.image-net.org/challenges/LSVRC/2012/"
137
+ AT_HASH = "a306397ccf9c2ead27155983c254227c0fd938e2"
138
+ FILES = [
139
+ "ILSVRC2012_img_train.tar",
140
+ ]
141
+ SIZES = [
142
+ 147897477120,
143
+ ]
144
+
145
+ def __init__(self, process_images=True, data_root=None, **kwargs):
146
+ self.process_images = process_images
147
+ self.data_root = data_root
148
+ super().__init__(**kwargs)
149
+
150
+ def _prepare(self):
151
+ if self.data_root:
152
+ self.root = os.path.join(self.data_root, self.NAME)
153
+ else:
154
+ cachedir = os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
155
+ self.root = os.path.join(cachedir, "autoencoders/data", self.NAME)
156
+
157
+ self.datadir = os.path.join(self.root, "data")
158
+ self.txt_filelist = os.path.join(self.root, "filelist.txt")
159
+ self.expected_length = 1281167
160
+ self.random_crop = retrieve(self.config, "ImageNetTrain/random_crop",
161
+ default=True)
162
+ if not tdu.is_prepared(self.root):
163
+ # prep
164
+ print("Preparing dataset {} in {}".format(self.NAME, self.root))
165
+
166
+ datadir = self.datadir
167
+ if not os.path.exists(datadir):
168
+ path = os.path.join(self.root, self.FILES[0])
169
+ if not os.path.exists(path) or not os.path.getsize(path)==self.SIZES[0]:
170
+ import academictorrents as at
171
+ atpath = at.get(self.AT_HASH, datastore=self.root)
172
+ assert atpath == path
173
+
174
+ print("Extracting {} to {}".format(path, datadir))
175
+ os.makedirs(datadir, exist_ok=True)
176
+ with tarfile.open(path, "r:") as tar:
177
+ tar.extractall(path=datadir)
178
+
179
+ print("Extracting sub-tars.")
180
+ subpaths = sorted(glob.glob(os.path.join(datadir, "*.tar")))
181
+ for subpath in tqdm(subpaths):
182
+ subdir = subpath[:-len(".tar")]
183
+ os.makedirs(subdir, exist_ok=True)
184
+ with tarfile.open(subpath, "r:") as tar:
185
+ tar.extractall(path=subdir)
186
+
187
+ filelist = glob.glob(os.path.join(datadir, "**", "*.JPEG"))
188
+ filelist = [os.path.relpath(p, start=datadir) for p in filelist]
189
+ filelist = sorted(filelist)
190
+ filelist = "\n".join(filelist)+"\n"
191
+ with open(self.txt_filelist, "w") as f:
192
+ f.write(filelist)
193
+
194
+ tdu.mark_prepared(self.root)
195
+
196
+
197
+ class ImageNetValidation(ImageNetBase):
198
+ NAME = "ILSVRC2012_validation"
199
+ URL = "http://www.image-net.org/challenges/LSVRC/2012/"
200
+ AT_HASH = "5d6d0df7ed81efd49ca99ea4737e0ae5e3a5f2e5"
201
+ VS_URL = "https://heibox.uni-heidelberg.de/f/3e0f6e9c624e45f2bd73/?dl=1"
202
+ FILES = [
203
+ "ILSVRC2012_img_val.tar",
204
+ "validation_synset.txt",
205
+ ]
206
+ SIZES = [
207
+ 6744924160,
208
+ 1950000,
209
+ ]
210
+
211
+ def __init__(self, process_images=True, data_root=None, **kwargs):
212
+ self.data_root = data_root
213
+ self.process_images = process_images
214
+ super().__init__(**kwargs)
215
+
216
+ def _prepare(self):
217
+ if self.data_root:
218
+ self.root = os.path.join(self.data_root, self.NAME)
219
+ else:
220
+ cachedir = os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
221
+ self.root = os.path.join(cachedir, "autoencoders/data", self.NAME)
222
+ self.datadir = os.path.join(self.root, "data")
223
+ self.txt_filelist = os.path.join(self.root, "filelist.txt")
224
+ self.expected_length = 50000
225
+ self.random_crop = retrieve(self.config, "ImageNetValidation/random_crop",
226
+ default=False)
227
+ if not tdu.is_prepared(self.root):
228
+ # prep
229
+ print("Preparing dataset {} in {}".format(self.NAME, self.root))
230
+
231
+ datadir = self.datadir
232
+ if not os.path.exists(datadir):
233
+ path = os.path.join(self.root, self.FILES[0])
234
+ if not os.path.exists(path) or not os.path.getsize(path)==self.SIZES[0]:
235
+ import academictorrents as at
236
+ atpath = at.get(self.AT_HASH, datastore=self.root)
237
+ assert atpath == path
238
+
239
+ print("Extracting {} to {}".format(path, datadir))
240
+ os.makedirs(datadir, exist_ok=True)
241
+ with tarfile.open(path, "r:") as tar:
242
+ tar.extractall(path=datadir)
243
+
244
+ vspath = os.path.join(self.root, self.FILES[1])
245
+ if not os.path.exists(vspath) or not os.path.getsize(vspath)==self.SIZES[1]:
246
+ download(self.VS_URL, vspath)
247
+
248
+ with open(vspath, "r") as f:
249
+ synset_dict = f.read().splitlines()
250
+ synset_dict = dict(line.split() for line in synset_dict)
251
+
252
+ print("Reorganizing into synset folders")
253
+ synsets = np.unique(list(synset_dict.values()))
254
+ for s in synsets:
255
+ os.makedirs(os.path.join(datadir, s), exist_ok=True)
256
+ for k, v in synset_dict.items():
257
+ src = os.path.join(datadir, k)
258
+ dst = os.path.join(datadir, v)
259
+ shutil.move(src, dst)
260
+
261
+ filelist = glob.glob(os.path.join(datadir, "**", "*.JPEG"))
262
+ filelist = [os.path.relpath(p, start=datadir) for p in filelist]
263
+ filelist = sorted(filelist)
264
+ filelist = "\n".join(filelist)+"\n"
265
+ with open(self.txt_filelist, "w") as f:
266
+ f.write(filelist)
267
+
268
+ tdu.mark_prepared(self.root)
269
+
270
+
271
+
272
+ class ImageNetSR(Dataset):
273
+ def __init__(self, size=None,
274
+ degradation=None, downscale_f=4, min_crop_f=0.5, max_crop_f=1.,
275
+ random_crop=True):
276
+ """
277
+ Imagenet Superresolution Dataloader
278
+ Performs following ops in order:
279
+ 1. crops a crop of size s from image either as random or center crop
280
+ 2. resizes crop to size with cv2.area_interpolation
281
+ 3. degrades resized crop with degradation_fn
282
+
283
+ :param size: resizing to size after cropping
284
+ :param degradation: degradation_fn, e.g. cv_bicubic or bsrgan_light
285
+ :param downscale_f: Low Resolution Downsample factor
286
+ :param min_crop_f: determines crop size s,
287
+ where s = c * min_img_side_len with c sampled from interval (min_crop_f, max_crop_f)
288
+ :param max_crop_f: ""
289
+ :param data_root:
290
+ :param random_crop:
291
+ """
292
+ self.base = self.get_base()
293
+ assert size
294
+ assert (size / downscale_f).is_integer()
295
+ self.size = size
296
+ self.LR_size = int(size / downscale_f)
297
+ self.min_crop_f = min_crop_f
298
+ self.max_crop_f = max_crop_f
299
+ assert(max_crop_f <= 1.)
300
+ self.center_crop = not random_crop
301
+
302
+ self.image_rescaler = albumentations.SmallestMaxSize(max_size=size, interpolation=cv2.INTER_AREA)
303
+
304
+ self.pil_interpolation = False # gets reset later if incase interp_op is from pillow
305
+
306
+ if degradation == "bsrgan":
307
+ self.degradation_process = partial(degradation_fn_bsr, sf=downscale_f)
308
+
309
+ elif degradation == "bsrgan_light":
310
+ self.degradation_process = partial(degradation_fn_bsr_light, sf=downscale_f)
311
+
312
+ else:
313
+ interpolation_fn = {
314
+ "cv_nearest": cv2.INTER_NEAREST,
315
+ "cv_bilinear": cv2.INTER_LINEAR,
316
+ "cv_bicubic": cv2.INTER_CUBIC,
317
+ "cv_area": cv2.INTER_AREA,
318
+ "cv_lanczos": cv2.INTER_LANCZOS4,
319
+ "pil_nearest": PIL.Image.NEAREST,
320
+ "pil_bilinear": PIL.Image.BILINEAR,
321
+ "pil_bicubic": PIL.Image.BICUBIC,
322
+ "pil_box": PIL.Image.BOX,
323
+ "pil_hamming": PIL.Image.HAMMING,
324
+ "pil_lanczos": PIL.Image.LANCZOS,
325
+ }[degradation]
326
+
327
+ self.pil_interpolation = degradation.startswith("pil_")
328
+
329
+ if self.pil_interpolation:
330
+ self.degradation_process = partial(TF.resize, size=self.LR_size, interpolation=interpolation_fn)
331
+
332
+ else:
333
+ self.degradation_process = albumentations.SmallestMaxSize(max_size=self.LR_size,
334
+ interpolation=interpolation_fn)
335
+
336
+ def __len__(self):
337
+ return len(self.base)
338
+
339
+ def __getitem__(self, i):
340
+ example = self.base[i]
341
+ image = Image.open(example["file_path_"])
342
+
343
+ if not image.mode == "RGB":
344
+ image = image.convert("RGB")
345
+
346
+ image = np.array(image).astype(np.uint8)
347
+
348
+ min_side_len = min(image.shape[:2])
349
+ crop_side_len = min_side_len * np.random.uniform(self.min_crop_f, self.max_crop_f, size=None)
350
+ crop_side_len = int(crop_side_len)
351
+
352
+ if self.center_crop:
353
+ self.cropper = albumentations.CenterCrop(height=crop_side_len, width=crop_side_len)
354
+
355
+ else:
356
+ self.cropper = albumentations.RandomCrop(height=crop_side_len, width=crop_side_len)
357
+
358
+ image = self.cropper(image=image)["image"]
359
+ image = self.image_rescaler(image=image)["image"]
360
+
361
+ if self.pil_interpolation:
362
+ image_pil = PIL.Image.fromarray(image)
363
+ LR_image = self.degradation_process(image_pil)
364
+ LR_image = np.array(LR_image).astype(np.uint8)
365
+
366
+ else:
367
+ LR_image = self.degradation_process(image=image)["image"]
368
+
369
+ example["image"] = (image/127.5 - 1.0).astype(np.float32)
370
+ example["LR_image"] = (LR_image/127.5 - 1.0).astype(np.float32)
371
+
372
+ return example
373
+
374
+
375
+ class ImageNetSRTrain(ImageNetSR):
376
+ def __init__(self, **kwargs):
377
+ super().__init__(**kwargs)
378
+
379
+ def get_base(self):
380
+ with open("data/imagenet_train_hr_indices.p", "rb") as f:
381
+ indices = pickle.load(f)
382
+ dset = ImageNetTrain(process_images=False,)
383
+ return Subset(dset, indices)
384
+
385
+
386
+ class ImageNetSRValidation(ImageNetSR):
387
+ def __init__(self, **kwargs):
388
+ super().__init__(**kwargs)
389
+
390
+ def get_base(self):
391
+ with open("data/imagenet_val_hr_indices.p", "rb") as f:
392
+ indices = pickle.load(f)
393
+ dset = ImageNetValidation(process_images=False,)
394
+ return Subset(dset, indices)
ldm/data/lsun.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import PIL
4
+ from PIL import Image
5
+ from torch.utils.data import Dataset
6
+ from torchvision import transforms
7
+
8
+
9
+ class LSUNBase(Dataset):
10
+ def __init__(self,
11
+ txt_file,
12
+ data_root,
13
+ size=None,
14
+ interpolation="bicubic",
15
+ flip_p=0.5
16
+ ):
17
+ self.data_paths = txt_file
18
+ self.data_root = data_root
19
+ with open(self.data_paths, "r") as f:
20
+ self.image_paths = f.read().splitlines()
21
+ self._length = len(self.image_paths)
22
+ self.labels = {
23
+ "relative_file_path_": [l for l in self.image_paths],
24
+ "file_path_": [os.path.join(self.data_root, l)
25
+ for l in self.image_paths],
26
+ }
27
+
28
+ self.size = size
29
+ self.interpolation = {"linear": PIL.Image.LINEAR,
30
+ "bilinear": PIL.Image.BILINEAR,
31
+ "bicubic": PIL.Image.BICUBIC,
32
+ "lanczos": PIL.Image.LANCZOS,
33
+ }[interpolation]
34
+ self.flip = transforms.RandomHorizontalFlip(p=flip_p)
35
+
36
+ def __len__(self):
37
+ return self._length
38
+
39
+ def __getitem__(self, i):
40
+ example = dict((k, self.labels[k][i]) for k in self.labels)
41
+ image = Image.open(example["file_path_"])
42
+ if not image.mode == "RGB":
43
+ image = image.convert("RGB")
44
+
45
+ # default to score-sde preprocessing
46
+ img = np.array(image).astype(np.uint8)
47
+ crop = min(img.shape[0], img.shape[1])
48
+ h, w, = img.shape[0], img.shape[1]
49
+ img = img[(h - crop) // 2:(h + crop) // 2,
50
+ (w - crop) // 2:(w + crop) // 2]
51
+
52
+ image = Image.fromarray(img)
53
+ if self.size is not None:
54
+ image = image.resize((self.size, self.size), resample=self.interpolation)
55
+
56
+ image = self.flip(image)
57
+ image = np.array(image).astype(np.uint8)
58
+ example["image"] = (image / 127.5 - 1.0).astype(np.float32)
59
+ return example
60
+
61
+
62
+ class LSUNChurchesTrain(LSUNBase):
63
+ def __init__(self, **kwargs):
64
+ super().__init__(txt_file="data/lsun/church_outdoor_train.txt", data_root="data/lsun/churches", **kwargs)
65
+
66
+
67
+ class LSUNChurchesValidation(LSUNBase):
68
+ def __init__(self, flip_p=0., **kwargs):
69
+ super().__init__(txt_file="data/lsun/church_outdoor_val.txt", data_root="data/lsun/churches",
70
+ flip_p=flip_p, **kwargs)
71
+
72
+
73
+ class LSUNBedroomsTrain(LSUNBase):
74
+ def __init__(self, **kwargs):
75
+ super().__init__(txt_file="data/lsun/bedrooms_train.txt", data_root="data/lsun/bedrooms", **kwargs)
76
+
77
+
78
+ class LSUNBedroomsValidation(LSUNBase):
79
+ def __init__(self, flip_p=0.0, **kwargs):
80
+ super().__init__(txt_file="data/lsun/bedrooms_val.txt", data_root="data/lsun/bedrooms",
81
+ flip_p=flip_p, **kwargs)
82
+
83
+
84
+ class LSUNCatsTrain(LSUNBase):
85
+ def __init__(self, **kwargs):
86
+ super().__init__(txt_file="data/lsun/cat_train.txt", data_root="data/lsun/cats", **kwargs)
87
+
88
+
89
+ class LSUNCatsValidation(LSUNBase):
90
+ def __init__(self, flip_p=0., **kwargs):
91
+ super().__init__(txt_file="data/lsun/cat_val.txt", data_root="data/lsun/cats",
92
+ flip_p=flip_p, **kwargs)
ldm/lr_scheduler.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ class LambdaWarmUpCosineScheduler:
5
+ """
6
+ note: use with a base_lr of 1.0
7
+ """
8
+ def __init__(self, warm_up_steps, lr_min, lr_max, lr_start, max_decay_steps, verbosity_interval=0):
9
+ self.lr_warm_up_steps = warm_up_steps
10
+ self.lr_start = lr_start
11
+ self.lr_min = lr_min
12
+ self.lr_max = lr_max
13
+ self.lr_max_decay_steps = max_decay_steps
14
+ self.last_lr = 0.
15
+ self.verbosity_interval = verbosity_interval
16
+
17
+ def schedule(self, n, **kwargs):
18
+ if self.verbosity_interval > 0:
19
+ if n % self.verbosity_interval == 0: print(f"current step: {n}, recent lr-multiplier: {self.last_lr}")
20
+ if n < self.lr_warm_up_steps:
21
+ lr = (self.lr_max - self.lr_start) / self.lr_warm_up_steps * n + self.lr_start
22
+ self.last_lr = lr
23
+ return lr
24
+ else:
25
+ t = (n - self.lr_warm_up_steps) / (self.lr_max_decay_steps - self.lr_warm_up_steps)
26
+ t = min(t, 1.0)
27
+ lr = self.lr_min + 0.5 * (self.lr_max - self.lr_min) * (
28
+ 1 + np.cos(t * np.pi))
29
+ self.last_lr = lr
30
+ return lr
31
+
32
+ def __call__(self, n, **kwargs):
33
+ return self.schedule(n,**kwargs)
34
+
35
+
36
+ class LambdaWarmUpCosineScheduler2:
37
+ """
38
+ supports repeated iterations, configurable via lists
39
+ note: use with a base_lr of 1.0.
40
+ """
41
+ def __init__(self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0):
42
+ assert len(warm_up_steps) == len(f_min) == len(f_max) == len(f_start) == len(cycle_lengths)
43
+ self.lr_warm_up_steps = warm_up_steps
44
+ self.f_start = f_start
45
+ self.f_min = f_min
46
+ self.f_max = f_max
47
+ self.cycle_lengths = cycle_lengths
48
+ self.cum_cycles = np.cumsum([0] + list(self.cycle_lengths))
49
+ self.last_f = 0.
50
+ self.verbosity_interval = verbosity_interval
51
+
52
+ def find_in_interval(self, n):
53
+ interval = 0
54
+ for cl in self.cum_cycles[1:]:
55
+ if n <= cl:
56
+ return interval
57
+ interval += 1
58
+
59
+ def schedule(self, n, **kwargs):
60
+ cycle = self.find_in_interval(n)
61
+ n = n - self.cum_cycles[cycle]
62
+ if self.verbosity_interval > 0:
63
+ if n % self.verbosity_interval == 0: print(f"current step: {n}, recent lr-multiplier: {self.last_f}, "
64
+ f"current cycle {cycle}")
65
+ if n < self.lr_warm_up_steps[cycle]:
66
+ f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
67
+ self.last_f = f
68
+ return f
69
+ else:
70
+ t = (n - self.lr_warm_up_steps[cycle]) / (self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle])
71
+ t = min(t, 1.0)
72
+ f = self.f_min[cycle] + 0.5 * (self.f_max[cycle] - self.f_min[cycle]) * (
73
+ 1 + np.cos(t * np.pi))
74
+ self.last_f = f
75
+ return f
76
+
77
+ def __call__(self, n, **kwargs):
78
+ return self.schedule(n, **kwargs)
79
+
80
+
81
+ class LambdaLinearScheduler(LambdaWarmUpCosineScheduler2):
82
+
83
+ def schedule(self, n, **kwargs):
84
+ cycle = self.find_in_interval(n)
85
+ n = n - self.cum_cycles[cycle]
86
+ if self.verbosity_interval > 0:
87
+ if n % self.verbosity_interval == 0: print(f"current step: {n}, recent lr-multiplier: {self.last_f}, "
88
+ f"current cycle {cycle}")
89
+
90
+ if n < self.lr_warm_up_steps[cycle]:
91
+ f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
92
+ self.last_f = f
93
+ return f
94
+ else:
95
+ f = self.f_min[cycle] + (self.f_max[cycle] - self.f_min[cycle]) * (self.cycle_lengths[cycle] - n) / (self.cycle_lengths[cycle])
96
+ self.last_f = f
97
+ return f
98
+
ldm/models/autoencoder.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pytorch_lightning as pl
3
+ import torch.nn.functional as F
4
+ from contextlib import contextmanager
5
+
6
+ from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
7
+
8
+ from ldm.modules.diffusionmodules.model import Encoder, Decoder
9
+ from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
10
+
11
+ from ldm.util import instantiate_from_config
12
+
13
+
14
+ class VQModel(pl.LightningModule):
15
+ def __init__(self,
16
+ ddconfig,
17
+ lossconfig,
18
+ n_embed,
19
+ embed_dim,
20
+ ckpt_path=None,
21
+ ignore_keys=[],
22
+ image_key="image",
23
+ colorize_nlabels=None,
24
+ monitor=None,
25
+ batch_resize_range=None,
26
+ scheduler_config=None,
27
+ lr_g_factor=1.0,
28
+ remap=None,
29
+ sane_index_shape=False, # tell vector quantizer to return indices as bhw
30
+ use_ema=False
31
+ ):
32
+ super().__init__()
33
+ self.embed_dim = embed_dim
34
+ self.n_embed = n_embed
35
+ self.image_key = image_key
36
+ self.encoder = Encoder(**ddconfig)
37
+ self.decoder = Decoder(**ddconfig)
38
+ self.loss = instantiate_from_config(lossconfig)
39
+ self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
40
+ remap=remap,
41
+ sane_index_shape=sane_index_shape)
42
+ self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
43
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
44
+ if colorize_nlabels is not None:
45
+ assert type(colorize_nlabels)==int
46
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
47
+ if monitor is not None:
48
+ self.monitor = monitor
49
+ self.batch_resize_range = batch_resize_range
50
+ if self.batch_resize_range is not None:
51
+ print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
52
+
53
+ self.use_ema = use_ema
54
+ if self.use_ema:
55
+ self.model_ema = LitEma(self)
56
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
57
+
58
+ if ckpt_path is not None:
59
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
60
+ self.scheduler_config = scheduler_config
61
+ self.lr_g_factor = lr_g_factor
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 init_from_ckpt(self, path, ignore_keys=list()):
79
+ sd = torch.load(path, map_location="cpu")["state_dict"]
80
+ keys = list(sd.keys())
81
+ for k in keys:
82
+ for ik in ignore_keys:
83
+ if k.startswith(ik):
84
+ print("Deleting key {} from state_dict.".format(k))
85
+ del sd[k]
86
+ missing, unexpected = self.load_state_dict(sd, strict=False)
87
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
88
+ if len(missing) > 0:
89
+ print(f"Missing Keys: {missing}")
90
+ print(f"Unexpected Keys: {unexpected}")
91
+
92
+ def on_train_batch_end(self, *args, **kwargs):
93
+ if self.use_ema:
94
+ self.model_ema(self)
95
+
96
+ def encode(self, x):
97
+ h = self.encoder(x)
98
+ h = self.quant_conv(h)
99
+ quant, emb_loss, info = self.quantize(h)
100
+ return quant, emb_loss, info
101
+
102
+ def encode_to_prequant(self, x):
103
+ h = self.encoder(x)
104
+ h = self.quant_conv(h)
105
+ return h
106
+
107
+ def decode(self, quant):
108
+ quant = self.post_quant_conv(quant)
109
+ dec = self.decoder(quant)
110
+ return dec
111
+
112
+ def decode_code(self, code_b):
113
+ quant_b = self.quantize.embed_code(code_b)
114
+ dec = self.decode(quant_b)
115
+ return dec
116
+
117
+ def forward(self, input, return_pred_indices=False):
118
+ quant, diff, (_,_,ind) = self.encode(input)
119
+ dec = self.decode(quant)
120
+ if return_pred_indices:
121
+ return dec, diff, ind
122
+ return dec, diff
123
+
124
+ def get_input(self, batch, k):
125
+ x = batch[k]
126
+ if len(x.shape) == 3:
127
+ x = x[..., None]
128
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
129
+ if self.batch_resize_range is not None:
130
+ lower_size = self.batch_resize_range[0]
131
+ upper_size = self.batch_resize_range[1]
132
+ if self.global_step <= 4:
133
+ # do the first few batches with max size to avoid later oom
134
+ new_resize = upper_size
135
+ else:
136
+ new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
137
+ if new_resize != x.shape[2]:
138
+ x = F.interpolate(x, size=new_resize, mode="bicubic")
139
+ x = x.detach()
140
+ return x
141
+
142
+ def training_step(self, batch, batch_idx, optimizer_idx):
143
+ # https://github.com/pytorch/pytorch/issues/37142
144
+ # try not to fool the heuristics
145
+ x = self.get_input(batch, self.image_key)
146
+ xrec, qloss, ind = self(x, return_pred_indices=True)
147
+
148
+ if optimizer_idx == 0:
149
+ # autoencode
150
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
151
+ last_layer=self.get_last_layer(), split="train",
152
+ predicted_indices=ind)
153
+
154
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
155
+ return aeloss
156
+
157
+ if optimizer_idx == 1:
158
+ # discriminator
159
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
160
+ last_layer=self.get_last_layer(), split="train")
161
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
162
+ return discloss
163
+
164
+ def validation_step(self, batch, batch_idx):
165
+ log_dict = self._validation_step(batch, batch_idx)
166
+ with self.ema_scope():
167
+ log_dict_ema = self._validation_step(batch, batch_idx, suffix="_ema")
168
+ return log_dict
169
+
170
+ def _validation_step(self, batch, batch_idx, suffix=""):
171
+ x = self.get_input(batch, self.image_key)
172
+ xrec, qloss, ind = self(x, return_pred_indices=True)
173
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
174
+ self.global_step,
175
+ last_layer=self.get_last_layer(),
176
+ split="val"+suffix,
177
+ predicted_indices=ind
178
+ )
179
+
180
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
181
+ self.global_step,
182
+ last_layer=self.get_last_layer(),
183
+ split="val"+suffix,
184
+ predicted_indices=ind
185
+ )
186
+ rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
187
+ self.log(f"val{suffix}/rec_loss", rec_loss,
188
+ prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
189
+ self.log(f"val{suffix}/aeloss", aeloss,
190
+ prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
191
+ if version.parse(pl.__version__) >= version.parse('1.4.0'):
192
+ del log_dict_ae[f"val{suffix}/rec_loss"]
193
+ self.log_dict(log_dict_ae)
194
+ self.log_dict(log_dict_disc)
195
+ return self.log_dict
196
+
197
+ def configure_optimizers(self):
198
+ lr_d = self.learning_rate
199
+ lr_g = self.lr_g_factor*self.learning_rate
200
+ print("lr_d", lr_d)
201
+ print("lr_g", lr_g)
202
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
203
+ list(self.decoder.parameters())+
204
+ list(self.quantize.parameters())+
205
+ list(self.quant_conv.parameters())+
206
+ list(self.post_quant_conv.parameters()),
207
+ lr=lr_g, betas=(0.5, 0.9))
208
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
209
+ lr=lr_d, betas=(0.5, 0.9))
210
+
211
+ if self.scheduler_config is not None:
212
+ scheduler = instantiate_from_config(self.scheduler_config)
213
+
214
+ print("Setting up LambdaLR scheduler...")
215
+ scheduler = [
216
+ {
217
+ 'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
218
+ 'interval': 'step',
219
+ 'frequency': 1
220
+ },
221
+ {
222
+ 'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
223
+ 'interval': 'step',
224
+ 'frequency': 1
225
+ },
226
+ ]
227
+ return [opt_ae, opt_disc], scheduler
228
+ return [opt_ae, opt_disc], []
229
+
230
+ def get_last_layer(self):
231
+ return self.decoder.conv_out.weight
232
+
233
+ def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
234
+ log = dict()
235
+ x = self.get_input(batch, self.image_key)
236
+ x = x.to(self.device)
237
+ if only_inputs:
238
+ log["inputs"] = x
239
+ return log
240
+ xrec, _ = self(x)
241
+ if x.shape[1] > 3:
242
+ # colorize with random projection
243
+ assert xrec.shape[1] > 3
244
+ x = self.to_rgb(x)
245
+ xrec = self.to_rgb(xrec)
246
+ log["inputs"] = x
247
+ log["reconstructions"] = xrec
248
+ if plot_ema:
249
+ with self.ema_scope():
250
+ xrec_ema, _ = self(x)
251
+ if x.shape[1] > 3: xrec_ema = self.to_rgb(xrec_ema)
252
+ log["reconstructions_ema"] = xrec_ema
253
+ return log
254
+
255
+ def to_rgb(self, x):
256
+ assert self.image_key == "segmentation"
257
+ if not hasattr(self, "colorize"):
258
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
259
+ x = F.conv2d(x, weight=self.colorize)
260
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
261
+ return x
262
+
263
+
264
+ class VQModelInterface(VQModel):
265
+ def __init__(self, embed_dim, *args, **kwargs):
266
+ super().__init__(embed_dim=embed_dim, *args, **kwargs)
267
+ self.embed_dim = embed_dim
268
+
269
+ def encode(self, x):
270
+ h = self.encoder(x)
271
+ h = self.quant_conv(h)
272
+ return h
273
+
274
+ def decode(self, h, force_not_quantize=False):
275
+ # also go through quantization layer
276
+ if not force_not_quantize:
277
+ quant, emb_loss, info = self.quantize(h)
278
+ else:
279
+ quant = h
280
+ quant = self.post_quant_conv(quant)
281
+ dec = self.decoder(quant)
282
+ return dec
283
+
284
+
285
+ class AutoencoderKL(pl.LightningModule):
286
+ def __init__(self,
287
+ ddconfig,
288
+ lossconfig,
289
+ embed_dim,
290
+ ckpt_path=None,
291
+ ignore_keys=[],
292
+ image_key="image",
293
+ colorize_nlabels=None,
294
+ monitor=None,
295
+ ):
296
+ super().__init__()
297
+ self.image_key = image_key
298
+ self.encoder = Encoder(**ddconfig)
299
+ self.decoder = Decoder(**ddconfig)
300
+ self.loss = instantiate_from_config(lossconfig)
301
+ assert ddconfig["double_z"]
302
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
303
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
304
+ self.embed_dim = embed_dim
305
+ if colorize_nlabels is not None:
306
+ assert type(colorize_nlabels)==int
307
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
308
+ if monitor is not None:
309
+ self.monitor = monitor
310
+ if ckpt_path is not None:
311
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
312
+
313
+ def init_from_ckpt(self, path, ignore_keys=list()):
314
+ sd = torch.load(path, map_location="cpu")["state_dict"]
315
+ keys = list(sd.keys())
316
+ for k in keys:
317
+ for ik in ignore_keys:
318
+ if k.startswith(ik):
319
+ print("Deleting key {} from state_dict.".format(k))
320
+ del sd[k]
321
+ self.load_state_dict(sd, strict=False)
322
+ print(f"Restored from {path}")
323
+
324
+ def encode(self, x):
325
+ h = self.encoder(x)
326
+ moments = self.quant_conv(h)
327
+ posterior = DiagonalGaussianDistribution(moments)
328
+ return posterior
329
+
330
+ def decode(self, z):
331
+ z = self.post_quant_conv(z)
332
+ dec = self.decoder(z)
333
+ return dec
334
+
335
+ def forward(self, input, sample_posterior=True):
336
+ posterior = self.encode(input)
337
+ if sample_posterior:
338
+ z = posterior.sample()
339
+ else:
340
+ z = posterior.mode()
341
+ dec = self.decode(z)
342
+ return dec, posterior
343
+
344
+ def get_input(self, batch, k):
345
+ x = batch[k]
346
+ if len(x.shape) == 3:
347
+ x = x[..., None]
348
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
349
+ return x
350
+
351
+ def training_step(self, batch, batch_idx, optimizer_idx):
352
+ inputs = self.get_input(batch, self.image_key)
353
+ reconstructions, posterior = self(inputs)
354
+
355
+ if optimizer_idx == 0:
356
+ # train encoder+decoder+logvar
357
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
358
+ last_layer=self.get_last_layer(), split="train")
359
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
360
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
361
+ return aeloss
362
+
363
+ if optimizer_idx == 1:
364
+ # train the discriminator
365
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
366
+ last_layer=self.get_last_layer(), split="train")
367
+
368
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
369
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
370
+ return discloss
371
+
372
+ def validation_step(self, batch, batch_idx):
373
+ inputs = self.get_input(batch, self.image_key)
374
+ reconstructions, posterior = self(inputs)
375
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
376
+ last_layer=self.get_last_layer(), split="val")
377
+
378
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
379
+ last_layer=self.get_last_layer(), split="val")
380
+
381
+ self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
382
+ self.log_dict(log_dict_ae)
383
+ self.log_dict(log_dict_disc)
384
+ return self.log_dict
385
+
386
+ def configure_optimizers(self):
387
+ lr = self.learning_rate
388
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
389
+ list(self.decoder.parameters())+
390
+ list(self.quant_conv.parameters())+
391
+ list(self.post_quant_conv.parameters()),
392
+ lr=lr, betas=(0.5, 0.9))
393
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
394
+ lr=lr, betas=(0.5, 0.9))
395
+ return [opt_ae, opt_disc], []
396
+
397
+ def get_last_layer(self):
398
+ return self.decoder.conv_out.weight
399
+
400
+ @torch.no_grad()
401
+ def log_images(self, batch, only_inputs=False, **kwargs):
402
+ log = dict()
403
+ x = self.get_input(batch, self.image_key)
404
+ x = x.to(self.device)
405
+ if not only_inputs:
406
+ xrec, posterior = self(x)
407
+ if x.shape[1] > 3:
408
+ # colorize with random projection
409
+ assert xrec.shape[1] > 3
410
+ x = self.to_rgb(x)
411
+ xrec = self.to_rgb(xrec)
412
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
413
+ log["reconstructions"] = xrec
414
+ log["inputs"] = x
415
+ return log
416
+
417
+ def to_rgb(self, x):
418
+ assert self.image_key == "segmentation"
419
+ if not hasattr(self, "colorize"):
420
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
421
+ x = F.conv2d(x, weight=self.colorize)
422
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
423
+ return x
424
+
425
+
426
+ class IdentityFirstStage(torch.nn.Module):
427
+ def __init__(self, *args, vq_interface=False, **kwargs):
428
+ self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
429
+ super().__init__()
430
+
431
+ def encode(self, x, *args, **kwargs):
432
+ return x
433
+
434
+ def decode(self, x, *args, **kwargs):
435
+ return x
436
+
437
+ def quantize(self, x, *args, **kwargs):
438
+ if self.vq_interface:
439
+ return x, None, [None, None, None]
440
+ return x
441
+
442
+ def forward(self, x, *args, **kwargs):
443
+ return x
ldm/models/diffusion/__init__.py ADDED
File without changes
ldm/models/diffusion/classifier.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import pytorch_lightning as pl
4
+ from omegaconf import OmegaConf
5
+ from torch.nn import functional as F
6
+ from torch.optim import AdamW
7
+ from torch.optim.lr_scheduler import LambdaLR
8
+ from copy import deepcopy
9
+ from einops import rearrange
10
+ from glob import glob
11
+ from natsort import natsorted
12
+
13
+ from ldm.modules.diffusionmodules.openaimodel import EncoderUNetModel, UNetModel
14
+ from ldm.util import log_txt_as_img, default, ismap, instantiate_from_config
15
+
16
+ __models__ = {
17
+ 'class_label': EncoderUNetModel,
18
+ 'segmentation': UNetModel
19
+ }
20
+
21
+
22
+ def disabled_train(self, mode=True):
23
+ """Overwrite model.train with this function to make sure train/eval mode
24
+ does not change anymore."""
25
+ return self
26
+
27
+
28
+ class NoisyLatentImageClassifier(pl.LightningModule):
29
+
30
+ def __init__(self,
31
+ diffusion_path,
32
+ num_classes,
33
+ ckpt_path=None,
34
+ pool='attention',
35
+ label_key=None,
36
+ diffusion_ckpt_path=None,
37
+ scheduler_config=None,
38
+ weight_decay=1.e-2,
39
+ log_steps=10,
40
+ monitor='val/loss',
41
+ *args,
42
+ **kwargs):
43
+ super().__init__(*args, **kwargs)
44
+ self.num_classes = num_classes
45
+ # get latest config of diffusion model
46
+ diffusion_config = natsorted(glob(os.path.join(diffusion_path, 'configs', '*-project.yaml')))[-1]
47
+ self.diffusion_config = OmegaConf.load(diffusion_config).model
48
+ self.diffusion_config.params.ckpt_path = diffusion_ckpt_path
49
+ self.load_diffusion()
50
+
51
+ self.monitor = monitor
52
+ self.numd = self.diffusion_model.first_stage_model.encoder.num_resolutions - 1
53
+ self.log_time_interval = self.diffusion_model.num_timesteps // log_steps
54
+ self.log_steps = log_steps
55
+
56
+ self.label_key = label_key if not hasattr(self.diffusion_model, 'cond_stage_key') \
57
+ else self.diffusion_model.cond_stage_key
58
+
59
+ assert self.label_key is not None, 'label_key neither in diffusion model nor in model.params'
60
+
61
+ if self.label_key not in __models__:
62
+ raise NotImplementedError()
63
+
64
+ self.load_classifier(ckpt_path, pool)
65
+
66
+ self.scheduler_config = scheduler_config
67
+ self.use_scheduler = self.scheduler_config is not None
68
+ self.weight_decay = weight_decay
69
+
70
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
71
+ sd = torch.load(path, map_location="cpu")
72
+ if "state_dict" in list(sd.keys()):
73
+ sd = sd["state_dict"]
74
+ keys = list(sd.keys())
75
+ for k in keys:
76
+ for ik in ignore_keys:
77
+ if k.startswith(ik):
78
+ print("Deleting key {} from state_dict.".format(k))
79
+ del sd[k]
80
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
81
+ sd, strict=False)
82
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
83
+ if len(missing) > 0:
84
+ print(f"Missing Keys: {missing}")
85
+ if len(unexpected) > 0:
86
+ print(f"Unexpected Keys: {unexpected}")
87
+
88
+ def load_diffusion(self):
89
+ model = instantiate_from_config(self.diffusion_config)
90
+ self.diffusion_model = model.eval()
91
+ self.diffusion_model.train = disabled_train
92
+ for param in self.diffusion_model.parameters():
93
+ param.requires_grad = False
94
+
95
+ def load_classifier(self, ckpt_path, pool):
96
+ model_config = deepcopy(self.diffusion_config.params.unet_config.params)
97
+ model_config.in_channels = self.diffusion_config.params.unet_config.params.out_channels
98
+ model_config.out_channels = self.num_classes
99
+ if self.label_key == 'class_label':
100
+ model_config.pool = pool
101
+
102
+ self.model = __models__[self.label_key](**model_config)
103
+ if ckpt_path is not None:
104
+ print('#####################################################################')
105
+ print(f'load from ckpt "{ckpt_path}"')
106
+ print('#####################################################################')
107
+ self.init_from_ckpt(ckpt_path)
108
+
109
+ @torch.no_grad()
110
+ def get_x_noisy(self, x, t, noise=None):
111
+ noise = default(noise, lambda: torch.randn_like(x))
112
+ continuous_sqrt_alpha_cumprod = None
113
+ if self.diffusion_model.use_continuous_noise:
114
+ continuous_sqrt_alpha_cumprod = self.diffusion_model.sample_continuous_noise_level(x.shape[0], t + 1)
115
+ # todo: make sure t+1 is correct here
116
+
117
+ return self.diffusion_model.q_sample(x_start=x, t=t, noise=noise,
118
+ continuous_sqrt_alpha_cumprod=continuous_sqrt_alpha_cumprod)
119
+
120
+ def forward(self, x_noisy, t, *args, **kwargs):
121
+ return self.model(x_noisy, t)
122
+
123
+ @torch.no_grad()
124
+ def get_input(self, batch, k):
125
+ x = batch[k]
126
+ if len(x.shape) == 3:
127
+ x = x[..., None]
128
+ x = rearrange(x, 'b h w c -> b c h w')
129
+ x = x.to(memory_format=torch.contiguous_format).float()
130
+ return x
131
+
132
+ @torch.no_grad()
133
+ def get_conditioning(self, batch, k=None):
134
+ if k is None:
135
+ k = self.label_key
136
+ assert k is not None, 'Needs to provide label key'
137
+
138
+ targets = batch[k].to(self.device)
139
+
140
+ if self.label_key == 'segmentation':
141
+ targets = rearrange(targets, 'b h w c -> b c h w')
142
+ for down in range(self.numd):
143
+ h, w = targets.shape[-2:]
144
+ targets = F.interpolate(targets, size=(h // 2, w // 2), mode='nearest')
145
+
146
+ # targets = rearrange(targets,'b c h w -> b h w c')
147
+
148
+ return targets
149
+
150
+ def compute_top_k(self, logits, labels, k, reduction="mean"):
151
+ _, top_ks = torch.topk(logits, k, dim=1)
152
+ if reduction == "mean":
153
+ return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item()
154
+ elif reduction == "none":
155
+ return (top_ks == labels[:, None]).float().sum(dim=-1)
156
+
157
+ def on_train_epoch_start(self):
158
+ # save some memory
159
+ self.diffusion_model.model.to('cpu')
160
+
161
+ @torch.no_grad()
162
+ def write_logs(self, loss, logits, targets):
163
+ log_prefix = 'train' if self.training else 'val'
164
+ log = {}
165
+ log[f"{log_prefix}/loss"] = loss.mean()
166
+ log[f"{log_prefix}/acc@1"] = self.compute_top_k(
167
+ logits, targets, k=1, reduction="mean"
168
+ )
169
+ log[f"{log_prefix}/acc@5"] = self.compute_top_k(
170
+ logits, targets, k=5, reduction="mean"
171
+ )
172
+
173
+ self.log_dict(log, prog_bar=False, logger=True, on_step=self.training, on_epoch=True)
174
+ self.log('loss', log[f"{log_prefix}/loss"], prog_bar=True, logger=False)
175
+ self.log('global_step', self.global_step, logger=False, on_epoch=False, prog_bar=True)
176
+ lr = self.optimizers().param_groups[0]['lr']
177
+ self.log('lr_abs', lr, on_step=True, logger=True, on_epoch=False, prog_bar=True)
178
+
179
+ def shared_step(self, batch, t=None):
180
+ x, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key)
181
+ targets = self.get_conditioning(batch)
182
+ if targets.dim() == 4:
183
+ targets = targets.argmax(dim=1)
184
+ if t is None:
185
+ t = torch.randint(0, self.diffusion_model.num_timesteps, (x.shape[0],), device=self.device).long()
186
+ else:
187
+ t = torch.full(size=(x.shape[0],), fill_value=t, device=self.device).long()
188
+ x_noisy = self.get_x_noisy(x, t)
189
+ logits = self(x_noisy, t)
190
+
191
+ loss = F.cross_entropy(logits, targets, reduction='none')
192
+
193
+ self.write_logs(loss.detach(), logits.detach(), targets.detach())
194
+
195
+ loss = loss.mean()
196
+ return loss, logits, x_noisy, targets
197
+
198
+ def training_step(self, batch, batch_idx):
199
+ loss, *_ = self.shared_step(batch)
200
+ return loss
201
+
202
+ def reset_noise_accs(self):
203
+ self.noisy_acc = {t: {'acc@1': [], 'acc@5': []} for t in
204
+ range(0, self.diffusion_model.num_timesteps, self.diffusion_model.log_every_t)}
205
+
206
+ def on_validation_start(self):
207
+ self.reset_noise_accs()
208
+
209
+ @torch.no_grad()
210
+ def validation_step(self, batch, batch_idx):
211
+ loss, *_ = self.shared_step(batch)
212
+
213
+ for t in self.noisy_acc:
214
+ _, logits, _, targets = self.shared_step(batch, t)
215
+ self.noisy_acc[t]['acc@1'].append(self.compute_top_k(logits, targets, k=1, reduction='mean'))
216
+ self.noisy_acc[t]['acc@5'].append(self.compute_top_k(logits, targets, k=5, reduction='mean'))
217
+
218
+ return loss
219
+
220
+ def configure_optimizers(self):
221
+ optimizer = AdamW(self.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
222
+
223
+ if self.use_scheduler:
224
+ scheduler = instantiate_from_config(self.scheduler_config)
225
+
226
+ print("Setting up LambdaLR scheduler...")
227
+ scheduler = [
228
+ {
229
+ 'scheduler': LambdaLR(optimizer, lr_lambda=scheduler.schedule),
230
+ 'interval': 'step',
231
+ 'frequency': 1
232
+ }]
233
+ return [optimizer], scheduler
234
+
235
+ return optimizer
236
+
237
+ @torch.no_grad()
238
+ def log_images(self, batch, N=8, *args, **kwargs):
239
+ log = dict()
240
+ x = self.get_input(batch, self.diffusion_model.first_stage_key)
241
+ log['inputs'] = x
242
+
243
+ y = self.get_conditioning(batch)
244
+
245
+ if self.label_key == 'class_label':
246
+ y = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
247
+ log['labels'] = y
248
+
249
+ if ismap(y):
250
+ log['labels'] = self.diffusion_model.to_rgb(y)
251
+
252
+ for step in range(self.log_steps):
253
+ current_time = step * self.log_time_interval
254
+
255
+ _, logits, x_noisy, _ = self.shared_step(batch, t=current_time)
256
+
257
+ log[f'inputs@t{current_time}'] = x_noisy
258
+
259
+ pred = F.one_hot(logits.argmax(dim=1), num_classes=self.num_classes)
260
+ pred = rearrange(pred, 'b h w c -> b c h w')
261
+
262
+ log[f'pred@t{current_time}'] = self.diffusion_model.to_rgb(pred)
263
+
264
+ for key in log:
265
+ log[key] = log[key][:N]
266
+
267
+ return log
ldm/models/diffusion/ddim.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.models.diffusion.ddpm import noise_like
9
+ from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps
10
+
11
+
12
+ class DDIMSampler(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
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
27
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
28
+ alphas_cumprod = self.model.alphas_cumprod
29
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
30
+
31
+ to_torch = partial(torch.tensor, dtype=torch.float32, device=self.model.device)
32
+
33
+ self.register_buffer('betas', to_torch(self.model.betas))
34
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
35
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
36
+
37
+ # calculations for diffusion q(x_t | x_{t-1}) and others
38
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
39
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
40
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
41
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
42
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
43
+
44
+ # ddim sampling parameters
45
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
46
+ ddim_timesteps=self.ddim_timesteps,
47
+ eta=ddim_eta,verbose=verbose)
48
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
49
+ self.register_buffer('ddim_alphas', ddim_alphas)
50
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
51
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
52
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
53
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
54
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
55
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
56
+
57
+ @torch.no_grad()
58
+ def sample(self,
59
+ S,
60
+ batch_size,
61
+ shape,
62
+ conditioning=None,
63
+ callback=None,
64
+ normals_sequence=None,
65
+ img_callback=None,
66
+ quantize_x0=False,
67
+ eta=0.,
68
+ mask=None,
69
+ x0=None,
70
+ temperature=1.,
71
+ noise_dropout=0.,
72
+ score_corrector=None,
73
+ corrector_kwargs=None,
74
+ verbose=True,
75
+ x_T=None,
76
+ log_every_t=100
77
+ ):
78
+ if conditioning is not None:
79
+ if isinstance(conditioning, dict):
80
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
81
+ if cbs != batch_size:
82
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
83
+ else:
84
+ if conditioning.shape[0] != batch_size:
85
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
86
+
87
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
88
+ # sampling
89
+ C, H, W = shape
90
+ size = (batch_size, C, H, W)
91
+ print(f'Data shape for DDIM sampling is {size}, eta {eta}')
92
+
93
+ samples, intermediates = self.ddim_sampling(conditioning, size,
94
+ callback=callback,
95
+ img_callback=img_callback,
96
+ quantize_denoised=quantize_x0,
97
+ mask=mask, x0=x0,
98
+ ddim_use_original_steps=False,
99
+ noise_dropout=noise_dropout,
100
+ temperature=temperature,
101
+ score_corrector=score_corrector,
102
+ corrector_kwargs=corrector_kwargs,
103
+ x_T=x_T,
104
+ log_every_t=log_every_t
105
+ )
106
+ return samples, intermediates
107
+
108
+ @torch.no_grad()
109
+ def ddim_sampling(self, cond, shape,
110
+ x_T=None, ddim_use_original_steps=False,
111
+ callback=None, timesteps=None, quantize_denoised=False,
112
+ mask=None, x0=None, img_callback=None, log_every_t=100,
113
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
114
+ device = self.model.betas.device
115
+ b = shape[0]
116
+ if x_T is None:
117
+ img = torch.randn(shape, device=device)
118
+ else:
119
+ img = x_T
120
+
121
+ if timesteps is None:
122
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
123
+ elif timesteps is not None and not ddim_use_original_steps:
124
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
125
+ timesteps = self.ddim_timesteps[:subset_end]
126
+
127
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
128
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
129
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
130
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
131
+
132
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
133
+
134
+ for i, step in enumerate(iterator):
135
+ index = total_steps - i - 1
136
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
137
+
138
+ if mask is not None:
139
+ assert x0 is not None
140
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
141
+ img = img_orig * mask + (1. - mask) * img
142
+
143
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
144
+ quantize_denoised=quantize_denoised, temperature=temperature,
145
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
146
+ corrector_kwargs=corrector_kwargs)
147
+ img, pred_x0 = outs
148
+ if callback: callback(i)
149
+ if img_callback: img_callback(pred_x0, i)
150
+
151
+ if index % log_every_t == 0 or index == total_steps - 1:
152
+ intermediates['x_inter'].append(img)
153
+ intermediates['pred_x0'].append(pred_x0)
154
+
155
+ return img, intermediates
156
+
157
+ @torch.no_grad()
158
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
159
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
160
+ b, *_, device = *x.shape, x.device
161
+ e_t = self.model.apply_model(x, t, c)
162
+ if score_corrector is not None:
163
+ assert self.model.parameterization == "eps"
164
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
165
+
166
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
167
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
168
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
169
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
170
+ # select parameters corresponding to the currently considered timestep
171
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
172
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
173
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
174
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
175
+
176
+ # current prediction for x_0
177
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
178
+ if quantize_denoised:
179
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
180
+ # direction pointing to x_t
181
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
182
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
183
+ if noise_dropout > 0.:
184
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
185
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
186
+ return x_prev, pred_x0
ldm/models/diffusion/ddpm.py ADDED
@@ -0,0 +1,1430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
16
+ from functools import partial
17
+ from tqdm import tqdm
18
+ from torchvision.utils import make_grid
19
+ from PIL import Image
20
+ from pytorch_lightning.utilities.distributed import rank_zero_only
21
+
22
+ from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
23
+ from ldm.modules.ema import LitEma
24
+ from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
25
+ from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
26
+ from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor
27
+
28
+
29
+ __conditioning_keys__ = {'concat': 'c_concat',
30
+ 'crossattn': 'c_crossattn',
31
+ 'adm': 'y'}
32
+
33
+
34
+ def disabled_train(self, mode=True):
35
+ """Overwrite model.train with this function to make sure train/eval mode
36
+ does not change anymore."""
37
+ return self
38
+
39
+
40
+ def noise_like(shape, device, repeat=False):
41
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
42
+ noise = lambda: torch.randn(shape, device=device)
43
+ return repeat_noise() if repeat else noise()
44
+
45
+
46
+ def uniform_on_device(r1, r2, shape, device):
47
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
48
+
49
+
50
+ class DDPM(pl.LightningModule):
51
+ # classic DDPM with Gaussian diffusion, in image space
52
+ def __init__(self,
53
+ unet_config,
54
+ timesteps=1000,
55
+ beta_schedule="linear",
56
+ loss_type="l2",
57
+ ckpt_path=None,
58
+ ignore_keys=[],
59
+ load_only_unet=False,
60
+ monitor="val/loss",
61
+ use_ema=True,
62
+ first_stage_key="image",
63
+ image_size=256,
64
+ channels=3,
65
+ log_every_t=100,
66
+ clip_denoised=True,
67
+ linear_start=1e-4,
68
+ linear_end=2e-2,
69
+ cosine_s=8e-3,
70
+ given_betas=None,
71
+ original_elbo_weight=0.,
72
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
73
+ l_simple_weight=1.,
74
+ conditioning_key=None,
75
+ parameterization="eps", # all assuming fixed variance schedules
76
+ scheduler_config=None,
77
+ use_positional_encodings=False,
78
+ learn_logvar=False,
79
+ logvar_init=0.,
80
+ ):
81
+ super().__init__()
82
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
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
+ if ckpt_path is not None:
110
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
111
+
112
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
113
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
114
+
115
+ self.loss_type = loss_type
116
+
117
+ self.learn_logvar = learn_logvar
118
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
119
+ if self.learn_logvar:
120
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
121
+
122
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
123
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
124
+ if exists(given_betas):
125
+ betas = given_betas
126
+ else:
127
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
128
+ cosine_s=cosine_s)
129
+ alphas = 1. - betas
130
+ alphas_cumprod = np.cumprod(alphas, axis=0)
131
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
132
+
133
+ timesteps, = betas.shape
134
+ self.num_timesteps = int(timesteps)
135
+ self.linear_start = linear_start
136
+ self.linear_end = linear_end
137
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
138
+
139
+ to_torch = partial(torch.tensor, dtype=torch.float32)
140
+
141
+ self.register_buffer('betas', to_torch(betas))
142
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
143
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
144
+
145
+ # calculations for diffusion q(x_t | x_{t-1}) and others
146
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
147
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
148
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
149
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
150
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
151
+
152
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
153
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
154
+ 1. - alphas_cumprod) + self.v_posterior * betas
155
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
156
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
157
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
158
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
159
+ self.register_buffer('posterior_mean_coef1', to_torch(
160
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
161
+ self.register_buffer('posterior_mean_coef2', to_torch(
162
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
163
+
164
+ if self.parameterization == "eps":
165
+ lvlb_weights = self.betas ** 2 / (
166
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
167
+ elif self.parameterization == "x0":
168
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
169
+ else:
170
+ raise NotImplementedError("mu not supported")
171
+ # TODO how to choose this term
172
+ lvlb_weights[0] = lvlb_weights[1]
173
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
174
+ assert not torch.isnan(self.lvlb_weights).all()
175
+
176
+ @contextmanager
177
+ def ema_scope(self, context=None):
178
+ if self.use_ema:
179
+ self.model_ema.store(self.model.parameters())
180
+ self.model_ema.copy_to(self.model)
181
+ if context is not None:
182
+ print(f"{context}: Switched to EMA weights")
183
+ try:
184
+ yield None
185
+ finally:
186
+ if self.use_ema:
187
+ self.model_ema.restore(self.model.parameters())
188
+ if context is not None:
189
+ print(f"{context}: Restored training weights")
190
+
191
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
192
+ sd = torch.load(path, map_location="cpu")
193
+ if "state_dict" in list(sd.keys()):
194
+ sd = sd["state_dict"]
195
+ keys = list(sd.keys())
196
+ for k in keys:
197
+ for ik in ignore_keys:
198
+ if k.startswith(ik):
199
+ print("Deleting key {} from state_dict.".format(k))
200
+ del sd[k]
201
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
202
+ sd, strict=False)
203
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
204
+ if len(missing) > 0:
205
+ print(f"Missing Keys: {missing}")
206
+ if len(unexpected) > 0:
207
+ print(f"Unexpected Keys: {unexpected}")
208
+
209
+ def q_mean_variance(self, x_start, t):
210
+ """
211
+ Get the distribution q(x_t | x_0).
212
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
213
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
214
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
215
+ """
216
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
217
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
218
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
219
+ return mean, variance, log_variance
220
+
221
+ def predict_start_from_noise(self, x_t, t, noise):
222
+ return (
223
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
224
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
225
+ )
226
+
227
+ def q_posterior(self, x_start, x_t, t):
228
+ posterior_mean = (
229
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
230
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
231
+ )
232
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
233
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
234
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
235
+
236
+ def p_mean_variance(self, x, t, clip_denoised: bool):
237
+ model_out = self.model(x, t)
238
+ if self.parameterization == "eps":
239
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
240
+ elif self.parameterization == "x0":
241
+ x_recon = model_out
242
+ if clip_denoised:
243
+ x_recon.clamp_(-1., 1.)
244
+
245
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
246
+ return model_mean, posterior_variance, posterior_log_variance
247
+
248
+ @torch.no_grad()
249
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
250
+ b, *_, device = *x.shape, x.device
251
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
252
+ noise = noise_like(x.shape, device, repeat_noise)
253
+ # no noise when t == 0
254
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
255
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
256
+
257
+ @torch.no_grad()
258
+ def p_sample_loop(self, shape, return_intermediates=False):
259
+ device = self.betas.device
260
+ b = shape[0]
261
+ img = torch.randn(shape, device=device)
262
+ intermediates = [img]
263
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
264
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
265
+ clip_denoised=self.clip_denoised)
266
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
267
+ intermediates.append(img)
268
+ if return_intermediates:
269
+ return img, intermediates
270
+ return img
271
+
272
+ @torch.no_grad()
273
+ def sample(self, batch_size=16, return_intermediates=False):
274
+ image_size = self.image_size
275
+ channels = self.channels
276
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
277
+ return_intermediates=return_intermediates)
278
+
279
+ def q_sample(self, x_start, t, noise=None):
280
+ noise = default(noise, lambda: torch.randn_like(x_start))
281
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
282
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
283
+
284
+ def get_loss(self, pred, target, mean=True):
285
+ if self.loss_type == 'l1':
286
+ loss = (target - pred).abs()
287
+ if mean:
288
+ loss = loss.mean()
289
+ elif self.loss_type == 'l2':
290
+ if mean:
291
+ loss = torch.nn.functional.mse_loss(target, pred)
292
+ else:
293
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
294
+ else:
295
+ raise NotImplementedError("unknown loss type '{loss_type}'")
296
+
297
+ return loss
298
+
299
+ def p_losses(self, x_start, t, noise=None):
300
+ noise = default(noise, lambda: torch.randn_like(x_start))
301
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
302
+ model_out = self.model(x_noisy, t)
303
+
304
+ loss_dict = {}
305
+ if self.parameterization == "eps":
306
+ target = noise
307
+ elif self.parameterization == "x0":
308
+ target = x_start
309
+ else:
310
+ raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
311
+
312
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
313
+
314
+ log_prefix = 'train' if self.training else 'val'
315
+
316
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
317
+ loss_simple = loss.mean() * self.l_simple_weight
318
+
319
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
320
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
321
+
322
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
323
+
324
+ loss_dict.update({f'{log_prefix}/loss': loss})
325
+
326
+ return loss, loss_dict
327
+
328
+ def forward(self, x, *args, **kwargs):
329
+ # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
330
+ # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
331
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
332
+ return self.p_losses(x, t, *args, **kwargs)
333
+
334
+ def get_input(self, batch, k):
335
+ x = batch[k]
336
+ if len(x.shape) == 3:
337
+ x = x[..., None]
338
+ x = rearrange(x, 'b h w c -> b c h w')
339
+ x = x.to(memory_format=torch.contiguous_format).float()
340
+ return x
341
+
342
+ def shared_step(self, batch):
343
+ x = self.get_input(batch, self.first_stage_key)
344
+ loss, loss_dict = self(x)
345
+ return loss, loss_dict
346
+
347
+ def training_step(self, batch, batch_idx):
348
+ loss, loss_dict = self.shared_step(batch)
349
+
350
+ self.log_dict(loss_dict, prog_bar=True,
351
+ logger=True, on_step=True, on_epoch=True)
352
+
353
+ self.log("global_step", self.global_step,
354
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
355
+
356
+ if self.use_scheduler:
357
+ lr = self.optimizers().param_groups[0]['lr']
358
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
359
+
360
+ return loss
361
+
362
+ @torch.no_grad()
363
+ def validation_step(self, batch, batch_idx):
364
+ _, loss_dict_no_ema = self.shared_step(batch)
365
+ with self.ema_scope():
366
+ _, loss_dict_ema = self.shared_step(batch)
367
+ loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
368
+ self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
369
+ self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
370
+
371
+ def on_train_batch_end(self, *args, **kwargs):
372
+ if self.use_ema:
373
+ self.model_ema(self.model)
374
+
375
+ def _get_rows_from_list(self, samples):
376
+ n_imgs_per_row = len(samples)
377
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
378
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
379
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
380
+ return denoise_grid
381
+
382
+ @torch.no_grad()
383
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
384
+ log = dict()
385
+ x = self.get_input(batch, self.first_stage_key)
386
+ N = min(x.shape[0], N)
387
+ n_row = min(x.shape[0], n_row)
388
+ x = x.to(self.device)[:N]
389
+ log["inputs"] = x
390
+
391
+ # get diffusion row
392
+ diffusion_row = list()
393
+ x_start = x[:n_row]
394
+
395
+ for t in range(self.num_timesteps):
396
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
397
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
398
+ t = t.to(self.device).long()
399
+ noise = torch.randn_like(x_start)
400
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
401
+ diffusion_row.append(x_noisy)
402
+
403
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
404
+
405
+ if sample:
406
+ # get denoise row
407
+ with self.ema_scope("Plotting"):
408
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
409
+
410
+ log["samples"] = samples
411
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
412
+
413
+ if return_keys:
414
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
415
+ return log
416
+ else:
417
+ return {key: log[key] for key in return_keys}
418
+ return log
419
+
420
+ def configure_optimizers(self):
421
+ lr = self.learning_rate
422
+ params = list(self.model.parameters())
423
+ if self.learn_logvar:
424
+ params = params + [self.logvar]
425
+ opt = torch.optim.AdamW(params, lr=lr)
426
+ return opt
427
+
428
+
429
+ class LatentDiffusion(DDPM):
430
+ """main class"""
431
+ def __init__(self,
432
+ first_stage_config,
433
+ cond_stage_config,
434
+ num_timesteps_cond=None,
435
+ cond_stage_key="image",
436
+ cond_stage_trainable=False,
437
+ concat_mode=True,
438
+ cond_stage_forward=None,
439
+ conditioning_key=None,
440
+ scale_factor=1.0,
441
+ scale_by_std=False,
442
+ *args, **kwargs):
443
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
444
+ self.scale_by_std = scale_by_std
445
+ assert self.num_timesteps_cond <= kwargs['timesteps']
446
+ # for backwards compatibility after implementation of DiffusionWrapper
447
+ if conditioning_key is None:
448
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
449
+ if cond_stage_config == '__is_unconditional__':
450
+ conditioning_key = None
451
+ ckpt_path = kwargs.pop("ckpt_path", None)
452
+ ignore_keys = kwargs.pop("ignore_keys", [])
453
+ super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
454
+ self.concat_mode = concat_mode
455
+ self.cond_stage_trainable = cond_stage_trainable
456
+ self.cond_stage_key = cond_stage_key
457
+ try:
458
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
459
+ except:
460
+ self.num_downs = 0
461
+ if not scale_by_std:
462
+ self.scale_factor = scale_factor
463
+ else:
464
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
465
+ self.instantiate_first_stage(first_stage_config)
466
+ self.instantiate_cond_stage(cond_stage_config)
467
+ self.cond_stage_forward = cond_stage_forward
468
+ self.clip_denoised = False
469
+ self.bbox_tokenizer = None # # TODO: special class?
470
+
471
+ self.restarted_from_ckpt = False
472
+ if ckpt_path is not None:
473
+ self.init_from_ckpt(ckpt_path, ignore_keys)
474
+ self.restarted_from_ckpt = True
475
+
476
+ def make_cond_schedule(self, ):
477
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
478
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
479
+ self.cond_ids[:self.num_timesteps_cond] = ids
480
+
481
+ @rank_zero_only
482
+ @torch.no_grad()
483
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
484
+ # only for very first batch
485
+ 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:
486
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
487
+ # set rescale weight to 1./std of encodings
488
+ print("### USING STD-RESCALING ###")
489
+ x = super().get_input(batch, self.first_stage_key)
490
+ x = x.to(self.device)
491
+ encoder_posterior = self.encode_first_stage(x)
492
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
493
+ del self.scale_factor
494
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
495
+ print(f"setting self.scale_factor to {self.scale_factor}")
496
+ print("### USING STD-RESCALING ###")
497
+
498
+ def register_schedule(self,
499
+ given_betas=None, beta_schedule="linear", timesteps=1000,
500
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
501
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
502
+
503
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
504
+ if self.shorten_cond_schedule:
505
+ self.make_cond_schedule()
506
+
507
+ def instantiate_first_stage(self, config):
508
+ model = instantiate_from_config(config)
509
+ self.first_stage_model = model.eval()
510
+ self.first_stage_model.train = disabled_train
511
+ for param in self.first_stage_model.parameters():
512
+ param.requires_grad = False
513
+
514
+ def instantiate_cond_stage(self, config):
515
+ if not self.cond_stage_trainable:
516
+ if config == "__is_first_stage__":
517
+ print("Using first stage also as cond stage.")
518
+ self.cond_stage_model = self.first_stage_model
519
+ elif config == "__is_unconditional__":
520
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
521
+ self.cond_stage_model = None
522
+ # self.be_unconditional = True
523
+ else:
524
+ model = instantiate_from_config(config)
525
+ self.cond_stage_model = model.eval()
526
+ self.cond_stage_model.train = disabled_train
527
+ for param in self.cond_stage_model.parameters():
528
+ param.requires_grad = False
529
+ else:
530
+ assert config != '__is_first_stage__'
531
+ assert config != '__is_unconditional__'
532
+ model = instantiate_from_config(config)
533
+ self.cond_stage_model = model
534
+
535
+ def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
536
+ denoise_row = []
537
+ for zd in tqdm(samples, desc=desc):
538
+ denoise_row.append(self.decode_first_stage(zd.to(self.device),
539
+ force_not_quantize=force_no_decoder_quantization))
540
+ n_imgs_per_row = len(denoise_row)
541
+ denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
542
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
543
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
544
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
545
+ return denoise_grid
546
+
547
+ def get_first_stage_encoding(self, encoder_posterior):
548
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
549
+ z = encoder_posterior.sample()
550
+ elif isinstance(encoder_posterior, torch.Tensor):
551
+ z = encoder_posterior
552
+ else:
553
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
554
+ return self.scale_factor * z
555
+
556
+ def get_learned_conditioning(self, c):
557
+ if self.cond_stage_forward is None:
558
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
559
+ c = self.cond_stage_model.encode(c)
560
+ if isinstance(c, DiagonalGaussianDistribution):
561
+ c = c.mode()
562
+ else:
563
+ c = self.cond_stage_model(c)
564
+ else:
565
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
566
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
567
+ return c
568
+
569
+ def meshgrid(self, h, w):
570
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
571
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
572
+
573
+ arr = torch.cat([y, x], dim=-1)
574
+ return arr
575
+
576
+ def delta_border(self, h, w):
577
+ """
578
+ :param h: height
579
+ :param w: width
580
+ :return: normalized distance to image border,
581
+ wtith min distance = 0 at border and max dist = 0.5 at image center
582
+ """
583
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
584
+ arr = self.meshgrid(h, w) / lower_right_corner
585
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
586
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
587
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
588
+ return edge_dist
589
+
590
+ def get_weighting(self, h, w, Ly, Lx, device):
591
+ weighting = self.delta_border(h, w)
592
+ weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
593
+ self.split_input_params["clip_max_weight"], )
594
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
595
+
596
+ if self.split_input_params["tie_braker"]:
597
+ L_weighting = self.delta_border(Ly, Lx)
598
+ L_weighting = torch.clip(L_weighting,
599
+ self.split_input_params["clip_min_tie_weight"],
600
+ self.split_input_params["clip_max_tie_weight"])
601
+
602
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
603
+ weighting = weighting * L_weighting
604
+ return weighting
605
+
606
+ def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code !
607
+ """
608
+ :param x: img of size (bs, c, h, w)
609
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
610
+ """
611
+ bs, nc, h, w = x.shape
612
+
613
+ # number of crops in image
614
+ Ly = (h - kernel_size[0]) // stride[0] + 1
615
+ Lx = (w - kernel_size[1]) // stride[1] + 1
616
+
617
+ if uf == 1 and df == 1:
618
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
619
+ unfold = torch.nn.Unfold(**fold_params)
620
+
621
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
622
+
623
+ weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
624
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
625
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
626
+
627
+ elif uf > 1 and df == 1:
628
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
629
+ unfold = torch.nn.Unfold(**fold_params)
630
+
631
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
632
+ dilation=1, padding=0,
633
+ stride=(stride[0] * uf, stride[1] * uf))
634
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
635
+
636
+ weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
637
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
638
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
639
+
640
+ elif df > 1 and uf == 1:
641
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
642
+ unfold = torch.nn.Unfold(**fold_params)
643
+
644
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
645
+ dilation=1, padding=0,
646
+ stride=(stride[0] // df, stride[1] // df))
647
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
648
+
649
+ weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
650
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
651
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
652
+
653
+ else:
654
+ raise NotImplementedError
655
+
656
+ return fold, unfold, normalization, weighting
657
+
658
+ @torch.no_grad()
659
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
660
+ cond_key=None, return_original_cond=False, bs=None):
661
+ x = super().get_input(batch, k)
662
+ if bs is not None:
663
+ x = x[:bs]
664
+ x = x.to(self.device)
665
+ encoder_posterior = self.encode_first_stage(x)
666
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
667
+
668
+ if self.model.conditioning_key is not None:
669
+ if cond_key is None:
670
+ cond_key = self.cond_stage_key
671
+ if cond_key != self.first_stage_key:
672
+ if cond_key in ['caption', 'coordinates_bbox']:
673
+ xc = batch[cond_key]
674
+ elif cond_key == 'class_label':
675
+ xc = batch
676
+ else:
677
+ xc = super().get_input(batch, cond_key).to(self.device)
678
+ else:
679
+ xc = x
680
+ if not self.cond_stage_trainable or force_c_encode:
681
+ if isinstance(xc, dict) or isinstance(xc, list):
682
+ # import pudb; pudb.set_trace()
683
+ c = self.get_learned_conditioning(xc)
684
+ else:
685
+ c = self.get_learned_conditioning(xc.to(self.device))
686
+ else:
687
+ c = xc
688
+ if bs is not None:
689
+ c = c[:bs]
690
+
691
+ if self.use_positional_encodings:
692
+ pos_x, pos_y = self.compute_latent_shifts(batch)
693
+ ckey = __conditioning_keys__[self.model.conditioning_key]
694
+ c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
695
+
696
+ else:
697
+ c = None
698
+ xc = None
699
+ if self.use_positional_encodings:
700
+ pos_x, pos_y = self.compute_latent_shifts(batch)
701
+ c = {'pos_x': pos_x, 'pos_y': pos_y}
702
+ out = [z, c]
703
+ if return_first_stage_outputs:
704
+ xrec = self.decode_first_stage(z)
705
+ out.extend([x, xrec])
706
+ if return_original_cond:
707
+ out.append(xc)
708
+ return out
709
+
710
+ @torch.no_grad()
711
+ def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
712
+ if predict_cids:
713
+ if z.dim() == 4:
714
+ z = torch.argmax(z.exp(), dim=1).long()
715
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
716
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
717
+
718
+ z = 1. / self.scale_factor * z
719
+
720
+ if hasattr(self, "split_input_params"):
721
+ if self.split_input_params["patch_distributed_vq"]:
722
+ ks = self.split_input_params["ks"] # eg. (128, 128)
723
+ stride = self.split_input_params["stride"] # eg. (64, 64)
724
+ uf = self.split_input_params["vqf"]
725
+ bs, nc, h, w = z.shape
726
+ if ks[0] > h or ks[1] > w:
727
+ ks = (min(ks[0], h), min(ks[1], w))
728
+ print("reducing Kernel")
729
+
730
+ if stride[0] > h or stride[1] > w:
731
+ stride = (min(stride[0], h), min(stride[1], w))
732
+ print("reducing stride")
733
+
734
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
735
+
736
+ z = unfold(z) # (bn, nc * prod(**ks), L)
737
+ # 1. Reshape to img shape
738
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
739
+
740
+ # 2. apply model loop over last dim
741
+ if isinstance(self.first_stage_model, VQModelInterface):
742
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
743
+ force_not_quantize=predict_cids or force_not_quantize)
744
+ for i in range(z.shape[-1])]
745
+ else:
746
+
747
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
748
+ for i in range(z.shape[-1])]
749
+
750
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
751
+ o = o * weighting
752
+ # Reverse 1. reshape to img shape
753
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
754
+ # stitch crops together
755
+ decoded = fold(o)
756
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
757
+ return decoded
758
+ else:
759
+ if isinstance(self.first_stage_model, VQModelInterface):
760
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
761
+ else:
762
+ return self.first_stage_model.decode(z)
763
+
764
+ else:
765
+ if isinstance(self.first_stage_model, VQModelInterface):
766
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
767
+ else:
768
+ return self.first_stage_model.decode(z)
769
+
770
+ # same as above but without decorator
771
+ def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
772
+ if predict_cids:
773
+ if z.dim() == 4:
774
+ z = torch.argmax(z.exp(), dim=1).long()
775
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
776
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
777
+
778
+ z = 1. / self.scale_factor * z
779
+
780
+ if hasattr(self, "split_input_params"):
781
+ if self.split_input_params["patch_distributed_vq"]:
782
+ ks = self.split_input_params["ks"] # eg. (128, 128)
783
+ stride = self.split_input_params["stride"] # eg. (64, 64)
784
+ uf = self.split_input_params["vqf"]
785
+ bs, nc, h, w = z.shape
786
+ if ks[0] > h or ks[1] > w:
787
+ ks = (min(ks[0], h), min(ks[1], w))
788
+ print("reducing Kernel")
789
+
790
+ if stride[0] > h or stride[1] > w:
791
+ stride = (min(stride[0], h), min(stride[1], w))
792
+ print("reducing stride")
793
+
794
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
795
+
796
+ z = unfold(z) # (bn, nc * prod(**ks), L)
797
+ # 1. Reshape to img shape
798
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
799
+
800
+ # 2. apply model loop over last dim
801
+ if isinstance(self.first_stage_model, VQModelInterface): # todo ask what this is
802
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
803
+ force_not_quantize=predict_cids or force_not_quantize)
804
+ for i in range(z.shape[-1])]
805
+ else:
806
+
807
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
808
+ for i in range(z.shape[-1])]
809
+
810
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
811
+ o = o * weighting
812
+ # Reverse 1. reshape to img shape
813
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
814
+ # stitch crops together
815
+ decoded = fold(o)
816
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
817
+ return decoded
818
+ else:
819
+ if isinstance(self.first_stage_model, VQModelInterface):
820
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
821
+ else:
822
+ return self.first_stage_model.decode(z)
823
+
824
+ else:
825
+ if isinstance(self.first_stage_model, VQModelInterface):
826
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
827
+ else:
828
+ return self.first_stage_model.decode(z)
829
+
830
+ @torch.no_grad()
831
+ def encode_first_stage(self, x):
832
+ if hasattr(self, "split_input_params"):
833
+ if self.split_input_params["patch_distributed_vq"]:
834
+ ks = self.split_input_params["ks"] # eg. (128, 128)
835
+ stride = self.split_input_params["stride"] # eg. (64, 64)
836
+ df = self.split_input_params["vqf"]
837
+ self.split_input_params['original_image_size'] = x.shape[-2:]
838
+ bs, nc, h, w = x.shape
839
+ if ks[0] > h or ks[1] > w:
840
+ ks = (min(ks[0], h), min(ks[1], w))
841
+ print("reducing Kernel")
842
+
843
+ if stride[0] > h or stride[1] > w:
844
+ stride = (min(stride[0], h), min(stride[1], w))
845
+ print("reducing stride")
846
+
847
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
848
+ z = unfold(x) # (bn, nc * prod(**ks), L)
849
+ # Reshape to img shape
850
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
851
+
852
+ output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
853
+ for i in range(z.shape[-1])]
854
+
855
+ o = torch.stack(output_list, axis=-1)
856
+ o = o * weighting
857
+
858
+ # Reverse reshape to img shape
859
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
860
+ # stitch crops together
861
+ decoded = fold(o)
862
+ decoded = decoded / normalization
863
+ return decoded
864
+
865
+ else:
866
+ return self.first_stage_model.encode(x)
867
+ else:
868
+ return self.first_stage_model.encode(x)
869
+
870
+ def shared_step(self, batch, **kwargs):
871
+ x, c = self.get_input(batch, self.first_stage_key)
872
+ loss = self(x, c)
873
+ return loss
874
+
875
+ def forward(self, x, c, *args, **kwargs):
876
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
877
+ if self.model.conditioning_key is not None:
878
+ assert c is not None
879
+ if self.cond_stage_trainable:
880
+ c = self.get_learned_conditioning(c)
881
+ if self.shorten_cond_schedule: # TODO: drop this option
882
+ tc = self.cond_ids[t].to(self.device)
883
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
884
+ return self.p_losses(x, c, t, *args, **kwargs)
885
+
886
+ def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
887
+ def rescale_bbox(bbox):
888
+ x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
889
+ y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
890
+ w = min(bbox[2] / crop_coordinates[2], 1 - x0)
891
+ h = min(bbox[3] / crop_coordinates[3], 1 - y0)
892
+ return x0, y0, w, h
893
+
894
+ return [rescale_bbox(b) for b in bboxes]
895
+
896
+ def apply_model(self, x_noisy, t, cond, return_ids=False):
897
+
898
+ if isinstance(cond, dict):
899
+ # hybrid case, cond is exptected to be a dict
900
+ pass
901
+ else:
902
+ if not isinstance(cond, list):
903
+ cond = [cond]
904
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
905
+ cond = {key: cond}
906
+
907
+ if hasattr(self, "split_input_params"):
908
+ assert len(cond) == 1 # todo can only deal with one conditioning atm
909
+ assert not return_ids # todo dont know what this is -> I exclude --> Good
910
+ ks = self.split_input_params["ks"] # eg. (128, 128)
911
+ stride = self.split_input_params["stride"] # eg. (64, 64)
912
+
913
+ h, w = x_noisy.shape[-2:]
914
+
915
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
916
+
917
+ z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
918
+ # Reshape to img shape
919
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
920
+ z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
921
+
922
+ if self.cond_stage_key in ["image", "LR_image", "segmentation",
923
+ 'bbox_img'] and self.model.conditioning_key: # todo check for completeness
924
+ c_key = next(iter(cond.keys())) # get key
925
+ c = next(iter(cond.values())) # get value
926
+ assert (len(c) == 1) # todo extend to list with more than one elem
927
+ c = c[0] # get element
928
+
929
+ c = unfold(c)
930
+ c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
931
+
932
+ cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
933
+
934
+ elif self.cond_stage_key == 'coordinates_bbox':
935
+ assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
936
+
937
+ # assuming padding of unfold is always 0 and its dilation is always 1
938
+ n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
939
+ full_img_h, full_img_w = self.split_input_params['original_image_size']
940
+ # as we are operating on latents, we need the factor from the original image size to the
941
+ # spatial latent size to properly rescale the crops for regenerating the bbox annotations
942
+ num_downs = self.first_stage_model.encoder.num_resolutions - 1
943
+ rescale_latent = 2 ** (num_downs)
944
+
945
+ # get top left postions of patches as conforming for the bbbox tokenizer, therefore we
946
+ # need to rescale the tl patch coordinates to be in between (0,1)
947
+ tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
948
+ rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
949
+ for patch_nr in range(z.shape[-1])]
950
+
951
+ # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
952
+ patch_limits = [(x_tl, y_tl,
953
+ rescale_latent * ks[0] / full_img_w,
954
+ rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
955
+ # patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
956
+
957
+ # tokenize crop coordinates for the bounding boxes of the respective patches
958
+ patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
959
+ for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
960
+ print(patch_limits_tknzd[0].shape)
961
+ # cut tknzd crop position from conditioning
962
+ assert isinstance(cond, dict), 'cond must be dict to be fed into model'
963
+ cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
964
+ print(cut_cond.shape)
965
+
966
+ adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
967
+ adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
968
+ print(adapted_cond.shape)
969
+ adapted_cond = self.get_learned_conditioning(adapted_cond)
970
+ print(adapted_cond.shape)
971
+ adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
972
+ print(adapted_cond.shape)
973
+
974
+ cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
975
+
976
+ else:
977
+ cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
978
+
979
+ # apply model by loop over crops
980
+ output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
981
+ assert not isinstance(output_list[0],
982
+ tuple) # todo cant deal with multiple model outputs check this never happens
983
+
984
+ o = torch.stack(output_list, axis=-1)
985
+ o = o * weighting
986
+ # Reverse reshape to img shape
987
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
988
+ # stitch crops together
989
+ x_recon = fold(o) / normalization
990
+
991
+ else:
992
+ x_recon = self.model(x_noisy, t, **cond)
993
+
994
+ if isinstance(x_recon, tuple) and not return_ids:
995
+ return x_recon[0]
996
+ else:
997
+ return x_recon
998
+
999
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
1000
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
1001
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
1002
+
1003
+ def _prior_bpd(self, x_start):
1004
+ """
1005
+ Get the prior KL term for the variational lower-bound, measured in
1006
+ bits-per-dim.
1007
+ This term can't be optimized, as it only depends on the encoder.
1008
+ :param x_start: the [N x C x ...] tensor of inputs.
1009
+ :return: a batch of [N] KL values (in bits), one per batch element.
1010
+ """
1011
+ batch_size = x_start.shape[0]
1012
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1013
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1014
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
1015
+ return mean_flat(kl_prior) / np.log(2.0)
1016
+
1017
+ def p_losses(self, x_start, cond, t, noise=None):
1018
+ noise = default(noise, lambda: torch.randn_like(x_start))
1019
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1020
+ model_output = self.apply_model(x_noisy, t, cond)
1021
+
1022
+ loss_dict = {}
1023
+ prefix = 'train' if self.training else 'val'
1024
+
1025
+ if self.parameterization == "x0":
1026
+ target = x_start
1027
+ elif self.parameterization == "eps":
1028
+ target = noise
1029
+ else:
1030
+ raise NotImplementedError()
1031
+
1032
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
1033
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
1034
+
1035
+ logvar_t = self.logvar[t].to(self.device)
1036
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
1037
+ # loss = loss_simple / torch.exp(self.logvar) + self.logvar
1038
+ if self.learn_logvar:
1039
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
1040
+ loss_dict.update({'logvar': self.logvar.data.mean()})
1041
+
1042
+ loss = self.l_simple_weight * loss.mean()
1043
+
1044
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
1045
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
1046
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
1047
+ loss += (self.original_elbo_weight * loss_vlb)
1048
+ loss_dict.update({f'{prefix}/loss': loss})
1049
+
1050
+ return loss, loss_dict
1051
+
1052
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
1053
+ return_x0=False, score_corrector=None, corrector_kwargs=None):
1054
+ t_in = t
1055
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
1056
+
1057
+ if score_corrector is not None:
1058
+ assert self.parameterization == "eps"
1059
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
1060
+
1061
+ if return_codebook_ids:
1062
+ model_out, logits = model_out
1063
+
1064
+ if self.parameterization == "eps":
1065
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
1066
+ elif self.parameterization == "x0":
1067
+ x_recon = model_out
1068
+ else:
1069
+ raise NotImplementedError()
1070
+
1071
+ if clip_denoised:
1072
+ x_recon.clamp_(-1., 1.)
1073
+ if quantize_denoised:
1074
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
1075
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
1076
+ if return_codebook_ids:
1077
+ return model_mean, posterior_variance, posterior_log_variance, logits
1078
+ elif return_x0:
1079
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
1080
+ else:
1081
+ return model_mean, posterior_variance, posterior_log_variance
1082
+
1083
+ @torch.no_grad()
1084
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
1085
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
1086
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
1087
+ b, *_, device = *x.shape, x.device
1088
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
1089
+ return_codebook_ids=return_codebook_ids,
1090
+ quantize_denoised=quantize_denoised,
1091
+ return_x0=return_x0,
1092
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1093
+ if return_codebook_ids:
1094
+ raise DeprecationWarning("Support dropped.")
1095
+ model_mean, _, model_log_variance, logits = outputs
1096
+ elif return_x0:
1097
+ model_mean, _, model_log_variance, x0 = outputs
1098
+ else:
1099
+ model_mean, _, model_log_variance = outputs
1100
+
1101
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
1102
+ if noise_dropout > 0.:
1103
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1104
+ # no noise when t == 0
1105
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1106
+
1107
+ if return_codebook_ids:
1108
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1109
+ if return_x0:
1110
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1111
+ else:
1112
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1113
+
1114
+ @torch.no_grad()
1115
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1116
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1117
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1118
+ log_every_t=None):
1119
+ if not log_every_t:
1120
+ log_every_t = self.log_every_t
1121
+ timesteps = self.num_timesteps
1122
+ if batch_size is not None:
1123
+ b = batch_size if batch_size is not None else shape[0]
1124
+ shape = [batch_size] + list(shape)
1125
+ else:
1126
+ b = batch_size = shape[0]
1127
+ if x_T is None:
1128
+ img = torch.randn(shape, device=self.device)
1129
+ else:
1130
+ img = x_T
1131
+ intermediates = []
1132
+ if cond is not None:
1133
+ if isinstance(cond, dict):
1134
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1135
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1136
+ else:
1137
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1138
+
1139
+ if start_T is not None:
1140
+ timesteps = min(timesteps, start_T)
1141
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1142
+ total=timesteps) if verbose else reversed(
1143
+ range(0, timesteps))
1144
+ if type(temperature) == float:
1145
+ temperature = [temperature] * timesteps
1146
+
1147
+ for i in iterator:
1148
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1149
+ if self.shorten_cond_schedule:
1150
+ assert self.model.conditioning_key != 'hybrid'
1151
+ tc = self.cond_ids[ts].to(cond.device)
1152
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1153
+
1154
+ img, x0_partial = self.p_sample(img, cond, ts,
1155
+ clip_denoised=self.clip_denoised,
1156
+ quantize_denoised=quantize_denoised, return_x0=True,
1157
+ temperature=temperature[i], noise_dropout=noise_dropout,
1158
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1159
+ if mask is not None:
1160
+ assert x0 is not None
1161
+ img_orig = self.q_sample(x0, ts)
1162
+ img = img_orig * mask + (1. - mask) * img
1163
+
1164
+ if i % log_every_t == 0 or i == timesteps - 1:
1165
+ intermediates.append(x0_partial)
1166
+ if callback: callback(i)
1167
+ if img_callback: img_callback(img, i)
1168
+ return img, intermediates
1169
+
1170
+ @torch.no_grad()
1171
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1172
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1173
+ mask=None, x0=None, img_callback=None, start_T=None,
1174
+ log_every_t=None):
1175
+
1176
+ if not log_every_t:
1177
+ log_every_t = self.log_every_t
1178
+ device = self.betas.device
1179
+ b = shape[0]
1180
+ if x_T is None:
1181
+ img = torch.randn(shape, device=device)
1182
+ else:
1183
+ img = x_T
1184
+
1185
+ intermediates = [img]
1186
+ if timesteps is None:
1187
+ timesteps = self.num_timesteps
1188
+
1189
+ if start_T is not None:
1190
+ timesteps = min(timesteps, start_T)
1191
+ print(timesteps, start_T)
1192
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1193
+ range(0, timesteps))
1194
+
1195
+ if mask is not None:
1196
+ assert x0 is not None
1197
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1198
+
1199
+ for i in iterator:
1200
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1201
+ if self.shorten_cond_schedule:
1202
+ assert self.model.conditioning_key != 'hybrid'
1203
+ tc = self.cond_ids[ts].to(cond.device)
1204
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1205
+
1206
+ img = self.p_sample(img, cond, ts,
1207
+ clip_denoised=self.clip_denoised,
1208
+ quantize_denoised=quantize_denoised)
1209
+ if mask is not None:
1210
+ img_orig = self.q_sample(x0, ts)
1211
+ img = img_orig * mask + (1. - mask) * img
1212
+
1213
+ if i % log_every_t == 0 or i == timesteps - 1:
1214
+ intermediates.append(img)
1215
+ if callback: callback(i)
1216
+ if img_callback: img_callback(img, i)
1217
+
1218
+ if return_intermediates:
1219
+ return img, intermediates
1220
+ return img
1221
+
1222
+ @torch.no_grad()
1223
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1224
+ verbose=True, timesteps=None, quantize_denoised=False,
1225
+ mask=None, x0=None, shape=None):
1226
+ if shape is None:
1227
+ shape = (batch_size, self.channels, self.image_size, self.image_size)
1228
+ if cond is not None:
1229
+ if isinstance(cond, dict):
1230
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1231
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1232
+ else:
1233
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1234
+ return self.p_sample_loop(cond,
1235
+ shape,
1236
+ return_intermediates=return_intermediates, x_T=x_T,
1237
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1238
+ mask=mask, x0=x0)
1239
+
1240
+ @torch.no_grad()
1241
+ def log_images(self, batch, N=8, n_row=4, sample=True, sample_ddim=False, return_keys=None,
1242
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1243
+ plot_diffusion_rows=True, **kwargs):
1244
+ # TODO: maybe add option for ddim sampling via DDIMSampler class
1245
+ log = dict()
1246
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1247
+ return_first_stage_outputs=True,
1248
+ force_c_encode=True,
1249
+ return_original_cond=True,
1250
+ bs=N)
1251
+ N = min(x.shape[0], N)
1252
+ n_row = min(x.shape[0], n_row)
1253
+ log["inputs"] = x
1254
+ log["reconstruction"] = xrec
1255
+ if self.model.conditioning_key is not None:
1256
+ if hasattr(self.cond_stage_model, "decode"):
1257
+ xc = self.cond_stage_model.decode(c)
1258
+ log["conditioning"] = xc
1259
+ elif self.cond_stage_key in ["caption"]:
1260
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
1261
+ log["conditioning"] = xc
1262
+ elif self.cond_stage_key == 'class_label':
1263
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
1264
+ log['conditioning'] = xc
1265
+ elif isimage(xc):
1266
+ log["conditioning"] = xc
1267
+ if ismap(xc):
1268
+ log["original_conditioning"] = self.to_rgb(xc)
1269
+
1270
+ if plot_diffusion_rows:
1271
+ # get diffusion row
1272
+ diffusion_row = list()
1273
+ z_start = z[:n_row]
1274
+ for t in range(self.num_timesteps):
1275
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1276
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1277
+ t = t.to(self.device).long()
1278
+ noise = torch.randn_like(z_start)
1279
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1280
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1281
+
1282
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1283
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1284
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1285
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1286
+ log["diffusion_row"] = diffusion_grid
1287
+
1288
+ if sample:
1289
+ # get denoise row
1290
+ with self.ema_scope("Plotting"):
1291
+ samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1292
+ x_samples = self.decode_first_stage(samples)
1293
+ log["samples"] = x_samples
1294
+ if plot_denoise_rows:
1295
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1296
+ log["denoise_row"] = denoise_grid
1297
+
1298
+ if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1299
+ self.first_stage_model, IdentityFirstStage):
1300
+ # also display when quantizing x0 while sampling
1301
+ with self.ema_scope("Plotting Quantized Denoised"):
1302
+ samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1303
+ quantize_denoised=True)
1304
+ x_samples = self.decode_first_stage(samples.to(self.device))
1305
+ log["samples_x0_quantized"] = x_samples
1306
+
1307
+ if inpaint:
1308
+ # make a simple center square
1309
+ b, h, w = z.shape[0], z.shape[2], z.shape[3]
1310
+ mask = torch.ones(N, h, w).to(self.device)
1311
+ # zeros will be filled in
1312
+ mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1313
+ mask = mask[:, None, ...]
1314
+ with self.ema_scope("Plotting Inpaint"):
1315
+ samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1316
+ quantize_denoised=False, x0=z[:N], mask=mask)
1317
+ x_samples = self.decode_first_stage(samples.to(self.device))
1318
+ log["samples_inpainting"] = x_samples
1319
+ log["mask"] = mask
1320
+ if plot_denoise_rows:
1321
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1322
+ log["denoise_row_inpainting"] = denoise_grid
1323
+
1324
+ # outpaint
1325
+ with self.ema_scope("Plotting Outpaint"):
1326
+ samples = self.sample(cond=c, batch_size=N, return_intermediates=False,
1327
+ quantize_denoised=False, x0=z[:N], mask=1. - mask)
1328
+ x_samples = self.decode_first_stage(samples.to(self.device))
1329
+ log["samples_outpainting"] = x_samples
1330
+
1331
+ if plot_progressive_rows:
1332
+ with self.ema_scope("Plotting Progressives"):
1333
+ img, progressives = self.progressive_denoising(c,
1334
+ shape=(self.channels, self.image_size, self.image_size),
1335
+ batch_size=N)
1336
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1337
+ log["progressive_row"] = prog_row
1338
+
1339
+ if return_keys:
1340
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1341
+ return log
1342
+ else:
1343
+ return {key: log[key] for key in return_keys}
1344
+ return log
1345
+
1346
+ def configure_optimizers(self):
1347
+ lr = self.learning_rate
1348
+ params = list(self.model.parameters())
1349
+ if self.cond_stage_trainable:
1350
+ print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1351
+ params = params + list(self.cond_stage_model.parameters())
1352
+ if self.learn_logvar:
1353
+ print('Diffusion model optimizing logvar')
1354
+ params.append(self.logvar)
1355
+ opt = torch.optim.AdamW(params, lr=lr)
1356
+ if self.use_scheduler:
1357
+ assert 'target' in self.scheduler_config
1358
+ scheduler = instantiate_from_config(self.scheduler_config)
1359
+
1360
+ print("Setting up LambdaLR scheduler...")
1361
+ scheduler = [
1362
+ {
1363
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1364
+ 'interval': 'step',
1365
+ 'frequency': 1
1366
+ }]
1367
+ return [opt], scheduler
1368
+ return opt
1369
+
1370
+ @torch.no_grad()
1371
+ def to_rgb(self, x):
1372
+ x = x.float()
1373
+ if not hasattr(self, "colorize"):
1374
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1375
+ x = nn.functional.conv2d(x, weight=self.colorize)
1376
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1377
+ return x
1378
+
1379
+
1380
+ class DiffusionWrapper(pl.LightningModule):
1381
+ def __init__(self, diff_model_config, conditioning_key):
1382
+ super().__init__()
1383
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1384
+ self.conditioning_key = conditioning_key
1385
+ assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
1386
+
1387
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
1388
+ if self.conditioning_key is None:
1389
+ out = self.diffusion_model(x, t)
1390
+ elif self.conditioning_key == 'concat':
1391
+ xc = torch.cat([x] + c_concat, dim=1)
1392
+ out = self.diffusion_model(xc, t)
1393
+ elif self.conditioning_key == 'crossattn':
1394
+ cc = torch.cat(c_crossattn, 1)
1395
+ out = self.diffusion_model(x, t, context=cc)
1396
+ elif self.conditioning_key == 'hybrid':
1397
+ xc = torch.cat([x] + c_concat, dim=1)
1398
+ cc = torch.cat(c_crossattn, 1)
1399
+ out = self.diffusion_model(xc, t, context=cc)
1400
+ elif self.conditioning_key == 'adm':
1401
+ cc = c_crossattn[0]
1402
+ out = self.diffusion_model(x, t, y=cc)
1403
+ else:
1404
+ raise NotImplementedError()
1405
+
1406
+ return out
1407
+
1408
+
1409
+ class Layout2ImgDiffusion(LatentDiffusion):
1410
+ # TODO: move all layout-specific hacks to this class
1411
+ def __init__(self, cond_stage_key, *args, **kwargs):
1412
+ assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
1413
+ super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
1414
+
1415
+ def log_images(self, batch, N=8, *args, **kwargs):
1416
+ logs = super().log_images(batch=batch, N=N, *args, **kwargs)
1417
+
1418
+ key = 'train' if self.training else 'validation'
1419
+ dset = self.trainer.datamodule.datasets[key]
1420
+ mapper = dset.conditional_builders[self.cond_stage_key]
1421
+
1422
+ bbox_imgs = []
1423
+ map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
1424
+ for tknzd_bbox in batch[self.cond_stage_key][:N]:
1425
+ bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
1426
+ bbox_imgs.append(bboximg)
1427
+
1428
+ cond_img = torch.stack(bbox_imgs, dim=0)
1429
+ logs['bbox_image'] = cond_img
1430
+ return logs
ldm/modules/attention.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ from ldm.modules.diffusionmodules.util import checkpoint
9
+
10
+
11
+ def exists(val):
12
+ return val is not None
13
+
14
+
15
+ def uniq(arr):
16
+ return{el: True for el in arr}.keys()
17
+
18
+
19
+ def default(val, d):
20
+ if exists(val):
21
+ return val
22
+ return d() if isfunction(d) else d
23
+
24
+
25
+ def max_neg_value(t):
26
+ return -torch.finfo(t.dtype).max
27
+
28
+
29
+ def init_(tensor):
30
+ dim = tensor.shape[-1]
31
+ std = 1 / math.sqrt(dim)
32
+ tensor.uniform_(-std, std)
33
+ return tensor
34
+
35
+
36
+ # feedforward
37
+ class GEGLU(nn.Module):
38
+ def __init__(self, dim_in, dim_out):
39
+ super().__init__()
40
+ self.proj = nn.Linear(dim_in, dim_out * 2)
41
+
42
+ def forward(self, x):
43
+ x, gate = self.proj(x).chunk(2, dim=-1)
44
+ return x * F.gelu(gate)
45
+
46
+
47
+ class FeedForward(nn.Module):
48
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
49
+ super().__init__()
50
+ inner_dim = int(dim * mult)
51
+ dim_out = default(dim_out, dim)
52
+ project_in = nn.Sequential(
53
+ nn.Linear(dim, inner_dim),
54
+ nn.GELU()
55
+ ) if not glu else GEGLU(dim, inner_dim)
56
+
57
+ self.net = nn.Sequential(
58
+ project_in,
59
+ nn.Dropout(dropout),
60
+ nn.Linear(inner_dim, dim_out)
61
+ )
62
+
63
+ def forward(self, x):
64
+ return self.net(x)
65
+
66
+
67
+ def zero_module(module):
68
+ """
69
+ Zero out the parameters of a module and return it.
70
+ """
71
+ for p in module.parameters():
72
+ p.detach().zero_()
73
+ return module
74
+
75
+
76
+ def Normalize(in_channels):
77
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
78
+
79
+
80
+ class LinearAttention(nn.Module):
81
+ def __init__(self, dim, heads=4, dim_head=32):
82
+ super().__init__()
83
+ self.heads = heads
84
+ hidden_dim = dim_head * heads
85
+ self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
86
+ self.to_out = nn.Conv2d(hidden_dim, dim, 1)
87
+
88
+ def forward(self, x):
89
+ b, c, h, w = x.shape
90
+ qkv = self.to_qkv(x)
91
+ q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
92
+ k = k.softmax(dim=-1)
93
+ context = torch.einsum('bhdn,bhen->bhde', k, v)
94
+ out = torch.einsum('bhde,bhdn->bhen', context, q)
95
+ out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
96
+ return self.to_out(out)
97
+
98
+
99
+ class SpatialSelfAttention(nn.Module):
100
+ def __init__(self, in_channels):
101
+ super().__init__()
102
+ self.in_channels = in_channels
103
+
104
+ self.norm = Normalize(in_channels)
105
+ self.q = torch.nn.Conv2d(in_channels,
106
+ in_channels,
107
+ kernel_size=1,
108
+ stride=1,
109
+ padding=0)
110
+ self.k = torch.nn.Conv2d(in_channels,
111
+ in_channels,
112
+ kernel_size=1,
113
+ stride=1,
114
+ padding=0)
115
+ self.v = torch.nn.Conv2d(in_channels,
116
+ in_channels,
117
+ kernel_size=1,
118
+ stride=1,
119
+ padding=0)
120
+ self.proj_out = torch.nn.Conv2d(in_channels,
121
+ in_channels,
122
+ kernel_size=1,
123
+ stride=1,
124
+ padding=0)
125
+
126
+ def forward(self, x):
127
+ h_ = x
128
+ h_ = self.norm(h_)
129
+ q = self.q(h_)
130
+ k = self.k(h_)
131
+ v = self.v(h_)
132
+
133
+ # compute attention
134
+ b,c,h,w = q.shape
135
+ q = rearrange(q, 'b c h w -> b (h w) c')
136
+ k = rearrange(k, 'b c h w -> b c (h w)')
137
+ w_ = torch.einsum('bij,bjk->bik', q, k)
138
+
139
+ w_ = w_ * (int(c)**(-0.5))
140
+ w_ = torch.nn.functional.softmax(w_, dim=2)
141
+
142
+ # attend to values
143
+ v = rearrange(v, 'b c h w -> b c (h w)')
144
+ w_ = rearrange(w_, 'b i j -> b j i')
145
+ h_ = torch.einsum('bij,bjk->bik', v, w_)
146
+ h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
147
+ h_ = self.proj_out(h_)
148
+
149
+ return x+h_
150
+
151
+
152
+ class CrossAttention(nn.Module):
153
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
154
+ super().__init__()
155
+ inner_dim = dim_head * heads
156
+ context_dim = default(context_dim, query_dim)
157
+
158
+ self.scale = dim_head ** -0.5
159
+ self.heads = heads
160
+
161
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
162
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
163
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
164
+
165
+ self.to_out = nn.Sequential(
166
+ nn.Linear(inner_dim, query_dim),
167
+ nn.Dropout(dropout)
168
+ )
169
+
170
+ def forward(self, x, context=None, mask=None):
171
+ h = self.heads
172
+
173
+ q = self.to_q(x)
174
+ context = default(context, x)
175
+ k = self.to_k(context)
176
+ v = self.to_v(context)
177
+
178
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
179
+
180
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
181
+
182
+ if exists(mask):
183
+ mask = rearrange(mask, 'b ... -> b (...)')
184
+ max_neg_value = -torch.finfo(sim.dtype).max
185
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
186
+ sim.masked_fill_(~mask, max_neg_value)
187
+
188
+ # attention, what we cannot get enough of
189
+ attn = sim.softmax(dim=-1)
190
+
191
+ out = einsum('b i j, b j d -> b i d', attn, v)
192
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
193
+ return self.to_out(out)
194
+
195
+
196
+ class BasicTransformerBlock(nn.Module):
197
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True):
198
+ super().__init__()
199
+ self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) # is a self-attention
200
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
201
+ self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
202
+ heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
203
+ self.norm1 = nn.LayerNorm(dim)
204
+ self.norm2 = nn.LayerNorm(dim)
205
+ self.norm3 = nn.LayerNorm(dim)
206
+ self.checkpoint = checkpoint
207
+
208
+ def forward(self, x, context=None):
209
+ return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
210
+
211
+ def _forward(self, x, context=None):
212
+ x = self.attn1(self.norm1(x)) + x
213
+ x = self.attn2(self.norm2(x), context=context) + x
214
+ x = self.ff(self.norm3(x)) + x
215
+ return x
216
+
217
+
218
+ class SpatialTransformer(nn.Module):
219
+ """
220
+ Transformer block for image-like data.
221
+ First, project the input (aka embedding)
222
+ and reshape to b, t, d.
223
+ Then apply standard transformer action.
224
+ Finally, reshape to image
225
+ """
226
+ def __init__(self, in_channels, n_heads, d_head,
227
+ depth=1, dropout=0., context_dim=None):
228
+ super().__init__()
229
+ self.in_channels = in_channels
230
+ inner_dim = n_heads * d_head
231
+ self.norm = Normalize(in_channels)
232
+
233
+ self.proj_in = nn.Conv2d(in_channels,
234
+ inner_dim,
235
+ kernel_size=1,
236
+ stride=1,
237
+ padding=0)
238
+
239
+ self.transformer_blocks = nn.ModuleList(
240
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim)
241
+ for d in range(depth)]
242
+ )
243
+
244
+ self.proj_out = zero_module(nn.Conv2d(inner_dim,
245
+ in_channels,
246
+ kernel_size=1,
247
+ stride=1,
248
+ padding=0))
249
+
250
+ def forward(self, x, context=None):
251
+ # note: if no context is given, cross-attention defaults to self-attention
252
+ b, c, h, w = x.shape
253
+ x_in = x
254
+ x = self.norm(x)
255
+ x = self.proj_in(x)
256
+ x = rearrange(x, 'b c h w -> b (h w) c')
257
+ for block in self.transformer_blocks:
258
+ x = block(x, context=context)
259
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
260
+ x = self.proj_out(x)
261
+ return x + x_in
ldm/modules/diffusionmodules/__init__.py ADDED
File without changes
ldm/modules/diffusionmodules/model.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pytorch_diffusion + derived encoder decoder
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ from einops import rearrange
7
+
8
+ from ldm.util import instantiate_from_config
9
+ from ldm.modules.attention import LinearAttention
10
+
11
+
12
+ def get_timestep_embedding(timesteps, embedding_dim):
13
+ """
14
+ This matches the implementation in Denoising Diffusion Probabilistic Models:
15
+ From Fairseq.
16
+ Build sinusoidal embeddings.
17
+ This matches the implementation in tensor2tensor, but differs slightly
18
+ from the description in Section 3.5 of "Attention Is All You Need".
19
+ """
20
+ assert len(timesteps.shape) == 1
21
+
22
+ half_dim = embedding_dim // 2
23
+ emb = math.log(10000) / (half_dim - 1)
24
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
25
+ emb = emb.to(device=timesteps.device)
26
+ emb = timesteps.float()[:, None] * emb[None, :]
27
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
28
+ if embedding_dim % 2 == 1: # zero pad
29
+ emb = torch.nn.functional.pad(emb, (0,1,0,0))
30
+ return emb
31
+
32
+
33
+ def nonlinearity(x):
34
+ # swish
35
+ return x*torch.sigmoid(x)
36
+
37
+
38
+ def Normalize(in_channels, num_groups=32):
39
+ return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
40
+
41
+
42
+ class Upsample(nn.Module):
43
+ def __init__(self, in_channels, with_conv):
44
+ super().__init__()
45
+ self.with_conv = with_conv
46
+ if self.with_conv:
47
+ self.conv = torch.nn.Conv2d(in_channels,
48
+ in_channels,
49
+ kernel_size=3,
50
+ stride=1,
51
+ padding=1)
52
+
53
+ def forward(self, x):
54
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
55
+ if self.with_conv:
56
+ x = self.conv(x)
57
+ return x
58
+
59
+
60
+ class Downsample(nn.Module):
61
+ def __init__(self, in_channels, with_conv):
62
+ super().__init__()
63
+ self.with_conv = with_conv
64
+ if self.with_conv:
65
+ # no asymmetric padding in torch conv, must do it ourselves
66
+ self.conv = torch.nn.Conv2d(in_channels,
67
+ in_channels,
68
+ kernel_size=3,
69
+ stride=2,
70
+ padding=0)
71
+
72
+ def forward(self, x):
73
+ if self.with_conv:
74
+ pad = (0,1,0,1)
75
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
76
+ x = self.conv(x)
77
+ else:
78
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
79
+ return x
80
+
81
+
82
+ class ResnetBlock(nn.Module):
83
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
84
+ dropout, temb_channels=512):
85
+ super().__init__()
86
+ self.in_channels = in_channels
87
+ out_channels = in_channels if out_channels is None else out_channels
88
+ self.out_channels = out_channels
89
+ self.use_conv_shortcut = conv_shortcut
90
+
91
+ self.norm1 = Normalize(in_channels)
92
+ self.conv1 = torch.nn.Conv2d(in_channels,
93
+ out_channels,
94
+ kernel_size=3,
95
+ stride=1,
96
+ padding=1)
97
+ if temb_channels > 0:
98
+ self.temb_proj = torch.nn.Linear(temb_channels,
99
+ out_channels)
100
+ self.norm2 = Normalize(out_channels)
101
+ self.dropout = torch.nn.Dropout(dropout)
102
+ self.conv2 = torch.nn.Conv2d(out_channels,
103
+ out_channels,
104
+ kernel_size=3,
105
+ stride=1,
106
+ padding=1)
107
+ if self.in_channels != self.out_channels:
108
+ if self.use_conv_shortcut:
109
+ self.conv_shortcut = torch.nn.Conv2d(in_channels,
110
+ out_channels,
111
+ kernel_size=3,
112
+ stride=1,
113
+ padding=1)
114
+ else:
115
+ self.nin_shortcut = torch.nn.Conv2d(in_channels,
116
+ out_channels,
117
+ kernel_size=1,
118
+ stride=1,
119
+ padding=0)
120
+
121
+ def forward(self, x, temb):
122
+ h = x
123
+ h = self.norm1(h)
124
+ h = nonlinearity(h)
125
+ h = self.conv1(h)
126
+
127
+ if temb is not None:
128
+ h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
129
+
130
+ h = self.norm2(h)
131
+ h = nonlinearity(h)
132
+ h = self.dropout(h)
133
+ h = self.conv2(h)
134
+
135
+ if self.in_channels != self.out_channels:
136
+ if self.use_conv_shortcut:
137
+ x = self.conv_shortcut(x)
138
+ else:
139
+ x = self.nin_shortcut(x)
140
+
141
+ return x+h
142
+
143
+
144
+ class LinAttnBlock(LinearAttention):
145
+ """to match AttnBlock usage"""
146
+ def __init__(self, in_channels):
147
+ super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
148
+
149
+
150
+ class AttnBlock(nn.Module):
151
+ def __init__(self, in_channels):
152
+ super().__init__()
153
+ self.in_channels = in_channels
154
+
155
+ self.norm = Normalize(in_channels)
156
+ self.q = torch.nn.Conv2d(in_channels,
157
+ in_channels,
158
+ kernel_size=1,
159
+ stride=1,
160
+ padding=0)
161
+ self.k = torch.nn.Conv2d(in_channels,
162
+ in_channels,
163
+ kernel_size=1,
164
+ stride=1,
165
+ padding=0)
166
+ self.v = torch.nn.Conv2d(in_channels,
167
+ in_channels,
168
+ kernel_size=1,
169
+ stride=1,
170
+ padding=0)
171
+ self.proj_out = torch.nn.Conv2d(in_channels,
172
+ in_channels,
173
+ kernel_size=1,
174
+ stride=1,
175
+ padding=0)
176
+
177
+
178
+ def forward(self, x):
179
+ h_ = x
180
+ h_ = self.norm(h_)
181
+ q = self.q(h_)
182
+ k = self.k(h_)
183
+ v = self.v(h_)
184
+
185
+ # compute attention
186
+ b,c,h,w = q.shape
187
+ q = q.reshape(b,c,h*w)
188
+ q = q.permute(0,2,1) # b,hw,c
189
+ k = k.reshape(b,c,h*w) # b,c,hw
190
+ w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
191
+ w_ = w_ * (int(c)**(-0.5))
192
+ w_ = torch.nn.functional.softmax(w_, dim=2)
193
+
194
+ # attend to values
195
+ v = v.reshape(b,c,h*w)
196
+ w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
197
+ h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
198
+ h_ = h_.reshape(b,c,h,w)
199
+
200
+ h_ = self.proj_out(h_)
201
+
202
+ return x+h_
203
+
204
+
205
+ def make_attn(in_channels, attn_type="vanilla"):
206
+ assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
207
+ print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
208
+ if attn_type == "vanilla":
209
+ return AttnBlock(in_channels)
210
+ elif attn_type == "none":
211
+ return nn.Identity(in_channels)
212
+ else:
213
+ return LinAttnBlock(in_channels)
214
+
215
+
216
+ class Model(nn.Module):
217
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
218
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
219
+ resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
220
+ super().__init__()
221
+ if use_linear_attn: attn_type = "linear"
222
+ self.ch = ch
223
+ self.temb_ch = self.ch*4
224
+ self.num_resolutions = len(ch_mult)
225
+ self.num_res_blocks = num_res_blocks
226
+ self.resolution = resolution
227
+ self.in_channels = in_channels
228
+
229
+ self.use_timestep = use_timestep
230
+ if self.use_timestep:
231
+ # timestep embedding
232
+ self.temb = nn.Module()
233
+ self.temb.dense = nn.ModuleList([
234
+ torch.nn.Linear(self.ch,
235
+ self.temb_ch),
236
+ torch.nn.Linear(self.temb_ch,
237
+ self.temb_ch),
238
+ ])
239
+
240
+ # downsampling
241
+ self.conv_in = torch.nn.Conv2d(in_channels,
242
+ self.ch,
243
+ kernel_size=3,
244
+ stride=1,
245
+ padding=1)
246
+
247
+ curr_res = resolution
248
+ in_ch_mult = (1,)+tuple(ch_mult)
249
+ self.down = nn.ModuleList()
250
+ for i_level in range(self.num_resolutions):
251
+ block = nn.ModuleList()
252
+ attn = nn.ModuleList()
253
+ block_in = ch*in_ch_mult[i_level]
254
+ block_out = ch*ch_mult[i_level]
255
+ for i_block in range(self.num_res_blocks):
256
+ block.append(ResnetBlock(in_channels=block_in,
257
+ out_channels=block_out,
258
+ temb_channels=self.temb_ch,
259
+ dropout=dropout))
260
+ block_in = block_out
261
+ if curr_res in attn_resolutions:
262
+ attn.append(make_attn(block_in, attn_type=attn_type))
263
+ down = nn.Module()
264
+ down.block = block
265
+ down.attn = attn
266
+ if i_level != self.num_resolutions-1:
267
+ down.downsample = Downsample(block_in, resamp_with_conv)
268
+ curr_res = curr_res // 2
269
+ self.down.append(down)
270
+
271
+ # middle
272
+ self.mid = nn.Module()
273
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
274
+ out_channels=block_in,
275
+ temb_channels=self.temb_ch,
276
+ dropout=dropout)
277
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
278
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
279
+ out_channels=block_in,
280
+ temb_channels=self.temb_ch,
281
+ dropout=dropout)
282
+
283
+ # upsampling
284
+ self.up = nn.ModuleList()
285
+ for i_level in reversed(range(self.num_resolutions)):
286
+ block = nn.ModuleList()
287
+ attn = nn.ModuleList()
288
+ block_out = ch*ch_mult[i_level]
289
+ skip_in = ch*ch_mult[i_level]
290
+ for i_block in range(self.num_res_blocks+1):
291
+ if i_block == self.num_res_blocks:
292
+ skip_in = ch*in_ch_mult[i_level]
293
+ block.append(ResnetBlock(in_channels=block_in+skip_in,
294
+ out_channels=block_out,
295
+ temb_channels=self.temb_ch,
296
+ dropout=dropout))
297
+ block_in = block_out
298
+ if curr_res in attn_resolutions:
299
+ attn.append(make_attn(block_in, attn_type=attn_type))
300
+ up = nn.Module()
301
+ up.block = block
302
+ up.attn = attn
303
+ if i_level != 0:
304
+ up.upsample = Upsample(block_in, resamp_with_conv)
305
+ curr_res = curr_res * 2
306
+ self.up.insert(0, up) # prepend to get consistent order
307
+
308
+ # end
309
+ self.norm_out = Normalize(block_in)
310
+ self.conv_out = torch.nn.Conv2d(block_in,
311
+ out_ch,
312
+ kernel_size=3,
313
+ stride=1,
314
+ padding=1)
315
+
316
+ def forward(self, x, t=None, context=None):
317
+ #assert x.shape[2] == x.shape[3] == self.resolution
318
+ if context is not None:
319
+ # assume aligned context, cat along channel axis
320
+ x = torch.cat((x, context), dim=1)
321
+ if self.use_timestep:
322
+ # timestep embedding
323
+ assert t is not None
324
+ temb = get_timestep_embedding(t, self.ch)
325
+ temb = self.temb.dense[0](temb)
326
+ temb = nonlinearity(temb)
327
+ temb = self.temb.dense[1](temb)
328
+ else:
329
+ temb = None
330
+
331
+ # downsampling
332
+ hs = [self.conv_in(x)]
333
+ for i_level in range(self.num_resolutions):
334
+ for i_block in range(self.num_res_blocks):
335
+ h = self.down[i_level].block[i_block](hs[-1], temb)
336
+ if len(self.down[i_level].attn) > 0:
337
+ h = self.down[i_level].attn[i_block](h)
338
+ hs.append(h)
339
+ if i_level != self.num_resolutions-1:
340
+ hs.append(self.down[i_level].downsample(hs[-1]))
341
+
342
+ # middle
343
+ h = hs[-1]
344
+ h = self.mid.block_1(h, temb)
345
+ h = self.mid.attn_1(h)
346
+ h = self.mid.block_2(h, temb)
347
+
348
+ # upsampling
349
+ for i_level in reversed(range(self.num_resolutions)):
350
+ for i_block in range(self.num_res_blocks+1):
351
+ h = self.up[i_level].block[i_block](
352
+ torch.cat([h, hs.pop()], dim=1), temb)
353
+ if len(self.up[i_level].attn) > 0:
354
+ h = self.up[i_level].attn[i_block](h)
355
+ if i_level != 0:
356
+ h = self.up[i_level].upsample(h)
357
+
358
+ # end
359
+ h = self.norm_out(h)
360
+ h = nonlinearity(h)
361
+ h = self.conv_out(h)
362
+ return h
363
+
364
+ def get_last_layer(self):
365
+ return self.conv_out.weight
366
+
367
+
368
+ class Encoder(nn.Module):
369
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
370
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
371
+ resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
372
+ **ignore_kwargs):
373
+ super().__init__()
374
+ if use_linear_attn: attn_type = "linear"
375
+ self.ch = ch
376
+ self.temb_ch = 0
377
+ self.num_resolutions = len(ch_mult)
378
+ self.num_res_blocks = num_res_blocks
379
+ self.resolution = resolution
380
+ self.in_channels = in_channels
381
+
382
+ # downsampling
383
+ self.conv_in = torch.nn.Conv2d(in_channels,
384
+ self.ch,
385
+ kernel_size=3,
386
+ stride=1,
387
+ padding=1)
388
+
389
+ curr_res = resolution
390
+ in_ch_mult = (1,)+tuple(ch_mult)
391
+ self.in_ch_mult = in_ch_mult
392
+ self.down = nn.ModuleList()
393
+ for i_level in range(self.num_resolutions):
394
+ block = nn.ModuleList()
395
+ attn = nn.ModuleList()
396
+ block_in = ch*in_ch_mult[i_level]
397
+ block_out = ch*ch_mult[i_level]
398
+ for i_block in range(self.num_res_blocks):
399
+ block.append(ResnetBlock(in_channels=block_in,
400
+ out_channels=block_out,
401
+ temb_channels=self.temb_ch,
402
+ dropout=dropout))
403
+ block_in = block_out
404
+ if curr_res in attn_resolutions:
405
+ attn.append(make_attn(block_in, attn_type=attn_type))
406
+ down = nn.Module()
407
+ down.block = block
408
+ down.attn = attn
409
+ if i_level != self.num_resolutions-1:
410
+ down.downsample = Downsample(block_in, resamp_with_conv)
411
+ curr_res = curr_res // 2
412
+ self.down.append(down)
413
+
414
+ # middle
415
+ self.mid = nn.Module()
416
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
417
+ out_channels=block_in,
418
+ temb_channels=self.temb_ch,
419
+ dropout=dropout)
420
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
421
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
422
+ out_channels=block_in,
423
+ temb_channels=self.temb_ch,
424
+ dropout=dropout)
425
+
426
+ # end
427
+ self.norm_out = Normalize(block_in)
428
+ self.conv_out = torch.nn.Conv2d(block_in,
429
+ 2*z_channels if double_z else z_channels,
430
+ kernel_size=3,
431
+ stride=1,
432
+ padding=1)
433
+
434
+ def forward(self, x):
435
+ # timestep embedding
436
+ temb = None
437
+
438
+ # downsampling
439
+ hs = [self.conv_in(x)]
440
+ for i_level in range(self.num_resolutions):
441
+ for i_block in range(self.num_res_blocks):
442
+ h = self.down[i_level].block[i_block](hs[-1], temb)
443
+ if len(self.down[i_level].attn) > 0:
444
+ h = self.down[i_level].attn[i_block](h)
445
+ hs.append(h)
446
+ if i_level != self.num_resolutions-1:
447
+ hs.append(self.down[i_level].downsample(hs[-1]))
448
+
449
+ # middle
450
+ h = hs[-1]
451
+ h = self.mid.block_1(h, temb)
452
+ h = self.mid.attn_1(h)
453
+ h = self.mid.block_2(h, temb)
454
+
455
+ # end
456
+ h = self.norm_out(h)
457
+ h = nonlinearity(h)
458
+ h = self.conv_out(h)
459
+ return h
460
+
461
+
462
+ class Decoder(nn.Module):
463
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
464
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
465
+ resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
466
+ attn_type="vanilla", **ignorekwargs):
467
+ super().__init__()
468
+ if use_linear_attn: attn_type = "linear"
469
+ self.ch = ch
470
+ self.temb_ch = 0
471
+ self.num_resolutions = len(ch_mult)
472
+ self.num_res_blocks = num_res_blocks
473
+ self.resolution = resolution
474
+ self.in_channels = in_channels
475
+ self.give_pre_end = give_pre_end
476
+ self.tanh_out = tanh_out
477
+
478
+ # compute in_ch_mult, block_in and curr_res at lowest res
479
+ in_ch_mult = (1,)+tuple(ch_mult)
480
+ block_in = ch*ch_mult[self.num_resolutions-1]
481
+ curr_res = resolution // 2**(self.num_resolutions-1)
482
+ self.z_shape = (1,z_channels,curr_res,curr_res)
483
+ print("Working with z of shape {} = {} dimensions.".format(
484
+ self.z_shape, np.prod(self.z_shape)))
485
+
486
+ # z to block_in
487
+ self.conv_in = torch.nn.Conv2d(z_channels,
488
+ block_in,
489
+ kernel_size=3,
490
+ stride=1,
491
+ padding=1)
492
+
493
+ # middle
494
+ self.mid = nn.Module()
495
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
496
+ out_channels=block_in,
497
+ temb_channels=self.temb_ch,
498
+ dropout=dropout)
499
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
500
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
501
+ out_channels=block_in,
502
+ temb_channels=self.temb_ch,
503
+ dropout=dropout)
504
+
505
+ # upsampling
506
+ self.up = nn.ModuleList()
507
+ for i_level in reversed(range(self.num_resolutions)):
508
+ block = nn.ModuleList()
509
+ attn = nn.ModuleList()
510
+ block_out = ch*ch_mult[i_level]
511
+ for i_block in range(self.num_res_blocks+1):
512
+ block.append(ResnetBlock(in_channels=block_in,
513
+ out_channels=block_out,
514
+ temb_channels=self.temb_ch,
515
+ dropout=dropout))
516
+ block_in = block_out
517
+ if curr_res in attn_resolutions:
518
+ attn.append(make_attn(block_in, attn_type=attn_type))
519
+ up = nn.Module()
520
+ up.block = block
521
+ up.attn = attn
522
+ if i_level != 0:
523
+ up.upsample = Upsample(block_in, resamp_with_conv)
524
+ curr_res = curr_res * 2
525
+ self.up.insert(0, up) # prepend to get consistent order
526
+
527
+ # end
528
+ self.norm_out = Normalize(block_in)
529
+ self.conv_out = torch.nn.Conv2d(block_in,
530
+ out_ch,
531
+ kernel_size=3,
532
+ stride=1,
533
+ padding=1)
534
+
535
+ def forward(self, z):
536
+ #assert z.shape[1:] == self.z_shape[1:]
537
+ self.last_z_shape = z.shape
538
+
539
+ # timestep embedding
540
+ temb = None
541
+
542
+ # z to block_in
543
+ h = self.conv_in(z)
544
+
545
+ # middle
546
+ h = self.mid.block_1(h, temb)
547
+ h = self.mid.attn_1(h)
548
+ h = self.mid.block_2(h, temb)
549
+
550
+ # upsampling
551
+ for i_level in reversed(range(self.num_resolutions)):
552
+ for i_block in range(self.num_res_blocks+1):
553
+ h = self.up[i_level].block[i_block](h, temb)
554
+ if len(self.up[i_level].attn) > 0:
555
+ h = self.up[i_level].attn[i_block](h)
556
+ if i_level != 0:
557
+ h = self.up[i_level].upsample(h)
558
+
559
+ # end
560
+ if self.give_pre_end:
561
+ return h
562
+
563
+ h = self.norm_out(h)
564
+ h = nonlinearity(h)
565
+ h = self.conv_out(h)
566
+ if self.tanh_out:
567
+ h = torch.tanh(h)
568
+ return h
569
+
570
+
571
+ class SimpleDecoder(nn.Module):
572
+ def __init__(self, in_channels, out_channels, *args, **kwargs):
573
+ super().__init__()
574
+ self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
575
+ ResnetBlock(in_channels=in_channels,
576
+ out_channels=2 * in_channels,
577
+ temb_channels=0, dropout=0.0),
578
+ ResnetBlock(in_channels=2 * in_channels,
579
+ out_channels=4 * in_channels,
580
+ temb_channels=0, dropout=0.0),
581
+ ResnetBlock(in_channels=4 * in_channels,
582
+ out_channels=2 * in_channels,
583
+ temb_channels=0, dropout=0.0),
584
+ nn.Conv2d(2*in_channels, in_channels, 1),
585
+ Upsample(in_channels, with_conv=True)])
586
+ # end
587
+ self.norm_out = Normalize(in_channels)
588
+ self.conv_out = torch.nn.Conv2d(in_channels,
589
+ out_channels,
590
+ kernel_size=3,
591
+ stride=1,
592
+ padding=1)
593
+
594
+ def forward(self, x):
595
+ for i, layer in enumerate(self.model):
596
+ if i in [1,2,3]:
597
+ x = layer(x, None)
598
+ else:
599
+ x = layer(x)
600
+
601
+ h = self.norm_out(x)
602
+ h = nonlinearity(h)
603
+ x = self.conv_out(h)
604
+ return x
605
+
606
+
607
+ class UpsampleDecoder(nn.Module):
608
+ def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
609
+ ch_mult=(2,2), dropout=0.0):
610
+ super().__init__()
611
+ # upsampling
612
+ self.temb_ch = 0
613
+ self.num_resolutions = len(ch_mult)
614
+ self.num_res_blocks = num_res_blocks
615
+ block_in = in_channels
616
+ curr_res = resolution // 2 ** (self.num_resolutions - 1)
617
+ self.res_blocks = nn.ModuleList()
618
+ self.upsample_blocks = nn.ModuleList()
619
+ for i_level in range(self.num_resolutions):
620
+ res_block = []
621
+ block_out = ch * ch_mult[i_level]
622
+ for i_block in range(self.num_res_blocks + 1):
623
+ res_block.append(ResnetBlock(in_channels=block_in,
624
+ out_channels=block_out,
625
+ temb_channels=self.temb_ch,
626
+ dropout=dropout))
627
+ block_in = block_out
628
+ self.res_blocks.append(nn.ModuleList(res_block))
629
+ if i_level != self.num_resolutions - 1:
630
+ self.upsample_blocks.append(Upsample(block_in, True))
631
+ curr_res = curr_res * 2
632
+
633
+ # end
634
+ self.norm_out = Normalize(block_in)
635
+ self.conv_out = torch.nn.Conv2d(block_in,
636
+ out_channels,
637
+ kernel_size=3,
638
+ stride=1,
639
+ padding=1)
640
+
641
+ def forward(self, x):
642
+ # upsampling
643
+ h = x
644
+ for k, i_level in enumerate(range(self.num_resolutions)):
645
+ for i_block in range(self.num_res_blocks + 1):
646
+ h = self.res_blocks[i_level][i_block](h, None)
647
+ if i_level != self.num_resolutions - 1:
648
+ h = self.upsample_blocks[k](h)
649
+ h = self.norm_out(h)
650
+ h = nonlinearity(h)
651
+ h = self.conv_out(h)
652
+ return h
653
+
654
+
655
+ class LatentRescaler(nn.Module):
656
+ def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
657
+ super().__init__()
658
+ # residual block, interpolate, residual block
659
+ self.factor = factor
660
+ self.conv_in = nn.Conv2d(in_channels,
661
+ mid_channels,
662
+ kernel_size=3,
663
+ stride=1,
664
+ padding=1)
665
+ self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
666
+ out_channels=mid_channels,
667
+ temb_channels=0,
668
+ dropout=0.0) for _ in range(depth)])
669
+ self.attn = AttnBlock(mid_channels)
670
+ self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
671
+ out_channels=mid_channels,
672
+ temb_channels=0,
673
+ dropout=0.0) for _ in range(depth)])
674
+
675
+ self.conv_out = nn.Conv2d(mid_channels,
676
+ out_channels,
677
+ kernel_size=1,
678
+ )
679
+
680
+ def forward(self, x):
681
+ x = self.conv_in(x)
682
+ for block in self.res_block1:
683
+ x = block(x, None)
684
+ x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
685
+ x = self.attn(x)
686
+ for block in self.res_block2:
687
+ x = block(x, None)
688
+ x = self.conv_out(x)
689
+ return x
690
+
691
+
692
+ class MergedRescaleEncoder(nn.Module):
693
+ def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
694
+ attn_resolutions, dropout=0.0, resamp_with_conv=True,
695
+ ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
696
+ super().__init__()
697
+ intermediate_chn = ch * ch_mult[-1]
698
+ self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
699
+ z_channels=intermediate_chn, double_z=False, resolution=resolution,
700
+ attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
701
+ out_ch=None)
702
+ self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
703
+ mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
704
+
705
+ def forward(self, x):
706
+ x = self.encoder(x)
707
+ x = self.rescaler(x)
708
+ return x
709
+
710
+
711
+ class MergedRescaleDecoder(nn.Module):
712
+ def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
713
+ dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
714
+ super().__init__()
715
+ tmp_chn = z_channels*ch_mult[-1]
716
+ self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
717
+ resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
718
+ ch_mult=ch_mult, resolution=resolution, ch=ch)
719
+ self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
720
+ out_channels=tmp_chn, depth=rescale_module_depth)
721
+
722
+ def forward(self, x):
723
+ x = self.rescaler(x)
724
+ x = self.decoder(x)
725
+ return x
726
+
727
+
728
+ class Upsampler(nn.Module):
729
+ def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
730
+ super().__init__()
731
+ assert out_size >= in_size
732
+ num_blocks = int(np.log2(out_size//in_size))+1
733
+ factor_up = 1.+ (out_size % in_size)
734
+ print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
735
+ self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
736
+ out_channels=in_channels)
737
+ self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
738
+ attn_resolutions=[], in_channels=None, ch=in_channels,
739
+ ch_mult=[ch_mult for _ in range(num_blocks)])
740
+
741
+ def forward(self, x):
742
+ x = self.rescaler(x)
743
+ x = self.decoder(x)
744
+ return x
745
+
746
+
747
+ class Resize(nn.Module):
748
+ def __init__(self, in_channels=None, learned=False, mode="bilinear"):
749
+ super().__init__()
750
+ self.with_conv = learned
751
+ self.mode = mode
752
+ if self.with_conv:
753
+ print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
754
+ raise NotImplementedError()
755
+ assert in_channels is not None
756
+ # no asymmetric padding in torch conv, must do it ourselves
757
+ self.conv = torch.nn.Conv2d(in_channels,
758
+ in_channels,
759
+ kernel_size=4,
760
+ stride=2,
761
+ padding=1)
762
+
763
+ def forward(self, x, scale_factor=1.0):
764
+ if scale_factor==1.0:
765
+ return x
766
+ else:
767
+ x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
768
+ return x
769
+
770
+ class FirstStagePostProcessor(nn.Module):
771
+
772
+ def __init__(self, ch_mult:list, in_channels,
773
+ pretrained_model:nn.Module=None,
774
+ reshape=False,
775
+ n_channels=None,
776
+ dropout=0.,
777
+ pretrained_config=None):
778
+ super().__init__()
779
+ if pretrained_config is None:
780
+ assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
781
+ self.pretrained_model = pretrained_model
782
+ else:
783
+ assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
784
+ self.instantiate_pretrained(pretrained_config)
785
+
786
+ self.do_reshape = reshape
787
+
788
+ if n_channels is None:
789
+ n_channels = self.pretrained_model.encoder.ch
790
+
791
+ self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
792
+ self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
793
+ stride=1,padding=1)
794
+
795
+ blocks = []
796
+ downs = []
797
+ ch_in = n_channels
798
+ for m in ch_mult:
799
+ blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
800
+ ch_in = m * n_channels
801
+ downs.append(Downsample(ch_in, with_conv=False))
802
+
803
+ self.model = nn.ModuleList(blocks)
804
+ self.downsampler = nn.ModuleList(downs)
805
+
806
+
807
+ def instantiate_pretrained(self, config):
808
+ model = instantiate_from_config(config)
809
+ self.pretrained_model = model.eval()
810
+ # self.pretrained_model.train = False
811
+ for param in self.pretrained_model.parameters():
812
+ param.requires_grad = False
813
+
814
+
815
+ @torch.no_grad()
816
+ def encode_with_pretrained(self,x):
817
+ c = self.pretrained_model.encode(x)
818
+ if isinstance(c, DiagonalGaussianDistribution):
819
+ c = c.mode()
820
+ return c
821
+
822
+ def forward(self,x):
823
+ z_fs = self.encode_with_pretrained(x)
824
+ z = self.proj_norm(z_fs)
825
+ z = self.proj(z)
826
+ z = nonlinearity(z)
827
+
828
+ for submodel, downmodel in zip(self.model,self.downsampler):
829
+ z = submodel(z,temb=None)
830
+ z = downmodel(z)
831
+
832
+ if self.do_reshape:
833
+ z = rearrange(z,'b c h w -> b (h w) c')
834
+ return z
835
+
ldm/modules/diffusionmodules/openaimodel.py ADDED
@@ -0,0 +1,936 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ from functools import partial
3
+ import math
4
+ from typing import Iterable
5
+
6
+ import numpy as np
7
+ import torch as th
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from ldm.modules.diffusionmodules.util import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ )
20
+ from ldm.modules.attention import SpatialTransformer
21
+
22
+
23
+ # dummy replace
24
+ def convert_module_to_f16(x):
25
+ pass
26
+
27
+ def convert_module_to_f32(x):
28
+ pass
29
+
30
+
31
+ ## go
32
+ class AttentionPool2d(nn.Module):
33
+ """
34
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ spacial_dim: int,
40
+ embed_dim: int,
41
+ num_heads_channels: int,
42
+ output_dim: int = None,
43
+ ):
44
+ super().__init__()
45
+ self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
46
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
47
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
48
+ self.num_heads = embed_dim // num_heads_channels
49
+ self.attention = QKVAttention(self.num_heads)
50
+
51
+ def forward(self, x):
52
+ b, c, *_spatial = x.shape
53
+ x = x.reshape(b, c, -1) # NC(HW)
54
+ x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
55
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
56
+ x = self.qkv_proj(x)
57
+ x = self.attention(x)
58
+ x = self.c_proj(x)
59
+ return x[:, :, 0]
60
+
61
+
62
+ class TimestepBlock(nn.Module):
63
+ """
64
+ Any module where forward() takes timestep embeddings as a second argument.
65
+ """
66
+
67
+ @abstractmethod
68
+ def forward(self, x, emb):
69
+ """
70
+ Apply the module to `x` given `emb` timestep embeddings.
71
+ """
72
+
73
+
74
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
75
+ """
76
+ A sequential module that passes timestep embeddings to the children that
77
+ support it as an extra input.
78
+ """
79
+
80
+ def forward(self, x, emb, context=None):
81
+ for layer in self:
82
+ if isinstance(layer, TimestepBlock):
83
+ x = layer(x, emb)
84
+ elif isinstance(layer, SpatialTransformer):
85
+ x = layer(x, context)
86
+ else:
87
+ x = layer(x)
88
+ return x
89
+
90
+
91
+ class Upsample(nn.Module):
92
+ """
93
+ An upsampling layer with an optional convolution.
94
+ :param channels: channels in the inputs and outputs.
95
+ :param use_conv: a bool determining if a convolution is applied.
96
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
97
+ upsampling occurs in the inner-two dimensions.
98
+ """
99
+
100
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
101
+ super().__init__()
102
+ self.channels = channels
103
+ self.out_channels = out_channels or channels
104
+ self.use_conv = use_conv
105
+ self.dims = dims
106
+ if use_conv:
107
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
108
+
109
+ def forward(self, x):
110
+ assert x.shape[1] == self.channels
111
+ if self.dims == 3:
112
+ x = F.interpolate(
113
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
114
+ )
115
+ else:
116
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
117
+ if self.use_conv:
118
+ x = self.conv(x)
119
+ return x
120
+
121
+ class TransposedUpsample(nn.Module):
122
+ 'Learned 2x upsampling without padding'
123
+ def __init__(self, channels, out_channels=None, ks=5):
124
+ super().__init__()
125
+ self.channels = channels
126
+ self.out_channels = out_channels or channels
127
+
128
+ self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
129
+
130
+ def forward(self,x):
131
+ return self.up(x)
132
+
133
+
134
+ class Downsample(nn.Module):
135
+ """
136
+ A downsampling layer with an optional convolution.
137
+ :param channels: channels in the inputs and outputs.
138
+ :param use_conv: a bool determining if a convolution is applied.
139
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
140
+ downsampling occurs in the inner-two dimensions.
141
+ """
142
+
143
+ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
144
+ super().__init__()
145
+ self.channels = channels
146
+ self.out_channels = out_channels or channels
147
+ self.use_conv = use_conv
148
+ self.dims = dims
149
+ stride = 2 if dims != 3 else (1, 2, 2)
150
+ if use_conv:
151
+ self.op = conv_nd(
152
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
153
+ )
154
+ else:
155
+ assert self.channels == self.out_channels
156
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
157
+
158
+ def forward(self, x):
159
+ assert x.shape[1] == self.channels
160
+ return self.op(x)
161
+
162
+
163
+ class ResBlock(TimestepBlock):
164
+ """
165
+ A residual block that can optionally change the number of channels.
166
+ :param channels: the number of input channels.
167
+ :param emb_channels: the number of timestep embedding channels.
168
+ :param dropout: the rate of dropout.
169
+ :param out_channels: if specified, the number of out channels.
170
+ :param use_conv: if True and out_channels is specified, use a spatial
171
+ convolution instead of a smaller 1x1 convolution to change the
172
+ channels in the skip connection.
173
+ :param dims: determines if the signal is 1D, 2D, or 3D.
174
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
175
+ :param up: if True, use this block for upsampling.
176
+ :param down: if True, use this block for downsampling.
177
+ """
178
+
179
+ def __init__(
180
+ self,
181
+ channels,
182
+ emb_channels,
183
+ dropout,
184
+ out_channels=None,
185
+ use_conv=False,
186
+ use_scale_shift_norm=False,
187
+ dims=2,
188
+ use_checkpoint=False,
189
+ up=False,
190
+ down=False,
191
+ ):
192
+ super().__init__()
193
+ self.channels = channels
194
+ self.emb_channels = emb_channels
195
+ self.dropout = dropout
196
+ self.out_channels = out_channels or channels
197
+ self.use_conv = use_conv
198
+ self.use_checkpoint = use_checkpoint
199
+ self.use_scale_shift_norm = use_scale_shift_norm
200
+
201
+ self.in_layers = nn.Sequential(
202
+ normalization(channels),
203
+ nn.SiLU(),
204
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
205
+ )
206
+
207
+ self.updown = up or down
208
+
209
+ if up:
210
+ self.h_upd = Upsample(channels, False, dims)
211
+ self.x_upd = Upsample(channels, False, dims)
212
+ elif down:
213
+ self.h_upd = Downsample(channels, False, dims)
214
+ self.x_upd = Downsample(channels, False, dims)
215
+ else:
216
+ self.h_upd = self.x_upd = nn.Identity()
217
+
218
+ self.emb_layers = nn.Sequential(
219
+ nn.SiLU(),
220
+ linear(
221
+ emb_channels,
222
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
223
+ ),
224
+ )
225
+ self.out_layers = nn.Sequential(
226
+ normalization(self.out_channels),
227
+ nn.SiLU(),
228
+ nn.Dropout(p=dropout),
229
+ zero_module(
230
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
231
+ ),
232
+ )
233
+
234
+ if self.out_channels == channels:
235
+ self.skip_connection = nn.Identity()
236
+ elif use_conv:
237
+ self.skip_connection = conv_nd(
238
+ dims, channels, self.out_channels, 3, padding=1
239
+ )
240
+ else:
241
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
242
+
243
+ def forward(self, x, emb):
244
+ """
245
+ Apply the block to a Tensor, conditioned on a timestep embedding.
246
+ :param x: an [N x C x ...] Tensor of features.
247
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
248
+ :return: an [N x C x ...] Tensor of outputs.
249
+ """
250
+ return checkpoint(
251
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
252
+ )
253
+
254
+
255
+ def _forward(self, x, emb):
256
+ if self.updown:
257
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
258
+ h = in_rest(x)
259
+ h = self.h_upd(h)
260
+ x = self.x_upd(x)
261
+ h = in_conv(h)
262
+ else:
263
+ h = self.in_layers(x)
264
+ emb_out = self.emb_layers(emb).type(h.dtype)
265
+ while len(emb_out.shape) < len(h.shape):
266
+ emb_out = emb_out[..., None]
267
+ if self.use_scale_shift_norm:
268
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
269
+ scale, shift = th.chunk(emb_out, 2, dim=1)
270
+ h = out_norm(h) * (1 + scale) + shift
271
+ h = out_rest(h)
272
+ else:
273
+ h = h + emb_out
274
+ h = self.out_layers(h)
275
+ return self.skip_connection(x) + h
276
+
277
+
278
+ class AttentionBlock(nn.Module):
279
+ """
280
+ An attention block that allows spatial positions to attend to each other.
281
+ Originally ported from here, but adapted to the N-d case.
282
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
283
+ """
284
+
285
+ def __init__(
286
+ self,
287
+ channels,
288
+ num_heads=1,
289
+ num_head_channels=-1,
290
+ use_checkpoint=False,
291
+ use_new_attention_order=False,
292
+ ):
293
+ super().__init__()
294
+ self.channels = channels
295
+ if num_head_channels == -1:
296
+ self.num_heads = num_heads
297
+ else:
298
+ assert (
299
+ channels % num_head_channels == 0
300
+ ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
301
+ self.num_heads = channels // num_head_channels
302
+ self.use_checkpoint = use_checkpoint
303
+ self.norm = normalization(channels)
304
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
305
+ if use_new_attention_order:
306
+ # split qkv before split heads
307
+ self.attention = QKVAttention(self.num_heads)
308
+ else:
309
+ # split heads before split qkv
310
+ self.attention = QKVAttentionLegacy(self.num_heads)
311
+
312
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
313
+
314
+ def forward(self, x):
315
+ return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
316
+ #return pt_checkpoint(self._forward, x) # pytorch
317
+
318
+ def _forward(self, x):
319
+ b, c, *spatial = x.shape
320
+ x = x.reshape(b, c, -1)
321
+ qkv = self.qkv(self.norm(x))
322
+ h = self.attention(qkv)
323
+ h = self.proj_out(h)
324
+ return (x + h).reshape(b, c, *spatial)
325
+
326
+
327
+ def count_flops_attn(model, _x, y):
328
+ """
329
+ A counter for the `thop` package to count the operations in an
330
+ attention operation.
331
+ Meant to be used like:
332
+ macs, params = thop.profile(
333
+ model,
334
+ inputs=(inputs, timestamps),
335
+ custom_ops={QKVAttention: QKVAttention.count_flops},
336
+ )
337
+ """
338
+ b, c, *spatial = y[0].shape
339
+ num_spatial = int(np.prod(spatial))
340
+ # We perform two matmuls with the same number of ops.
341
+ # The first computes the weight matrix, the second computes
342
+ # the combination of the value vectors.
343
+ matmul_ops = 2 * b * (num_spatial ** 2) * c
344
+ model.total_ops += th.DoubleTensor([matmul_ops])
345
+
346
+
347
+ class QKVAttentionLegacy(nn.Module):
348
+ """
349
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
350
+ """
351
+
352
+ def __init__(self, n_heads):
353
+ super().__init__()
354
+ self.n_heads = n_heads
355
+
356
+ def forward(self, qkv):
357
+ """
358
+ Apply QKV attention.
359
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
360
+ :return: an [N x (H * C) x T] tensor after attention.
361
+ """
362
+ bs, width, length = qkv.shape
363
+ assert width % (3 * self.n_heads) == 0
364
+ ch = width // (3 * self.n_heads)
365
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
366
+ scale = 1 / math.sqrt(math.sqrt(ch))
367
+ weight = th.einsum(
368
+ "bct,bcs->bts", q * scale, k * scale
369
+ ) # More stable with f16 than dividing afterwards
370
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
371
+ a = th.einsum("bts,bcs->bct", weight, v)
372
+ return a.reshape(bs, -1, length)
373
+
374
+ @staticmethod
375
+ def count_flops(model, _x, y):
376
+ return count_flops_attn(model, _x, y)
377
+
378
+
379
+ class QKVAttention(nn.Module):
380
+ """
381
+ A module which performs QKV attention and splits in a different order.
382
+ """
383
+
384
+ def __init__(self, n_heads):
385
+ super().__init__()
386
+ self.n_heads = n_heads
387
+
388
+ def forward(self, qkv):
389
+ """
390
+ Apply QKV attention.
391
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
392
+ :return: an [N x (H * C) x T] tensor after attention.
393
+ """
394
+ bs, width, length = qkv.shape
395
+ assert width % (3 * self.n_heads) == 0
396
+ ch = width // (3 * self.n_heads)
397
+ q, k, v = qkv.chunk(3, dim=1)
398
+ scale = 1 / math.sqrt(math.sqrt(ch))
399
+ weight = th.einsum(
400
+ "bct,bcs->bts",
401
+ (q * scale).view(bs * self.n_heads, ch, length),
402
+ (k * scale).view(bs * self.n_heads, ch, length),
403
+ ) # More stable with f16 than dividing afterwards
404
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
405
+ a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
406
+ return a.reshape(bs, -1, length)
407
+
408
+ @staticmethod
409
+ def count_flops(model, _x, y):
410
+ return count_flops_attn(model, _x, y)
411
+
412
+
413
+ class UNetModel(nn.Module):
414
+ """
415
+ The full UNet model with attention and timestep embedding.
416
+ :param in_channels: channels in the input Tensor.
417
+ :param model_channels: base channel count for the model.
418
+ :param out_channels: channels in the output Tensor.
419
+ :param num_res_blocks: number of residual blocks per downsample.
420
+ :param attention_resolutions: a collection of downsample rates at which
421
+ attention will take place. May be a set, list, or tuple.
422
+ For example, if this contains 4, then at 4x downsampling, attention
423
+ will be used.
424
+ :param dropout: the dropout probability.
425
+ :param channel_mult: channel multiplier for each level of the UNet.
426
+ :param conv_resample: if True, use learned convolutions for upsampling and
427
+ downsampling.
428
+ :param dims: determines if the signal is 1D, 2D, or 3D.
429
+ :param num_classes: if specified (as an int), then this model will be
430
+ class-conditional with `num_classes` classes.
431
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
432
+ :param num_heads: the number of attention heads in each attention layer.
433
+ :param num_heads_channels: if specified, ignore num_heads and instead use
434
+ a fixed channel width per attention head.
435
+ :param num_heads_upsample: works with num_heads to set a different number
436
+ of heads for upsampling. Deprecated.
437
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
438
+ :param resblock_updown: use residual blocks for up/downsampling.
439
+ :param use_new_attention_order: use a different attention pattern for potentially
440
+ increased efficiency.
441
+ """
442
+
443
+ def __init__(
444
+ self,
445
+ image_size,
446
+ in_channels,
447
+ model_channels,
448
+ out_channels,
449
+ num_res_blocks,
450
+ attention_resolutions,
451
+ dropout=0,
452
+ channel_mult=(1, 2, 4, 8),
453
+ conv_resample=True,
454
+ dims=2,
455
+ num_classes=None,
456
+ use_checkpoint=False,
457
+ use_fp16=False,
458
+ num_heads=1,
459
+ num_head_channels=-1,
460
+ num_heads_upsample=-1,
461
+ use_scale_shift_norm=False,
462
+ resblock_updown=False,
463
+ use_new_attention_order=False,
464
+ use_spatial_transformer=False, # custom transformer support
465
+ transformer_depth=1, # custom transformer support
466
+ context_dim=None, # custom transformer support
467
+ n_embed=None # custom support for prediction of discrete ids into codebook of first stage vq model
468
+ ):
469
+ super().__init__()
470
+
471
+ if use_spatial_transformer:
472
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
473
+
474
+ if context_dim is not None:
475
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
476
+
477
+
478
+
479
+ if num_heads_upsample == -1:
480
+ num_heads_upsample = num_heads
481
+
482
+ self.image_size = image_size
483
+ self.in_channels = in_channels
484
+ self.model_channels = model_channels
485
+ self.out_channels = out_channels
486
+ self.num_res_blocks = num_res_blocks
487
+ self.attention_resolutions = attention_resolutions
488
+ self.dropout = dropout
489
+ self.channel_mult = channel_mult
490
+ self.conv_resample = conv_resample
491
+ self.num_classes = num_classes
492
+ self.use_checkpoint = use_checkpoint
493
+ self.dtype = th.float16 if use_fp16 else th.float32
494
+ self.num_heads = num_heads
495
+ self.num_head_channels = num_head_channels
496
+ self.num_heads_upsample = num_heads_upsample
497
+ self.predict_codebook_ids = n_embed is not None
498
+
499
+ time_embed_dim = model_channels * 4
500
+ self.time_embed = nn.Sequential(
501
+ linear(model_channels, time_embed_dim),
502
+ nn.SiLU(),
503
+ linear(time_embed_dim, time_embed_dim),
504
+ )
505
+
506
+ if self.num_classes is not None:
507
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
508
+
509
+ self.input_blocks = nn.ModuleList(
510
+ [
511
+ TimestepEmbedSequential(
512
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
513
+ )
514
+ ]
515
+ )
516
+ self._feature_size = model_channels
517
+ input_block_chans = [model_channels]
518
+ ch = model_channels
519
+ ds = 1
520
+ for level, mult in enumerate(channel_mult):
521
+ for _ in range(num_res_blocks):
522
+ layers = [
523
+ ResBlock(
524
+ ch,
525
+ time_embed_dim,
526
+ dropout,
527
+ out_channels=mult * model_channels,
528
+ dims=dims,
529
+ use_checkpoint=use_checkpoint,
530
+ use_scale_shift_norm=use_scale_shift_norm,
531
+ )
532
+ ]
533
+ ch = mult * model_channels
534
+ if ds in attention_resolutions:
535
+ dim_head = ch // num_heads
536
+ layers.append(
537
+ AttentionBlock(
538
+ ch,
539
+ use_checkpoint=use_checkpoint,
540
+ num_heads=num_heads,
541
+ num_head_channels=num_head_channels,
542
+ use_new_attention_order=use_new_attention_order,
543
+ ) if not use_spatial_transformer else SpatialTransformer(
544
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
545
+ )
546
+ )
547
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
548
+ self._feature_size += ch
549
+ input_block_chans.append(ch)
550
+ if level != len(channel_mult) - 1:
551
+ out_ch = ch
552
+ self.input_blocks.append(
553
+ TimestepEmbedSequential(
554
+ ResBlock(
555
+ ch,
556
+ time_embed_dim,
557
+ dropout,
558
+ out_channels=out_ch,
559
+ dims=dims,
560
+ use_checkpoint=use_checkpoint,
561
+ use_scale_shift_norm=use_scale_shift_norm,
562
+ down=True,
563
+ )
564
+ if resblock_updown
565
+ else Downsample(
566
+ ch, conv_resample, dims=dims, out_channels=out_ch
567
+ )
568
+ )
569
+ )
570
+ ch = out_ch
571
+ input_block_chans.append(ch)
572
+ ds *= 2
573
+ self._feature_size += ch
574
+
575
+ dim_head = ch // num_heads
576
+ self.middle_block = TimestepEmbedSequential(
577
+ ResBlock(
578
+ ch,
579
+ time_embed_dim,
580
+ dropout,
581
+ dims=dims,
582
+ use_checkpoint=use_checkpoint,
583
+ use_scale_shift_norm=use_scale_shift_norm,
584
+ ),
585
+ AttentionBlock(
586
+ ch,
587
+ use_checkpoint=use_checkpoint,
588
+ num_heads=num_heads,
589
+ num_head_channels=num_head_channels,
590
+ use_new_attention_order=use_new_attention_order,
591
+ ) if not use_spatial_transformer else SpatialTransformer(
592
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
593
+ ),
594
+ ResBlock(
595
+ ch,
596
+ time_embed_dim,
597
+ dropout,
598
+ dims=dims,
599
+ use_checkpoint=use_checkpoint,
600
+ use_scale_shift_norm=use_scale_shift_norm,
601
+ ),
602
+ )
603
+ self._feature_size += ch
604
+
605
+ self.output_blocks = nn.ModuleList([])
606
+ for level, mult in list(enumerate(channel_mult))[::-1]:
607
+ for i in range(num_res_blocks + 1):
608
+ ich = input_block_chans.pop()
609
+ layers = [
610
+ ResBlock(
611
+ ch + ich,
612
+ time_embed_dim,
613
+ dropout,
614
+ out_channels=model_channels * mult,
615
+ dims=dims,
616
+ use_checkpoint=use_checkpoint,
617
+ use_scale_shift_norm=use_scale_shift_norm,
618
+ )
619
+ ]
620
+ ch = model_channels * mult
621
+ if ds in attention_resolutions:
622
+ dim_head = ch // num_heads
623
+ layers.append(
624
+ AttentionBlock(
625
+ ch,
626
+ use_checkpoint=use_checkpoint,
627
+ num_heads=num_heads_upsample,
628
+ num_head_channels=num_head_channels,
629
+ use_new_attention_order=use_new_attention_order,
630
+ ) if not use_spatial_transformer else SpatialTransformer(
631
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
632
+ )
633
+ )
634
+ if level and i == num_res_blocks:
635
+ out_ch = ch
636
+ layers.append(
637
+ ResBlock(
638
+ ch,
639
+ time_embed_dim,
640
+ dropout,
641
+ out_channels=out_ch,
642
+ dims=dims,
643
+ use_checkpoint=use_checkpoint,
644
+ use_scale_shift_norm=use_scale_shift_norm,
645
+ up=True,
646
+ )
647
+ if resblock_updown
648
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
649
+ )
650
+ ds //= 2
651
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
652
+ self._feature_size += ch
653
+
654
+ self.out = nn.Sequential(
655
+ normalization(ch),
656
+ nn.SiLU(),
657
+ zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
658
+ )
659
+ if self.predict_codebook_ids:
660
+ self.id_predictor = nn.Sequential(
661
+ normalization(ch),
662
+ conv_nd(dims, model_channels, n_embed, 1),
663
+ #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
664
+ )
665
+
666
+ def convert_to_fp16(self):
667
+ """
668
+ Convert the torso of the model to float16.
669
+ """
670
+ self.input_blocks.apply(convert_module_to_f16)
671
+ self.middle_block.apply(convert_module_to_f16)
672
+ self.output_blocks.apply(convert_module_to_f16)
673
+
674
+ def convert_to_fp32(self):
675
+ """
676
+ Convert the torso of the model to float32.
677
+ """
678
+ self.input_blocks.apply(convert_module_to_f32)
679
+ self.middle_block.apply(convert_module_to_f32)
680
+ self.output_blocks.apply(convert_module_to_f32)
681
+
682
+ def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
683
+ """
684
+ Apply the model to an input batch.
685
+ :param x: an [N x C x ...] Tensor of inputs.
686
+ :param timesteps: a 1-D batch of timesteps.
687
+ :param context: conditioning plugged in via crossattn
688
+ :param y: an [N] Tensor of labels, if class-conditional.
689
+ :return: an [N x C x ...] Tensor of outputs.
690
+ """
691
+ assert (y is not None) == (
692
+ self.num_classes is not None
693
+ ), "must specify y if and only if the model is class-conditional"
694
+ assert timesteps is not None, 'need to implement no-timestep usage'
695
+ hs = []
696
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
697
+ emb = self.time_embed(t_emb)
698
+
699
+ if self.num_classes is not None:
700
+ assert y.shape == (x.shape[0],)
701
+ emb = emb + self.label_emb(y)
702
+
703
+ h = x.type(self.dtype)
704
+ for module in self.input_blocks:
705
+ h = module(h, emb, context)
706
+ hs.append(h)
707
+ h = self.middle_block(h, emb, context)
708
+ for module in self.output_blocks:
709
+ h = th.cat([h, hs.pop()], dim=1)
710
+ h = module(h, emb, context)
711
+ h = h.type(x.dtype)
712
+ if self.predict_codebook_ids:
713
+ #return self.out(h), self.id_predictor(h)
714
+ return self.id_predictor(h)
715
+ else:
716
+ return self.out(h)
717
+
718
+
719
+ class EncoderUNetModel(nn.Module):
720
+ # TODO: do we use it ?
721
+ """
722
+ The half UNet model with attention and timestep embedding.
723
+ For usage, see UNet.
724
+ """
725
+
726
+ def __init__(
727
+ self,
728
+ image_size,
729
+ in_channels,
730
+ model_channels,
731
+ out_channels,
732
+ num_res_blocks,
733
+ attention_resolutions,
734
+ dropout=0,
735
+ channel_mult=(1, 2, 4, 8),
736
+ conv_resample=True,
737
+ dims=2,
738
+ use_checkpoint=False,
739
+ use_fp16=False,
740
+ num_heads=1,
741
+ num_head_channels=-1,
742
+ num_heads_upsample=-1,
743
+ use_scale_shift_norm=False,
744
+ resblock_updown=False,
745
+ use_new_attention_order=False,
746
+ pool="adaptive",
747
+ *args,
748
+ **kwargs
749
+ ):
750
+ super().__init__()
751
+
752
+ if num_heads_upsample == -1:
753
+ num_heads_upsample = num_heads
754
+
755
+ self.in_channels = in_channels
756
+ self.model_channels = model_channels
757
+ self.out_channels = out_channels
758
+ self.num_res_blocks = num_res_blocks
759
+ self.attention_resolutions = attention_resolutions
760
+ self.dropout = dropout
761
+ self.channel_mult = channel_mult
762
+ self.conv_resample = conv_resample
763
+ self.use_checkpoint = use_checkpoint
764
+ self.dtype = th.float16 if use_fp16 else th.float32
765
+ self.num_heads = num_heads
766
+ self.num_head_channels = num_head_channels
767
+ self.num_heads_upsample = num_heads_upsample
768
+
769
+ time_embed_dim = model_channels * 4
770
+ self.time_embed = nn.Sequential(
771
+ linear(model_channels, time_embed_dim),
772
+ nn.SiLU(),
773
+ linear(time_embed_dim, time_embed_dim),
774
+ )
775
+
776
+ self.input_blocks = nn.ModuleList(
777
+ [
778
+ TimestepEmbedSequential(
779
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
780
+ )
781
+ ]
782
+ )
783
+ self._feature_size = model_channels
784
+ input_block_chans = [model_channels]
785
+ ch = model_channels
786
+ ds = 1
787
+ for level, mult in enumerate(channel_mult):
788
+ for _ in range(num_res_blocks):
789
+ layers = [
790
+ ResBlock(
791
+ ch,
792
+ time_embed_dim,
793
+ dropout,
794
+ out_channels=mult * model_channels,
795
+ dims=dims,
796
+ use_checkpoint=use_checkpoint,
797
+ use_scale_shift_norm=use_scale_shift_norm,
798
+ )
799
+ ]
800
+ ch = mult * model_channels
801
+ if ds in attention_resolutions:
802
+ layers.append(
803
+ AttentionBlock(
804
+ ch,
805
+ use_checkpoint=use_checkpoint,
806
+ num_heads=num_heads,
807
+ num_head_channels=num_head_channels,
808
+ use_new_attention_order=use_new_attention_order,
809
+ )
810
+ )
811
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
812
+ self._feature_size += ch
813
+ input_block_chans.append(ch)
814
+ if level != len(channel_mult) - 1:
815
+ out_ch = ch
816
+ self.input_blocks.append(
817
+ TimestepEmbedSequential(
818
+ ResBlock(
819
+ ch,
820
+ time_embed_dim,
821
+ dropout,
822
+ out_channels=out_ch,
823
+ dims=dims,
824
+ use_checkpoint=use_checkpoint,
825
+ use_scale_shift_norm=use_scale_shift_norm,
826
+ down=True,
827
+ )
828
+ if resblock_updown
829
+ else Downsample(
830
+ ch, conv_resample, dims=dims, out_channels=out_ch
831
+ )
832
+ )
833
+ )
834
+ ch = out_ch
835
+ input_block_chans.append(ch)
836
+ ds *= 2
837
+ self._feature_size += ch
838
+
839
+ self.middle_block = TimestepEmbedSequential(
840
+ ResBlock(
841
+ ch,
842
+ time_embed_dim,
843
+ dropout,
844
+ dims=dims,
845
+ use_checkpoint=use_checkpoint,
846
+ use_scale_shift_norm=use_scale_shift_norm,
847
+ ),
848
+ AttentionBlock(
849
+ ch,
850
+ use_checkpoint=use_checkpoint,
851
+ num_heads=num_heads,
852
+ num_head_channels=num_head_channels,
853
+ use_new_attention_order=use_new_attention_order,
854
+ ),
855
+ ResBlock(
856
+ ch,
857
+ time_embed_dim,
858
+ dropout,
859
+ dims=dims,
860
+ use_checkpoint=use_checkpoint,
861
+ use_scale_shift_norm=use_scale_shift_norm,
862
+ ),
863
+ )
864
+ self._feature_size += ch
865
+ self.pool = pool
866
+ if pool == "adaptive":
867
+ self.out = nn.Sequential(
868
+ normalization(ch),
869
+ nn.SiLU(),
870
+ nn.AdaptiveAvgPool2d((1, 1)),
871
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
872
+ nn.Flatten(),
873
+ )
874
+ elif pool == "attention":
875
+ assert num_head_channels != -1
876
+ self.out = nn.Sequential(
877
+ normalization(ch),
878
+ nn.SiLU(),
879
+ AttentionPool2d(
880
+ (image_size // ds), ch, num_head_channels, out_channels
881
+ ),
882
+ )
883
+ elif pool == "spatial":
884
+ self.out = nn.Sequential(
885
+ nn.Linear(self._feature_size, 2048),
886
+ nn.ReLU(),
887
+ nn.Linear(2048, self.out_channels),
888
+ )
889
+ elif pool == "spatial_v2":
890
+ self.out = nn.Sequential(
891
+ nn.Linear(self._feature_size, 2048),
892
+ normalization(2048),
893
+ nn.SiLU(),
894
+ nn.Linear(2048, self.out_channels),
895
+ )
896
+ else:
897
+ raise NotImplementedError(f"Unexpected {pool} pooling")
898
+
899
+ def convert_to_fp16(self):
900
+ """
901
+ Convert the torso of the model to float16.
902
+ """
903
+ self.input_blocks.apply(convert_module_to_f16)
904
+ self.middle_block.apply(convert_module_to_f16)
905
+
906
+ def convert_to_fp32(self):
907
+ """
908
+ Convert the torso of the model to float32.
909
+ """
910
+ self.input_blocks.apply(convert_module_to_f32)
911
+ self.middle_block.apply(convert_module_to_f32)
912
+
913
+ def forward(self, x, timesteps):
914
+ """
915
+ Apply the model to an input batch.
916
+ :param x: an [N x C x ...] Tensor of inputs.
917
+ :param timesteps: a 1-D batch of timesteps.
918
+ :return: an [N x K] Tensor of outputs.
919
+ """
920
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
921
+
922
+ results = []
923
+ h = x.type(self.dtype)
924
+ for module in self.input_blocks:
925
+ h = module(h, emb)
926
+ if self.pool.startswith("spatial"):
927
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
928
+ h = self.middle_block(h, emb)
929
+ if self.pool.startswith("spatial"):
930
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
931
+ h = th.cat(results, axis=-1)
932
+ return self.out(h)
933
+ else:
934
+ h = h.type(x.dtype)
935
+ return self.out(h)
936
+
ldm/modules/diffusionmodules/util.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adopted from
2
+ # https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
3
+ # and
4
+ # https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
5
+ # and
6
+ # https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
7
+ #
8
+ # thanks!
9
+
10
+
11
+ import os
12
+ import math
13
+ import torch
14
+ import torch.nn as nn
15
+ import numpy as np
16
+ from einops import repeat
17
+
18
+ from ldm.util import instantiate_from_config
19
+
20
+
21
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
22
+ if schedule == "linear":
23
+ betas = (
24
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
25
+ )
26
+
27
+ elif schedule == "cosine":
28
+ timesteps = (
29
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
30
+ )
31
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
32
+ alphas = torch.cos(alphas).pow(2)
33
+ alphas = alphas / alphas[0]
34
+ betas = 1 - alphas[1:] / alphas[:-1]
35
+ betas = np.clip(betas, a_min=0, a_max=0.999)
36
+
37
+ elif schedule == "sqrt_linear":
38
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
39
+ elif schedule == "sqrt":
40
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
41
+ else:
42
+ raise ValueError(f"schedule '{schedule}' unknown.")
43
+ return betas.numpy()
44
+
45
+
46
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
47
+ if ddim_discr_method == 'uniform':
48
+ c = num_ddpm_timesteps // num_ddim_timesteps
49
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
50
+ elif ddim_discr_method == 'quad':
51
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
52
+ else:
53
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
54
+
55
+ # assert ddim_timesteps.shape[0] == num_ddim_timesteps
56
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
57
+ steps_out = ddim_timesteps + 1
58
+ if verbose:
59
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
60
+ return steps_out
61
+
62
+
63
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
64
+ # select alphas for computing the variance schedule
65
+ alphas = alphacums[ddim_timesteps]
66
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
67
+
68
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
69
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
70
+ if verbose:
71
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
72
+ print(f'For the chosen value of eta, which is {eta}, '
73
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
74
+ return sigmas, alphas, alphas_prev
75
+
76
+
77
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
78
+ """
79
+ Create a beta schedule that discretizes the given alpha_t_bar function,
80
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
81
+ :param num_diffusion_timesteps: the number of betas to produce.
82
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
83
+ produces the cumulative product of (1-beta) up to that
84
+ part of the diffusion process.
85
+ :param max_beta: the maximum beta to use; use values lower than 1 to
86
+ prevent singularities.
87
+ """
88
+ betas = []
89
+ for i in range(num_diffusion_timesteps):
90
+ t1 = i / num_diffusion_timesteps
91
+ t2 = (i + 1) / num_diffusion_timesteps
92
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
93
+ return np.array(betas)
94
+
95
+
96
+ def extract_into_tensor(a, t, x_shape):
97
+ b, *_ = t.shape
98
+ out = a.gather(-1, t)
99
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
100
+
101
+
102
+ def checkpoint(func, inputs, params, flag):
103
+ """
104
+ Evaluate a function without caching intermediate activations, allowing for
105
+ reduced memory at the expense of extra compute in the backward pass.
106
+ :param func: the function to evaluate.
107
+ :param inputs: the argument sequence to pass to `func`.
108
+ :param params: a sequence of parameters `func` depends on but does not
109
+ explicitly take as arguments.
110
+ :param flag: if False, disable gradient checkpointing.
111
+ """
112
+ if flag:
113
+ args = tuple(inputs) + tuple(params)
114
+ return CheckpointFunction.apply(func, len(inputs), *args)
115
+ else:
116
+ return func(*inputs)
117
+
118
+
119
+ class CheckpointFunction(torch.autograd.Function):
120
+ @staticmethod
121
+ def forward(ctx, run_function, length, *args):
122
+ ctx.run_function = run_function
123
+ ctx.input_tensors = list(args[:length])
124
+ ctx.input_params = list(args[length:])
125
+
126
+ with torch.no_grad():
127
+ output_tensors = ctx.run_function(*ctx.input_tensors)
128
+ return output_tensors
129
+
130
+ @staticmethod
131
+ def backward(ctx, *output_grads):
132
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
133
+ with torch.enable_grad():
134
+ # Fixes a bug where the first op in run_function modifies the
135
+ # Tensor storage in place, which is not allowed for detach()'d
136
+ # Tensors.
137
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
138
+ output_tensors = ctx.run_function(*shallow_copies)
139
+ input_grads = torch.autograd.grad(
140
+ output_tensors,
141
+ ctx.input_tensors + ctx.input_params,
142
+ output_grads,
143
+ allow_unused=True,
144
+ )
145
+ del ctx.input_tensors
146
+ del ctx.input_params
147
+ del output_tensors
148
+ return (None, None) + input_grads
149
+
150
+
151
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
152
+ """
153
+ Create sinusoidal timestep embeddings.
154
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
155
+ These may be fractional.
156
+ :param dim: the dimension of the output.
157
+ :param max_period: controls the minimum frequency of the embeddings.
158
+ :return: an [N x dim] Tensor of positional embeddings.
159
+ """
160
+ if not repeat_only:
161
+ half = dim // 2
162
+ freqs = torch.exp(
163
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
164
+ ).to(device=timesteps.device)
165
+ args = timesteps[:, None].float() * freqs[None]
166
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
167
+ if dim % 2:
168
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
169
+ else:
170
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
171
+ return embedding
172
+
173
+
174
+ def zero_module(module):
175
+ """
176
+ Zero out the parameters of a module and return it.
177
+ """
178
+ for p in module.parameters():
179
+ p.detach().zero_()
180
+ return module
181
+
182
+
183
+ def scale_module(module, scale):
184
+ """
185
+ Scale the parameters of a module and return it.
186
+ """
187
+ for p in module.parameters():
188
+ p.detach().mul_(scale)
189
+ return module
190
+
191
+
192
+ def mean_flat(tensor):
193
+ """
194
+ Take the mean over all non-batch dimensions.
195
+ """
196
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
197
+
198
+
199
+ def normalization(channels):
200
+ """
201
+ Make a standard normalization layer.
202
+ :param channels: number of input channels.
203
+ :return: an nn.Module for normalization.
204
+ """
205
+ return GroupNorm32(32, channels)
206
+
207
+
208
+ # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
209
+ class SiLU(nn.Module):
210
+ def forward(self, x):
211
+ return x * torch.sigmoid(x)
212
+
213
+
214
+ class GroupNorm32(nn.GroupNorm):
215
+ def forward(self, x):
216
+ return super().forward(x.float()).type(x.dtype)
217
+
218
+ def conv_nd(dims, *args, **kwargs):
219
+ """
220
+ Create a 1D, 2D, or 3D convolution module.
221
+ """
222
+ if dims == 1:
223
+ return nn.Conv1d(*args, **kwargs)
224
+ elif dims == 2:
225
+ return nn.Conv2d(*args, **kwargs)
226
+ elif dims == 3:
227
+ return nn.Conv3d(*args, **kwargs)
228
+ raise ValueError(f"unsupported dimensions: {dims}")
229
+
230
+
231
+ def linear(*args, **kwargs):
232
+ """
233
+ Create a linear module.
234
+ """
235
+ return nn.Linear(*args, **kwargs)
236
+
237
+
238
+ def avg_pool_nd(dims, *args, **kwargs):
239
+ """
240
+ Create a 1D, 2D, or 3D average pooling module.
241
+ """
242
+ if dims == 1:
243
+ return nn.AvgPool1d(*args, **kwargs)
244
+ elif dims == 2:
245
+ return nn.AvgPool2d(*args, **kwargs)
246
+ elif dims == 3:
247
+ return nn.AvgPool3d(*args, **kwargs)
248
+ raise ValueError(f"unsupported dimensions: {dims}")
249
+
250
+
251
+ class HybridConditioner(nn.Module):
252
+
253
+ def __init__(self, c_concat_config, c_crossattn_config):
254
+ super().__init__()
255
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
256
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
257
+
258
+ def forward(self, c_concat, c_crossattn):
259
+ c_concat = self.concat_conditioner(c_concat)
260
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
261
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
ldm/modules/distributions/__init__.py ADDED
File without changes
ldm/modules/distributions/distributions.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ class AbstractDistribution:
6
+ def sample(self):
7
+ raise NotImplementedError()
8
+
9
+ def mode(self):
10
+ raise NotImplementedError()
11
+
12
+
13
+ class DiracDistribution(AbstractDistribution):
14
+ def __init__(self, value):
15
+ self.value = value
16
+
17
+ def sample(self):
18
+ return self.value
19
+
20
+ def mode(self):
21
+ return self.value
22
+
23
+
24
+ class DiagonalGaussianDistribution(object):
25
+ def __init__(self, parameters, deterministic=False):
26
+ self.parameters = parameters
27
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
28
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
29
+ self.deterministic = deterministic
30
+ self.std = torch.exp(0.5 * self.logvar)
31
+ self.var = torch.exp(self.logvar)
32
+ if self.deterministic:
33
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
34
+
35
+ def sample(self):
36
+ x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
37
+ return x
38
+
39
+ def kl(self, other=None):
40
+ if self.deterministic:
41
+ return torch.Tensor([0.])
42
+ else:
43
+ if other is None:
44
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
45
+ + self.var - 1.0 - self.logvar,
46
+ dim=[1, 2, 3])
47
+ else:
48
+ return 0.5 * torch.sum(
49
+ torch.pow(self.mean - other.mean, 2) / other.var
50
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
51
+ dim=[1, 2, 3])
52
+
53
+ def nll(self, sample, dims=[1,2,3]):
54
+ if self.deterministic:
55
+ return torch.Tensor([0.])
56
+ logtwopi = np.log(2.0 * np.pi)
57
+ return 0.5 * torch.sum(
58
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
59
+ dim=dims)
60
+
61
+ def mode(self):
62
+ return self.mean
63
+
64
+
65
+ def normal_kl(mean1, logvar1, mean2, logvar2):
66
+ """
67
+ source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
68
+ Compute the KL divergence between two gaussians.
69
+ Shapes are automatically broadcasted, so batches can be compared to
70
+ scalars, among other use cases.
71
+ """
72
+ tensor = None
73
+ for obj in (mean1, logvar1, mean2, logvar2):
74
+ if isinstance(obj, torch.Tensor):
75
+ tensor = obj
76
+ break
77
+ assert tensor is not None, "at least one argument must be a Tensor"
78
+
79
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
80
+ # Tensors, but it does not work for torch.exp().
81
+ logvar1, logvar2 = [
82
+ x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
83
+ for x in (logvar1, logvar2)
84
+ ]
85
+
86
+ return 0.5 * (
87
+ -1.0
88
+ + logvar2
89
+ - logvar1
90
+ + torch.exp(logvar1 - logvar2)
91
+ + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
92
+ )
ldm/modules/ema.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class LitEma(nn.Module):
6
+ def __init__(self, model, decay=0.9999, use_num_upates=True):
7
+ super().__init__()
8
+ if decay < 0.0 or decay > 1.0:
9
+ raise ValueError('Decay must be between 0 and 1')
10
+
11
+ self.m_name2s_name = {}
12
+ self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
13
+ self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates
14
+ else torch.tensor(-1,dtype=torch.int))
15
+
16
+ for name, p in model.named_parameters():
17
+ if p.requires_grad:
18
+ #remove as '.'-character is not allowed in buffers
19
+ s_name = name.replace('.','')
20
+ self.m_name2s_name.update({name:s_name})
21
+ self.register_buffer(s_name,p.clone().detach().data)
22
+
23
+ self.collected_params = []
24
+
25
+ def forward(self,model):
26
+ decay = self.decay
27
+
28
+ if self.num_updates >= 0:
29
+ self.num_updates += 1
30
+ decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))
31
+
32
+ one_minus_decay = 1.0 - decay
33
+
34
+ with torch.no_grad():
35
+ m_param = dict(model.named_parameters())
36
+ shadow_params = dict(self.named_buffers())
37
+
38
+ for key in m_param:
39
+ if m_param[key].requires_grad:
40
+ sname = self.m_name2s_name[key]
41
+ shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
42
+ shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
43
+ else:
44
+ assert not key in self.m_name2s_name
45
+
46
+ def copy_to(self, model):
47
+ m_param = dict(model.named_parameters())
48
+ shadow_params = dict(self.named_buffers())
49
+ for key in m_param:
50
+ if m_param[key].requires_grad:
51
+ m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
52
+ else:
53
+ assert not key in self.m_name2s_name
54
+
55
+ def store(self, parameters):
56
+ """
57
+ Save the current parameters for restoring later.
58
+ Args:
59
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
60
+ temporarily stored.
61
+ """
62
+ self.collected_params = [param.clone() for param in parameters]
63
+
64
+ def restore(self, parameters):
65
+ """
66
+ Restore the parameters stored with the `store` method.
67
+ Useful to validate the model with EMA parameters without affecting the
68
+ original optimization process. Store the parameters before the
69
+ `copy_to` method. After validation (or model saving), use this to
70
+ restore the former parameters.
71
+ Args:
72
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
73
+ updated with the stored parameters.
74
+ """
75
+ for c_param, param in zip(self.collected_params, parameters):
76
+ param.data.copy_(c_param.data)